Merge branch 'devel' into dev/click
Conflicts: setup.py src/octoprint/__init__.py src/octoprint/plugin/core.py src/octoprint/server/__init__.py
This commit is contained in:
commit
b326efbc3c
197 files changed
+28216
-4328
No files matched your search
@@ -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
|
||||
|
||||
+4
-1
@@ -6,4 +6,7 @@ python:
|
||||
install:
|
||||
- pip install -e .[develop]
|
||||
script:
|
||||
- nosetests tests/
|
||||
- nosetests --with-doctest
|
||||
sudo: false
|
||||
git:
|
||||
depth: 250
|
||||
+7
-4
@@ -10,10 +10,13 @@
|
||||
# master shall not use the lookup table, only tags
|
||||
master
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.2.4
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.2.8
|
||||
# so are any fix/... branches
|
||||
maintenance 1.2.4 3761995aff94acf32495556730f133a1626245b3
|
||||
fix/.* 1.2.4 3761995aff94acf32495556730f133a1626245b3
|
||||
maintenance 1.2.8 6c622f7c4332b71c6ece59552ffc87c146155c84 pep440-dev
|
||||
fix/.* 1.2.8 6c622f7c4332b71c6ece59552ffc87c146155c84 pep440-dev
|
||||
|
||||
# Special case disconnected checkouts, e.g. 'git checkout <tag>'
|
||||
\(detached.*
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
|
||||
.* 1.3.0 198d3450d94be1a2 pep440-dev
|
||||
.* 1.3.0 198d3450d94be1a2 pep440-dev
|
||||
@@ -51,6 +51,10 @@ date of first contribution):
|
||||
* [Mark Walker](https://github.com/markwal)
|
||||
* [Lucas Clemente](https://github.com/lucas-clemente)
|
||||
* [Andrew Erickson](https://github.com/aerickson)
|
||||
* [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)
|
||||
|
||||
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
|
||||
|
||||
+231
-1
@@ -2,6 +2,19 @@
|
||||
|
||||
## 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
|
||||
@@ -11,11 +24,228 @@
|
||||
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.7 (2015-10-20)
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#1062](https://github.com/foosel/OctoPrint/issues/1062) - Plugin Manager
|
||||
now has a configuration dialog that among other things allows defining the
|
||||
used `pip` command if auto detection proves to be insufficient here.
|
||||
* Allow defining additional `pip` parameters in Plugin Manager. That might
|
||||
make `sudo`-less installation of plugins possible in situations where it's
|
||||
tricky otherwise.
|
||||
* Improved timelapse processing (backported from `devel` branch):
|
||||
* Individually captured frames cannot "overtake" each other anymore through
|
||||
usage of a capture queue.
|
||||
* Notifications will now be shown when the capturing of the timelapse's
|
||||
post roll happens, including an approximation of how long that will take.
|
||||
* Usage of `requests` instead of `urllib` for fetching the snapshot,
|
||||
appears to also have [positive effects on webcam compatibility](https://github.com/foosel/OctoPrint/issues/1078).
|
||||
* Some more defensive escaping for various settings in the UI (e.g. webcam URL)
|
||||
* Switch to more error resilient saving of configuration files and other files
|
||||
modified during runtime (save to temporary file & move). Should reduce risk
|
||||
of file corruption.
|
||||
* Downloading GCODE and STL files should now set more fitting `Content-Type`
|
||||
headers (`text/plain` and `application/sla`) for better client side support
|
||||
for "Open with" like usage scenarios.
|
||||
* Selecting z-triggered timelapse mode will now inform about that not working
|
||||
when printing from SD card.
|
||||
* Software Update Plugin: Removed "The web interface will now be reloaded"
|
||||
notification after successful update since that became obsolete with
|
||||
introduction of the "Reload Now" overlay.
|
||||
* Updated required version of `psutil` and `netifaces` dependencies.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#1057](https://github.com/foosel/OctoPrint/issues/1057) - Better error
|
||||
resilience of the Software Update plugin against broken/incomplete update
|
||||
configurations.
|
||||
* [#1075](https://github.com/foosel/OctoPrint/issues/1075) - Fixed support
|
||||
of `sudo` for installing plugins, but added big visible warning about it
|
||||
as it's **not** recommended.
|
||||
* [#1077](https://github.com/foosel/OctoPrint/issues/1077) - Do not hiccup
|
||||
on [UTF-8 BOMs](https://en.wikipedia.org/wiki/Byte_order_mark) (or other
|
||||
BOMs for that matter) at the beginning of GCODE files.
|
||||
* Fixed an issue that caused user sessions to not be properly associated,
|
||||
leading to Sessions getting duplicated, wrongly saved etc.
|
||||
* Fixed internal server error (HTTP 500) response on REST API calls with
|
||||
unset `Content-Type` header.
|
||||
* Fixed an issue leading to drag-and-drop file uploads to trigger frontend
|
||||
processing in various other file upload widgets.
|
||||
* Fixed a documentation error.
|
||||
* Fixed caching behaviour on GCODE/STL downloads, was setting the `ETag`
|
||||
header improperly.
|
||||
* Fixed GCODE viewer not properly detecting change of currently visualized
|
||||
file on Windows systems.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.6...1.2.7))
|
||||
|
||||
## 1.2.6 (2015-09-02)
|
||||
|
||||
### Improvements
|
||||
|
||||
* Added support for version reporting on detached checkouts
|
||||
(see [#1041](https://github.com/foosel/OctoPrint/pull/1041))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Pinned requirement for [psutil](https://pypi.python.org/pypi/psutil)
|
||||
dependency to version 3.1.1 of that library due to an issue when
|
||||
installing version 3.2.0 of that library released on 2015-09-02 through
|
||||
a `python setup.py install` on OctoPrint. Also pinned all other requirements
|
||||
to definitive versions that definitely work while at it to keep that from
|
||||
happening again.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.5...1.2.6))
|
||||
|
||||
## 1.2.5 (2015-08-31)
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#986](https://github.com/foosel/OctoPrint/issues/986) - Added tooltip for
|
||||
"additional data" button in file list.
|
||||
* [#1028](https://github.com/foosel/OctoPrint/issues/1028) - Hint about why
|
||||
timelapse configuration is disabled.
|
||||
* 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.
|
||||
* Settings dialog now visualizes when settings are saving and when they being
|
||||
retrieved. Also the Send/Cancel buttons are disabled while settings are saving
|
||||
to prevent duplicated requests and concurrent retrieval of the settings by
|
||||
multiple viewmodels is disabled as well.
|
||||
* Better protection against rendering errors from templates provided by third
|
||||
party plugins.
|
||||
* Better protection against corrupting the configuration by using a temporary
|
||||
file as intermediate buffer.
|
||||
* Added warning to UI regarding Z timelapses and spiralized objects.
|
||||
* Better compatibility with Repetier firmware:
|
||||
* Added "Format Error" to whitelisted recoverable communication errors
|
||||
(see also [#1032](https://github.com/foosel/OctoPrint/pull/1032)).
|
||||
* Added option to ignore repeated resend requests for the same line (see
|
||||
also discussion in [#1015](https://github.com/foosel/OctoPrint/pull/1015)).
|
||||
* Software Update Plugin:
|
||||
* Adjusted to utilize new centralized restart commands (see above).
|
||||
* Allow configuration of checkout folder and version tracking type via
|
||||
Plugin Configuration.
|
||||
* Display message to user if OctoPrint's checkout folder is not configured
|
||||
or a non-release version is running and version tracking against releases
|
||||
is enabled.
|
||||
* Clear version cache when a change in the check configuration is detected.
|
||||
* Mark check configurations for which an update is not possible.
|
||||
* Made disk space running low a bit more obvious through visual warning on
|
||||
configurable thresholds.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#985](https://github.com/foosel/OctoPrint/issues/985) - Do not hiccup on
|
||||
unset `Content-Type` part headers for multipart file uploads.
|
||||
* [#1001](https://github.com/foosel/OctoPrint/issues/1001) - Fixed connection
|
||||
tab not unfolding properly (see also [#1002](https://github.com/foosel/OctoPrint/pull/1002)).
|
||||
* [#1012](https://github.com/foosel/OctoPrint/issues/1012) - All API
|
||||
responses now set no-cache headers, making the Edge browser behave a bit better
|
||||
* [#1019](https://github.com/foosel/OctoPrint/issues/1019) - Better error
|
||||
handling of problems when trying to write the webassets cache.
|
||||
* [#1021](https://github.com/foosel/OctoPrint/issues/1021) - Properly handle
|
||||
serial close on Macs.
|
||||
* [#1031](https://github.com/foosel/OctoPrint/issues/1031) - Special
|
||||
handling of `M112` (emergency stop) command:
|
||||
* Jump send queue
|
||||
* In case the printer's firmware doesn't understand it yet, at least
|
||||
shutdown all of the heaters
|
||||
* Disconnect
|
||||
* Properly reset job progress to 0% when restarting a previously completed
|
||||
printjob (see [#998](https://github.com/foosel/OctoPrint/pull/998)).
|
||||
* Report an update as failed if the `pip` command returns a return code that
|
||||
indicates failure.
|
||||
* Fixed sorting of templates: could only be sorted by name, individual
|
||||
configurations were ignored (see [#1022](https://github.com/foosel/OctoPrint/pull/1022)).
|
||||
* Fixed positioning of custom context menus: were offset due to changes in
|
||||
overall positioning settings (see [#1023](https://github.com/foosel/OctoPrint/pull/1023)).
|
||||
* Software Update: Don't use display version for comparison of git commit
|
||||
hashs.
|
||||
* Fixed temperature parsing for multi extruder setups.
|
||||
* Fixed nested vertical and horizontal custom control layouts.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.4...1.2.5))
|
||||
|
||||
## 1.2.4 (2015-07-23)
|
||||
|
||||
### Improvements
|
||||
|
||||
* `RepeatedTimer` now defaults to `daemon` set to `True`. This makes sure
|
||||
plugins using it don't have to remember to set that flag themselves in
|
||||
order for the server to properly shut down when timers are still active.
|
||||
* Fixed a typo in the docs about `logging.yaml` (top level element is
|
||||
`loggers`, not `logger`).
|
||||
* Support for plugins with external dependencies (`dependency_links` in
|
||||
setuptools), interesting for plugin authors who need to depend on Python
|
||||
libraries that are (not yet) available on PyPI.
|
||||
* Better resilience against errors within plugins.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Do not cache web page when running for the first time, to avoid caching
|
||||
the first run dialog popup along side with it. This should solve issues
|
||||
people were having when configuring OctoPrint for the first time, then
|
||||
reloading the page without clearing the cache, being again prompted with
|
||||
the dialog with no chance to clear it.
|
||||
* Fix/workaround for occasional white panes in settings dialog on Safari 8,
|
||||
which appears to have an issue with fixed positioning.
|
||||
* Fixed form field truncation in upload requests that could lead to problems
|
||||
when trying to import Cura profiles with names longer than 28 characters.
|
||||
* Fixed webcam rotation for timelapse rendering.
|
||||
* Fixed user settings not reaching the editor in the frontend.
|
||||
* Notifications that are in process of being closed don't open again on
|
||||
mouse over (that was actually more of an unwanted feature).
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.3...1.2.4))
|
||||
|
||||
## 1.2.3 (2015-07-09)
|
||||
|
||||
@@ -225,7 +455,7 @@
|
||||
changed under "Temperatures" in the Settings ([#343](https://github.com/foosel/OctoPrint/issues/343)).
|
||||
* High-DPI support for the GCode viewer ([#837](https://github.com/foosel/OctoPrint/issues/837)).
|
||||
* Stop websocket connections from multiplying ([#888](https://github.com/foosel/OctoPrint/pull/888)).
|
||||
* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and
|
||||
* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and
|
||||
[#906](https://github.com/foosel/OctoPrint/pull/906))
|
||||
* System commands now be set to a) run asynchronized by setting their `async` property to `true` and b) to ignore their
|
||||
result by setting their `ignore` property to `true`.
|
||||
|
||||
@@ -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
|
||||
@@ -1,26 +1,68 @@
|
||||
OctoPrint
|
||||
=========
|
||||
|
||||
[](https://flattr.com/submit/auto?user_id=foosel&url=https://github.com/foosel/OctoPrint&title=OctoPrint&language=&tags=github&category=software)
|
||||
|
||||
OctoPrint provides a responsive web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
|
||||
OctoPrint provides a snappy web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
|
||||
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
|
||||
|
||||
Its website can be found at [octoprint.org](http://octoprint.org).
|
||||
|
||||
The documentation is located at [docs.octoprint.org](http://docs.octoprint.org).
|
||||
|
||||
The official plugin repository can be reached at [plugins.octoprint.org](http://plugins.octoprint.org).
|
||||
|
||||

|
||||
|
||||
You are currently looking at the source code repository of OctoPrint. If you already installed it
|
||||
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
|
||||
want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki)
|
||||
might be of more interest for you. You might also want to subscribe to [the mailing list](https://groups.google.com/group/octoprint)
|
||||
or the [G+ Community](https://plus.google.com/communities/102771308349328485741) where there are other active users who might be
|
||||
able to help you with any questions you might have.
|
||||
|
||||
Contributing
|
||||
------------
|
||||
|
||||
Please see the project's [Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
|
||||
Contributions of all kinds are welcome, not only in the form of code but also with regards to the
|
||||
[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), support
|
||||
of other users in the [bug tracker](https://github.com/foosel/OctoPrint/issues),
|
||||
[the Mailinglist](https://groups.google.com/group/octoprint) or
|
||||
[the G+ Community](https://plus.google.com/communities/102771308349328485741).
|
||||
|
||||
If you think something is bad as it is about OctoPrint or its documentation the way it is, please help
|
||||
in any way to make it better instead of just complaining about it -- this is an Open Source Project
|
||||
after all :)
|
||||
|
||||
For information about how to go about contributions of any kind, please see the project's
|
||||
[Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
Installation instructions for installing from source for different operating systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
|
||||
Installation instructions for installing from source for different operating
|
||||
systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
|
||||
|
||||
If you want to run OctoPrint on a Raspberry Pi you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi)
|
||||
which is a custom SD card image that includes OctoPrint plus dependencies.
|
||||
|
||||
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:
|
||||
|
||||
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`
|
||||
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)
|
||||
for details.
|
||||
|
||||
After installation, please make sure you follow the first-run wizard and set up
|
||||
access control as necessary. If you want to not only be notified about new
|
||||
releases but also be able to automatically upgrade to them from within
|
||||
OctoPrint, take a look [at the documentation of the Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update#making-octoprint-updateable-on-existing-installations)
|
||||
and at its settings.
|
||||
|
||||
Dependencies
|
||||
------------
|
||||
|
||||
@@ -36,7 +78,11 @@ OctoPrint currently only supports Python 2.7.
|
||||
Usage
|
||||
-----
|
||||
|
||||
Running the `setup.py` script installs the `octoprint` script in your Python installation's scripts folder
|
||||
Running the `setup.py` script via
|
||||
|
||||
python setup.py install
|
||||
|
||||
installs the `octoprint` script in your Python installation's scripts folder
|
||||
(which depending on whether you installed OctoPrint globally or into a virtual env will be on your `PATH` or not). The
|
||||
following usage examples assume that said `octoprint` script is on your `PATH`.
|
||||
|
||||
@@ -77,5 +123,13 @@ which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows
|
||||
at `~/Library/Application Support/OctoPrint` on MacOS.
|
||||
|
||||
A comprehensive overview of all available configuration settings can be found
|
||||
[on the wiki](https://github.com/foosel/OctoPrint/wiki/Configuration). Please note that the most commonly used
|
||||
configuration settings can also easily be edited from OctoPrint's settings dialog.
|
||||
[in the docs](http://docs.octoprint.org/en/master/configuration/config_yaml.html).
|
||||
Please note that the most commonly used configuration settings can also easily
|
||||
be edited from OctoPrint's settings dialog.
|
||||
|
||||
Special Thanks
|
||||
--------------
|
||||
|
||||
The development of OctoPrint is sponsored and maintained by [BQ](http://www.bq.com/).
|
||||
Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/).
|
||||
Profiling is done with the help of [PyVmMonitor](http://www.pyvmmonitor.com).
|
||||
@@ -0,0 +1,54 @@
|
||||
# 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
|
||||
|
||||
* [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
|
||||
+4
-4
@@ -37,7 +37,7 @@ Issue a job command
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
POST /api/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
@@ -54,7 +54,7 @@ Issue a job command
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
POST /api/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
@@ -71,7 +71,7 @@ Issue a job command
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
POST /api/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
@@ -88,7 +88,7 @@ Issue a job command
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
POST /api/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ Log file management
|
||||
Retrieve a list of available log files
|
||||
======================================
|
||||
|
||||
.. http:post:: /api/logs
|
||||
.. http:get:: /api/logs
|
||||
|
||||
Retrieve information regarding all log files currently available and regarding the disk space still available
|
||||
in the system on the location the log files are being stored.
|
||||
|
||||
@@ -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
|
||||
@@ -621,7 +647,8 @@ Use the following settings to configure the server:
|
||||
.. code-block:: yaml
|
||||
|
||||
server:
|
||||
# Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all interfaces)
|
||||
# Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all
|
||||
# interfaces)
|
||||
host: 0.0.0.0
|
||||
|
||||
# Use this option to define the port to which to bind the server, defaults to 5000
|
||||
@@ -691,6 +718,18 @@ Use the following settings to configure the server:
|
||||
# Maximum size of requests other than file uploads in bytes, defaults to 100KB.
|
||||
maxSize: 102400
|
||||
|
||||
# Commands to restart/shutdown octoprint or the system it's running on
|
||||
commands:
|
||||
|
||||
# Command to restart OctoPrint, defaults to being unset
|
||||
serverRestartCommand: sudo service octoprint restart
|
||||
|
||||
# Command to restart the system OctoPrint is running on, defaults to being unset
|
||||
systemRestartCommand: sudo shutdown -r now
|
||||
|
||||
# Command to shut down the system OctoPrint is running on, defaults to being unset
|
||||
systemShutdownCommand: sudo shutdown -h now
|
||||
|
||||
|
||||
.. note::
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ Changing log levels
|
||||
If you need to change the default logging level within OctoPrint, create the file with a text editor of your choice
|
||||
(it's usually not there). The general format is this::
|
||||
|
||||
logger:
|
||||
loggers:
|
||||
<component>:
|
||||
level: <loglevel>
|
||||
|
||||
@@ -27,7 +27,7 @@ new log level to set. An example for increasing the log level of the events and
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
logger:
|
||||
loggers:
|
||||
octoprint.events:
|
||||
level: DEBUG
|
||||
octoprint.filemanager:
|
||||
@@ -97,4 +97,4 @@ expressed in YAML as follows:
|
||||
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
|
||||
The possible keys for the logging format can be found in the
|
||||
`Python documentation on LogRecord attributes <https://docs.python.org/2/library/logging.html#logrecord-attributes>`_.
|
||||
`Python documentation on LogRecord attributes <https://docs.python.org/2/library/logging.html#logrecord-attributes>`_.
|
||||
@@ -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
|
||||
-------------
|
||||
|
||||
|
||||
@@ -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>`.
|
||||
|
||||
@@ -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::
|
||||
|
||||
|
||||
@@ -159,6 +159,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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,4 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python2
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -133,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
|
||||
@@ -152,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
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
|
||||
# See the docstring in versioneer.py for instructions. Note that you must
|
||||
# re-run 'versioneer.py setup' after changing this section, and commit the
|
||||
# resulting files.
|
||||
[metadata]
|
||||
description-file = README.md
|
||||
|
||||
[versioneer]
|
||||
VCS = git
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -15,23 +16,25 @@ import octoprint_setuptools
|
||||
INSTALL_REQUIRES = [
|
||||
"flask>=0.9,<0.11",
|
||||
"werkzeug==0.8.3",
|
||||
"tornado==4.0.1",
|
||||
"sockjs-tornado>=1.0.0",
|
||||
"tornado==4.0.2",
|
||||
"sockjs-tornado==1.0.2",
|
||||
"PyYAML==3.10",
|
||||
"Flask-Login==0.2.2",
|
||||
"Flask-Principal==0.3.5",
|
||||
"Flask-Babel==0.9",
|
||||
"Flask-Assets==0.10",
|
||||
"pyserial",
|
||||
"netaddr",
|
||||
"watchdog",
|
||||
"sarge>=0.1.4",
|
||||
"netifaces",
|
||||
"pylru",
|
||||
"rsa",
|
||||
"pkginfo",
|
||||
"requests",
|
||||
"semantic_version",
|
||||
"Flask-Markdown==0.3",
|
||||
"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",
|
||||
"Click"
|
||||
]
|
||||
|
||||
@@ -47,7 +50,10 @@ EXTRA_REQUIRES = dict(
|
||||
# Documentation dependencies
|
||||
"sphinx>=1.3",
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinx_rtd_theme"
|
||||
"sphinx_rtd_theme",
|
||||
|
||||
# PyPi upload related
|
||||
"pypandoc"
|
||||
],
|
||||
|
||||
# Dependencies for developing OctoPrint plugins
|
||||
@@ -56,12 +62,41 @@ EXTRA_REQUIRES = dict(
|
||||
]
|
||||
)
|
||||
|
||||
# Additional requirements for setup
|
||||
SETUP_REQUIRES = []
|
||||
|
||||
# Dependency links for any of the aforementioned dependencies
|
||||
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()
|
||||
|
||||
@@ -74,6 +109,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
|
||||
|
||||
|
||||
@@ -82,8 +125,22 @@ def params():
|
||||
version = versioneer.get_version()
|
||||
cmdclass = get_cmdclass()
|
||||
|
||||
description = "A responsive web interface for 3D printers"
|
||||
description = "A snappy web interface for 3D printers"
|
||||
long_description = open("README.md").read()
|
||||
|
||||
install_requires = INSTALL_REQUIRES
|
||||
extras_require = EXTRA_REQUIRES
|
||||
dependency_links = DEPENDENCY_LINKS
|
||||
setup_requires = SETUP_REQUIRES
|
||||
|
||||
try:
|
||||
import pypandoc
|
||||
setup_requires += ["setuptools-markdown"]
|
||||
long_description_markdown_filename = "README.md"
|
||||
del pypandoc
|
||||
except:
|
||||
pass
|
||||
|
||||
classifiers = [
|
||||
"Development Status :: 4 - Beta",
|
||||
"Environment :: Web Environment",
|
||||
@@ -110,17 +167,16 @@ 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
|
||||
zip_safe = False
|
||||
install_requires = INSTALL_REQUIRES
|
||||
extras_require = EXTRA_REQUIRES
|
||||
dependency_links = DEPENDENCY_LINKS
|
||||
|
||||
if os.environ.get('READTHEDOCS', None) == 'True':
|
||||
# we can't tell read the docs to please perform a pip install -e .[develop], so we help
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#!/usr/bin/env python2
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, print_function
|
||||
|
||||
__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 sys
|
||||
import click
|
||||
|
||||
|
||||
@@ -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"
|
||||
@@ -74,6 +79,9 @@ class Events(object):
|
||||
# Timelapse
|
||||
CAPTURE_START = "CaptureStart"
|
||||
CAPTURE_DONE = "CaptureDone"
|
||||
CAPTURE_FAILED = "CaptureFailed"
|
||||
POSTROLL_START = "PostRollStart"
|
||||
POSTROLL_END = "PostRollEnd"
|
||||
MOVIE_RENDERING = "MovieRendering"
|
||||
MOVIE_DONE = "MovieDone"
|
||||
MOVIE_FAILED = "MovieFailed"
|
||||
|
||||
@@ -18,6 +18,11 @@ from .analysis import QueueEntry, AnalysisQueue
|
||||
from .storage import LocalFileStorage
|
||||
from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
|
||||
ContentTypeDetector = namedtuple("ContentTypeDetector", "extensions, detector")
|
||||
|
||||
extensions = dict(
|
||||
)
|
||||
|
||||
@@ -25,11 +30,11 @@ def full_extension_tree():
|
||||
result = dict(
|
||||
# extensions for 3d model files
|
||||
model=dict(
|
||||
stl=["stl"]
|
||||
stl=ContentTypeMapping(["stl"], "application/sla")
|
||||
),
|
||||
# extensions for printable machine code
|
||||
machinecode=dict(
|
||||
gcode=["gcode", "gco", "g"]
|
||||
gcode=ContentTypeMapping(["gcode", "gco", "g"], "text/plain")
|
||||
)
|
||||
)
|
||||
|
||||
@@ -68,8 +73,12 @@ def get_all_extensions(subtree=None):
|
||||
for key, value in subtree.items():
|
||||
if isinstance(value, dict):
|
||||
result += get_all_extensions(value)
|
||||
elif isinstance(value, (ContentTypeMapping, ContentTypeDetector)):
|
||||
result += value.extensions
|
||||
elif isinstance(value, (list, tuple)):
|
||||
result += value
|
||||
elif isinstance(subtree, (ContentTypeMapping, ContentTypeDetector)):
|
||||
result = subtree.extensions
|
||||
elif isinstance(subtree, (list, tuple)):
|
||||
result = subtree
|
||||
return result
|
||||
@@ -79,7 +88,9 @@ def get_path_for_extension(extension, subtree=None):
|
||||
subtree = full_extension_tree()
|
||||
|
||||
for key, value in subtree.items():
|
||||
if isinstance(value, (list, tuple)) and extension in value:
|
||||
if isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions:
|
||||
return [key]
|
||||
elif isinstance(value, (list, tuple)) and extension in value:
|
||||
return [key]
|
||||
elif isinstance(value, dict):
|
||||
path = get_path_for_extension(extension, subtree=value)
|
||||
@@ -88,6 +99,23 @@ def get_path_for_extension(extension, subtree=None):
|
||||
|
||||
return None
|
||||
|
||||
def get_content_type_mapping_for_extension(extension, subtree=None):
|
||||
if not subtree:
|
||||
subtree = full_extension_tree()
|
||||
|
||||
for key, value in subtree.items():
|
||||
content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value. extensions
|
||||
list_extension_matches = isinstance(value, (list, tuple)) and extension in value
|
||||
|
||||
if content_extension_matches or list_extension_matches:
|
||||
return value
|
||||
elif isinstance(value, dict):
|
||||
result = get_content_type_mapping_for_extension(extension, subtree=value)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
return None
|
||||
|
||||
def valid_extension(extension, type=None):
|
||||
if not type:
|
||||
return extension in get_all_extensions()
|
||||
@@ -106,6 +134,19 @@ def get_file_type(filename):
|
||||
extension = extension[1:].lower()
|
||||
return get_path_for_extension(extension)
|
||||
|
||||
def get_mime_type(filename):
|
||||
_, extension = os.path.splitext(filename)
|
||||
extension = extension[1:].lower()
|
||||
mapping = get_content_type_mapping_for_extension(extension)
|
||||
if mapping:
|
||||
if isinstance(mapping, ContentTypeMapping) and mapping.content_type is not None:
|
||||
return mapping.content_type
|
||||
elif isinstance(mapping, ContentTypeDetector) and callable(mapping.detector):
|
||||
result = mapping.detector(filename)
|
||||
if result is not None:
|
||||
return result
|
||||
return "application/octet-stream"
|
||||
|
||||
|
||||
class NoSuchStorage(Exception):
|
||||
pass
|
||||
@@ -155,7 +196,11 @@ class FileManager(object):
|
||||
self._slicing_progress_callbacks.append(callback)
|
||||
|
||||
def unregister_slicingprogress_callback(self, callback):
|
||||
self._slicing_progress_callbacks.remove(callback)
|
||||
try:
|
||||
self._slicing_progress_callbacks.remove(callback)
|
||||
except ValueError:
|
||||
# callback was not registered
|
||||
pass
|
||||
|
||||
def _determine_analysis_backlog(self, storage_type, storage_manager):
|
||||
counter = 0
|
||||
|
||||
@@ -584,24 +584,6 @@ class LocalFileStorage(StorageInterface):
|
||||
Note that for a ``path`` without a trailing slash the last part will be considered a file name and
|
||||
hence be returned at second position. If you only need to convert a folder path, be sure to
|
||||
include a trailing slash for a string ``path`` or an empty last element for a list ``path``.
|
||||
|
||||
Examples::
|
||||
|
||||
>>> storage = LocalFileStorage("/some/base/folder")
|
||||
>>> storage.sanitize("some/folder/and/some file.gco")
|
||||
("/some/base/folder/some/folder/and", "some_file.gco")
|
||||
>>> storage.sanitize(("some", "folder", "and", "some file.gco"))
|
||||
("/some/base/folder/some/folder/and", "some_file.gco")
|
||||
>>> storage.sanitize("some file.gco")
|
||||
("/some/base/folder", "some_file.gco")
|
||||
>>> storage.sanitize(("some file.gco",))
|
||||
("/some/base/folder", "some_file.gco")
|
||||
>>> storage.sanitize("")
|
||||
("/some/base/folder", "")
|
||||
>>> storage.sanitize("some/folder/with/trailing/slash/")
|
||||
("/some/base/folder/some/folder/with/trailing/slash", "")
|
||||
>>> storage.sanitize("some", "folder", "")
|
||||
("/some/base/folder/some/folder", "")
|
||||
"""
|
||||
name = None
|
||||
if isinstance(path, (str, unicode, basestring)):
|
||||
@@ -628,24 +610,6 @@ class LocalFileStorage(StorageInterface):
|
||||
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise strips any characters from the
|
||||
given ``name`` that are not any of the ASCII characters, digits, ``-``, ``_``, ``.``, ``(``, ``)`` or space and
|
||||
replaces and spaces with ``_``.
|
||||
|
||||
Examples::
|
||||
|
||||
>>> storage = LocalFileStorage("/some/base/folder")
|
||||
>>> storage.sanitize_name("some_file.gco")
|
||||
"some_file.gco"
|
||||
>>> storage.sanitize_name("some_file with (parentheses) and ümläuts and digits 123.gco")
|
||||
"some_file_with_(parentheses)_and_mluts_and_digits_123.gco"
|
||||
>>> storage.sanitize_name("pengüino pequeño.stl")
|
||||
"pengino_pequeo.stl"
|
||||
>>> storage.sanitize_name("some/folder/still/left.gco")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: name must not contain / or \
|
||||
>>> storage.sanitize_name("also\\no\\backslashes.gco")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: name must not contain / or \
|
||||
"""
|
||||
if name is None:
|
||||
return None
|
||||
@@ -664,22 +628,6 @@ class LocalFileStorage(StorageInterface):
|
||||
Ensures that the on disk representation of ``path`` is located under the configured basefolder. Resolves all
|
||||
relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the
|
||||
absolute path including leading ``basefolder`` path.
|
||||
|
||||
Examples::
|
||||
|
||||
>>> storage = LocalFileStorage("/some/base/folder")
|
||||
>>> storage.sanitize_path("folder/with/subfolder")
|
||||
"/some/base/folder/folder/with/subfolder"
|
||||
>>> storage.sanitize_path("folder/with/subfolder/../other/folder")
|
||||
"/some/base/folder/folder/with/other/folder"
|
||||
>>> storage.sanitize_path("/folder/with/leading/slash")
|
||||
"/some/base/folder/folder/with/leading/slash"
|
||||
>>> storage.sanitize_path(".folder/with/leading/dot")
|
||||
"/some/base/folder/folder/with/leading/dot
|
||||
>>> storage.sanitize_path("../../folder/out/of/the/basefolder")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: path not contained in base folder: /some/folder/out/of/the/basefolder
|
||||
"""
|
||||
if path[0] == "/" or path[0] == ".":
|
||||
path = path[1:]
|
||||
|
||||
@@ -7,6 +7,8 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
|
||||
import io
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
class AbstractFileWrapper(object):
|
||||
"""
|
||||
Wrapper for file representations to save to storages.
|
||||
@@ -85,7 +87,7 @@ class StreamWrapper(AbstractFileWrapper):
|
||||
"""
|
||||
import shutil
|
||||
|
||||
with open(path, "wb") as dest:
|
||||
with atomic_write(path, "wb") as dest:
|
||||
with self.stream() as source:
|
||||
shutil.copyfileobj(source, dest)
|
||||
|
||||
|
||||
@@ -106,7 +106,9 @@ 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:
|
||||
@@ -159,7 +161,7 @@ def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_prepr
|
||||
set_preprocessors=set_preprocessors)
|
||||
|
||||
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None):
|
||||
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
|
||||
@@ -205,7 +207,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:
|
||||
@@ -301,19 +303,16 @@ class PluginSettings(object):
|
||||
self.set_preprocessors = dict(plugins=dict())
|
||||
self.set_preprocessors["plugins"][plugin_key] = set_preprocessors
|
||||
|
||||
def prefix_path(path):
|
||||
return ['plugins', self.plugin_key] + path
|
||||
|
||||
def prefix_path_in_args(args, index=0):
|
||||
result = []
|
||||
if index == 0:
|
||||
result.append(prefix_path(args[0]))
|
||||
result.append(self._prefix_path(args[0]))
|
||||
result.extend(args[1:])
|
||||
else:
|
||||
args_before = args[:index - 1]
|
||||
args_after = args[index + 1:]
|
||||
result.extend(args_before)
|
||||
result.append(prefix_path(args[index]))
|
||||
result.append(self._prefix_path(args[index]))
|
||||
result.extend(args_after)
|
||||
return result
|
||||
|
||||
@@ -332,6 +331,7 @@ class PluginSettings(object):
|
||||
return kwargs
|
||||
|
||||
self.access_methods = dict(
|
||||
has =("has", prefix_path_in_args, add_getter_kwargs),
|
||||
get =("get", prefix_path_in_args, add_getter_kwargs),
|
||||
get_int =("getInt", prefix_path_in_args, add_getter_kwargs),
|
||||
get_float =("getFloat", prefix_path_in_args, add_getter_kwargs),
|
||||
@@ -339,7 +339,8 @@ class PluginSettings(object):
|
||||
set =("set", prefix_path_in_args, add_setter_kwargs),
|
||||
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)
|
||||
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs),
|
||||
remove =("remove", prefix_path_in_args)
|
||||
)
|
||||
self.deprecated_access_methods = dict(
|
||||
getInt ="get_int",
|
||||
@@ -350,6 +351,17 @@ class PluginSettings(object):
|
||||
setBoolean="set_boolean"
|
||||
)
|
||||
|
||||
def _prefix_path(self, path=None):
|
||||
if path is None:
|
||||
path = list()
|
||||
return ['plugins', self.plugin_key] + path
|
||||
|
||||
def global_has(self, path, **kwargs):
|
||||
return self.settings.has(path, **kwargs)
|
||||
|
||||
def global_remove(self, path, **kwargs):
|
||||
return self.settings.remove(path, **kwargs)
|
||||
|
||||
def global_get(self, path, **kwargs):
|
||||
"""
|
||||
Getter for retrieving settings not managed by the plugin itself from the core settings structure. Use this
|
||||
@@ -443,6 +455,24 @@ class PluginSettings(object):
|
||||
os.makedirs(path)
|
||||
return path
|
||||
|
||||
def get_all_data(self, **kwargs):
|
||||
merged = kwargs.get("merged", True)
|
||||
asdict = kwargs.get("asdict", True)
|
||||
defaults = kwargs.get("defaults", self.defaults)
|
||||
preprocessors = kwargs.get("preprocessors", self.get_preprocessors)
|
||||
|
||||
kwargs.update(dict(
|
||||
merged=merged,
|
||||
asdict=asdict,
|
||||
defaults=defaults,
|
||||
preprocessors=preprocessors
|
||||
))
|
||||
|
||||
return self.settings.get(self._prefix_path(), **kwargs)
|
||||
|
||||
def clean_all_data(self):
|
||||
self.settings.remove(self._prefix_path())
|
||||
|
||||
def __getattr__(self, item):
|
||||
all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys()
|
||||
if item in all_access_methods:
|
||||
|
||||
+180
-28
@@ -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,12 +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)
|
||||
@@ -490,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))
|
||||
@@ -518,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
|
||||
|
||||
@@ -530,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]
|
||||
|
||||
@@ -565,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
|
||||
|
||||
@@ -635,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:
|
||||
@@ -777,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:
|
||||
@@ -789,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
|
||||
@@ -859,7 +933,7 @@ class PluginManager(object):
|
||||
additional_pre_inits=additional_pre_inits,
|
||||
additional_post_inits=additional_post_inits)
|
||||
|
||||
self.logger.info("Initialized {count} plugin(s)".format(count=len(self.plugin_implementations)))
|
||||
self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations)))
|
||||
|
||||
def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
|
||||
if plugin.implementation is None:
|
||||
@@ -959,8 +1033,8 @@ class PluginManager(object):
|
||||
location_str=location_str,
|
||||
show_enabled=show_enabled,
|
||||
enabled_strs=enabled_str),
|
||||
sorted(self.enabled_plugins.values(), key=lambda x: x.name.lower()),
|
||||
))))
|
||||
sorted(self.plugins.values(), key=lambda x: str(x).lower()))
|
||||
)))
|
||||
|
||||
def get_plugin(self, identifier, require_enabled=True):
|
||||
"""
|
||||
@@ -1015,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``.
|
||||
|
||||
@@ -1028,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:
|
||||
@@ -1038,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`.
|
||||
|
||||
@@ -1054,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):
|
||||
@@ -1114,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):
|
||||
|
||||
@@ -1207,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):
|
||||
|
||||
+525
-14
@@ -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,357 @@ 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
|
||||
|
||||
|
||||
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 +1029,8 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
|
||||
flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo"
|
||||
|
||||
|
||||
``BlueprintPlugin`` implements :class:`~octoprint.plugins.core.RestartNeedingPlugin`.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@@ -651,6 +1055,24 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
return f
|
||||
return decorator
|
||||
|
||||
@staticmethod
|
||||
def errorhandler(code_or_exception):
|
||||
"""
|
||||
A decorator to mark errorhandlings methods in your BlueprintPlugin subclass. Works just the same as Flask's
|
||||
own ``errorhandler`` decorator available on blueprints.
|
||||
|
||||
See `the documentation for flask.Blueprint.errorhandler <http://flask.pocoo.org/docs/0.10/api/#flask.Blueprint.errorhandler>`_
|
||||
and `the documentation for flask.Flask.errorhandler <http://flask.pocoo.org/docs/0.10/api/#flask.Flask.errorhandler>`_ for more
|
||||
information.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
def decorator(f):
|
||||
if not hasattr(f, "_blueprint_error_handler") or f._blueprint_error_handler is None:
|
||||
f._blueprint_error_handler = defaultdict(list)
|
||||
f._blueprint_error_handler[f.__name__].append(code_or_exception)
|
||||
return f
|
||||
return decorator
|
||||
|
||||
def get_blueprint(self):
|
||||
"""
|
||||
Creates and returns the blueprint for your plugin. Override this if you want to define and handle your blueprint yourself.
|
||||
@@ -660,15 +1082,34 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
:return: the blueprint ready to be registered with Flask
|
||||
"""
|
||||
|
||||
if hasattr(self, "_blueprint"):
|
||||
# if we already constructed the blueprint and hence have it cached,
|
||||
# return that instance - we don't want to instance it multiple times
|
||||
return self._blueprint
|
||||
|
||||
import flask
|
||||
kwargs = self.get_blueprint_kwargs()
|
||||
blueprint = flask.Blueprint("plugin." + self._identifier, self._identifier, **kwargs)
|
||||
|
||||
# we now iterate over all members of ourselves and look if we find an attribute
|
||||
# that has data originating from one of our decorators - we ignore anything
|
||||
# starting with a _ to only handle public stuff
|
||||
for member in [member for member in dir(self) if not member.startswith("_")]:
|
||||
f = getattr(self, member)
|
||||
|
||||
if hasattr(f, "_blueprint_rules") and member in f._blueprint_rules:
|
||||
# this attribute was annotated with our @route decorator
|
||||
for blueprint_rule in f._blueprint_rules[member]:
|
||||
rule, options = blueprint_rule
|
||||
blueprint.add_url_rule(rule, options.pop("endpoint", f.__name__), view_func=f, **options)
|
||||
|
||||
if hasattr(f, "_blueprint_error_handler") and member in f._blueprint_error_handler:
|
||||
# this attribute was annotated with our @error_handler decorator
|
||||
for code_or_exception in f._blueprint_error_handler[member]:
|
||||
blueprint.errorhandler(code_or_exception)(f)
|
||||
|
||||
# cache and return the blueprint object
|
||||
self._blueprint = blueprint
|
||||
return blueprint
|
||||
|
||||
def get_blueprint_kwargs(self):
|
||||
@@ -764,6 +1205,9 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
the plugin core system upon initialization of the implementation.
|
||||
"""
|
||||
|
||||
config_version_key = "_config_version"
|
||||
"""Key of the field in the settings that holds the configuration format version."""
|
||||
|
||||
def on_settings_load(self):
|
||||
"""
|
||||
Loads the settings for the plugin, called by the Settings API view in order to retrieve all settings from
|
||||
@@ -781,9 +1225,9 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
:return: the current settings of the plugin, as a dictionary
|
||||
"""
|
||||
data = self._settings.get([], asdict=True, merged=True)
|
||||
if "_config_version" in data:
|
||||
del data["_config_version"]
|
||||
data = self._settings.get_all_data()
|
||||
if self.config_version_key in data:
|
||||
del data[self.config_version_key]
|
||||
return data
|
||||
|
||||
def on_settings_save(self, data):
|
||||
@@ -795,7 +1239,8 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
.. note::
|
||||
|
||||
The default implementation will persist your plugin's settings as is, so just in the structure and in the
|
||||
types that were received by the Settings API view.
|
||||
types that were received by the Settings API view. Values identical to the default settings values
|
||||
will *not* be persisted.
|
||||
|
||||
If you need more granular control here, e.g. over the used data types, you'll need to override this method
|
||||
and iterate yourself over all your settings, retrieving them (if set) from the supplied received ``data``
|
||||
@@ -803,15 +1248,38 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
Arguments:
|
||||
data (dict): The settings dictionary to be saved for the plugin
|
||||
|
||||
Returns:
|
||||
dict: The settings that differed from the defaults and were actually saved.
|
||||
"""
|
||||
import octoprint.util
|
||||
|
||||
if "_config_version" in data:
|
||||
del data["_config_version"]
|
||||
# get the current data
|
||||
current = self._settings.get_all_data()
|
||||
if current is None:
|
||||
current = dict()
|
||||
|
||||
current = self._settings.get([], asdict=True, merged=True)
|
||||
merged = octoprint.util.dict_merge(current, data)
|
||||
self._settings.set([], merged)
|
||||
# merge our new data on top of it
|
||||
new_current = octoprint.util.dict_merge(current, data)
|
||||
if self.config_version_key in new_current:
|
||||
del new_current[self.config_version_key]
|
||||
|
||||
# determine diff dict that contains minimal set of changes against the
|
||||
# default settings - we only want to persist that, not everything
|
||||
diff = octoprint.util.dict_minimal_mergediff(self.get_settings_defaults(), new_current)
|
||||
|
||||
version = self.get_settings_version()
|
||||
|
||||
to_persist = dict(diff)
|
||||
if version:
|
||||
to_persist[self.config_version_key] = version
|
||||
|
||||
if to_persist:
|
||||
self._settings.set([], to_persist)
|
||||
else:
|
||||
self._settings.clean_all_data()
|
||||
|
||||
return diff
|
||||
|
||||
def get_settings_defaults(self):
|
||||
"""
|
||||
@@ -894,6 +1362,49 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_settings_cleanup(self):
|
||||
"""
|
||||
Called after migration and initialization but before call to :func:`on_settings_initialized`.
|
||||
|
||||
Plugins may overwrite this method to perform additional clean up tasks.
|
||||
|
||||
The default implementation just minimizes the data persisted on disk to only contain
|
||||
the differences to the defaults (in case the current data was persisted with an older
|
||||
version of OctoPrint that still duplicated default data).
|
||||
"""
|
||||
import octoprint.util
|
||||
from octoprint.settings import NoSuchSettingsPath
|
||||
|
||||
try:
|
||||
# let's fetch the current persisted config (so only the data on disk,
|
||||
# without the defaults)
|
||||
config = self._settings.get_all_data(merged=False, incl_defaults=False, error_on_path=True)
|
||||
except NoSuchSettingsPath:
|
||||
# no config persisted, nothing to do => get out of here
|
||||
return
|
||||
|
||||
if config is None:
|
||||
# config is set to None, that doesn't make sense, kill it and leave
|
||||
self._settings.clean_all_data()
|
||||
return
|
||||
|
||||
if self.config_version_key in config and config[self.config_version_key] is None:
|
||||
# delete None entries for config version - it's the default, no need
|
||||
del config[self.config_version_key]
|
||||
|
||||
# calculate a minimal diff between the settings and the current config -
|
||||
# anything already in the settings will be removed from the persisted
|
||||
# config, no need to duplicate it
|
||||
defaults = self.get_settings_defaults()
|
||||
diff = octoprint.util.dict_minimal_mergediff(defaults, config)
|
||||
|
||||
if not diff:
|
||||
# no diff to defaults, no need to have anything persisted
|
||||
self._settings.clean_all_data()
|
||||
else:
|
||||
# diff => persist only that
|
||||
self._settings.set([], diff)
|
||||
|
||||
def on_settings_initialized(self):
|
||||
"""
|
||||
Called after the settings have been initialized and - if necessary - also been migrated through a call to
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
# 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 is not None 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)
|
||||
octoprint.server.userManager.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._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 & 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>
|
||||
@@ -19,13 +19,16 @@ 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")
|
||||
@@ -37,14 +40,34 @@ 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_configs(self):
|
||||
from flask.ext.babel import gettext
|
||||
return [
|
||||
dict(type="settings", name=gettext("CuraEngine"))
|
||||
dict(type="settings", name=gettext("CuraEngine")),
|
||||
dict(type="wizard", name=gettext("CuraEngine"))
|
||||
]
|
||||
|
||||
##~~ 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):
|
||||
@@ -62,9 +85,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"])
|
||||
@@ -93,8 +113,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:
|
||||
@@ -102,22 +124,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
|
||||
)
|
||||
@@ -159,10 +190,11 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
def is_slicer_configured(self):
|
||||
cura_engine = normalize_path(self._settings.get(["cura_engine"]))
|
||||
if cura_engine is not None and os.path.exists(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(
|
||||
@@ -230,15 +262,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 = 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]
|
||||
|
||||
@@ -321,6 +367,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()
|
||||
@@ -331,17 +379,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:
|
||||
@@ -391,16 +447,40 @@ 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):
|
||||
import yaml
|
||||
with open(path, "wb") as f:
|
||||
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:
|
||||
@@ -415,9 +495,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"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura"
|
||||
__plugin_description__ = "Adds support for slicing via CuraEngine from within OctoPrint"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = CuraPlugin()
|
||||
|
||||
|
||||
|
||||
@@ -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
@@ -23,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");
|
||||
@@ -66,6 +70,7 @@ $(function() {
|
||||
dataType: "json",
|
||||
maxNumberOfFiles: 1,
|
||||
autoUpload: false,
|
||||
headers: OctoPrint.getRequestHeaders(),
|
||||
add: function(e, data) {
|
||||
if (data.files.length == 0) {
|
||||
return false;
|
||||
@@ -93,6 +98,9 @@ $(function() {
|
||||
if (self.profileDescription() !== undefined) {
|
||||
form["description"] = self.profileDescription();
|
||||
}
|
||||
if (self.profileMakeDefault()) {
|
||||
form["default"] = true;
|
||||
}
|
||||
|
||||
data.formData = form;
|
||||
data.submit();
|
||||
@@ -107,6 +115,7 @@ $(function() {
|
||||
self.profileDisplayName(undefined);
|
||||
self.profileDescription(undefined);
|
||||
self.profileAllowOverwrite(true);
|
||||
self.profileMakeDefault(false);
|
||||
|
||||
$("#settings_plugin_cura_import").modal("hide");
|
||||
self.requestData();
|
||||
@@ -123,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) {
|
||||
@@ -148,35 +154,23 @@ $(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() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "util/test",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: JSON.stringify({
|
||||
command: "path",
|
||||
path: self.settings.plugins.cura.cura_engine(),
|
||||
check_type: "file",
|
||||
check_access: "x"
|
||||
}),
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
success: function(response) {
|
||||
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"));
|
||||
@@ -190,17 +184,12 @@ $(function() {
|
||||
}
|
||||
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) {
|
||||
@@ -223,16 +212,35 @@ $(function() {
|
||||
};
|
||||
|
||||
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,58 @@
|
||||
<div id="settings_plugin_cura_import" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</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>
|
||||
</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> | <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>
|
||||
@@ -1,111 +1,14 @@
|
||||
<h4>{{ _('General') }}</h4>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<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">
|
||||
<button class="btn" type="button" data-bind="click: testEnginePath">{{ _('Test') }}</button>
|
||||
</div>
|
||||
<span class="help-block" data-bind="visible: pathBroken() || pathOk, text: pathText"></span>
|
||||
</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 plugin_cura_engine.log') }}
|
||||
</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> | <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>
|
||||
|
||||
<div id="settings_plugin_cura_import" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</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>
|
||||
</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, open it, set up your
|
||||
profile, then click on "File" and there on "Save Profile". You can
|
||||
import the .ini-file this creates via the "Import Profile" button.
|
||||
{% endtrans %}</small>
|
||||
</div>
|
||||
</div>
|
||||
@@ -52,7 +52,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
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,13 +84,25 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
repository="http://plugins.octoprint.org/plugins.json",
|
||||
repository_ttl=24*60,
|
||||
pip=None,
|
||||
pip_args=None,
|
||||
pip_force_user=False,
|
||||
dependency_links=False,
|
||||
hidden=[]
|
||||
)
|
||||
|
||||
def on_settings_save(self, data):
|
||||
old_pip = self._settings.get(["pip"])
|
||||
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
||||
new_pip = self._settings.get(["pip"])
|
||||
|
||||
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
|
||||
self._pip_caller.refresh = True
|
||||
self._pip_caller.force_user = self._settings.get_boolean(["pip_force_user"])
|
||||
if old_pip != new_pip:
|
||||
self._pip_caller.configured = new_pip
|
||||
try:
|
||||
self._pip_caller.trigger_refresh()
|
||||
except:
|
||||
self._pip_caller
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
@@ -104,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
|
||||
@@ -160,19 +186,26 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if not admin_permission.can():
|
||||
return make_response("Insufficient rights", 403)
|
||||
|
||||
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))
|
||||
|
||||
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, repository=dict(available=self._repository_available, plugins=self._repository_plugins), os=self._get_os(), octoprint=self._get_octoprint_version_string())
|
||||
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_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"])
|
||||
))
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
if not admin_permission.can():
|
||||
@@ -187,6 +220,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
plugin_name = data["plugin"] if "plugin" in data else None
|
||||
return self.command_install(url=url,
|
||||
force="force" in data and data["force"] in valid_boolean_trues,
|
||||
dependency_links="dependency_links" in data and data["dependency_links"] in valid_boolean_trues,
|
||||
reinstall=plugin_name)
|
||||
|
||||
elif command == "uninstall":
|
||||
@@ -205,7 +239,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
plugin = self._plugin_manager.plugins[plugin_name]
|
||||
return self.command_toggle(plugin, command)
|
||||
|
||||
def command_install(self, url=None, path=None, force=False, reinstall=None):
|
||||
def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False):
|
||||
if url is not None:
|
||||
pip_args = ["install", sarge.shell_quote(url)]
|
||||
elif path is not None:
|
||||
@@ -213,6 +247,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
else:
|
||||
raise ValueError("Either url or path must be provided")
|
||||
|
||||
if dependency_links or self._settings.get_boolean(["dependency_links"]):
|
||||
pip_args.append("--process-dependency-links")
|
||||
|
||||
all_plugins_before = self._plugin_manager.find_plugins()
|
||||
|
||||
success_string = "Successfully installed"
|
||||
@@ -300,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))
|
||||
@@ -314,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()))
|
||||
@@ -361,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:
|
||||
@@ -421,8 +467,19 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
def _call_pip(self, args):
|
||||
if self._pip_caller is None or not self._pip_caller.available:
|
||||
raise RuntimeError(u"No pip available, can't operate".format(**locals()))
|
||||
|
||||
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")
|
||||
|
||||
additional_args = self._settings.get(["pip_args"])
|
||||
if additional_args:
|
||||
args.append(additional_args)
|
||||
|
||||
return self._pip_caller.execute(*args)
|
||||
|
||||
def _log_message(self, *lines):
|
||||
self._log(lines, prefix=u"*", stream="message")
|
||||
|
||||
def _log_call(self, *lines):
|
||||
self._log(lines, prefix=u" ", stream="call")
|
||||
|
||||
@@ -500,7 +557,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
try:
|
||||
import json
|
||||
with open(self._repository_cache_path, "w+b") as f:
|
||||
with octoprint.util.atomic_write(self._repository_cache_path, "wb") as f:
|
||||
json.dump(repo_data, f)
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e)))
|
||||
@@ -519,6 +576,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
def map_repository_entry(entry):
|
||||
result = dict(entry)
|
||||
|
||||
if not "follow_dependency_links" in result:
|
||||
result["follow_dependency_links"] = False
|
||||
|
||||
if not "follow_dependency_links" in result:
|
||||
result["follow_dependency_links"] = False
|
||||
|
||||
result["is_compatible"] = dict(
|
||||
octoprint=True,
|
||||
os=True
|
||||
@@ -594,6 +657,18 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
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(
|
||||
key=plugin.key,
|
||||
@@ -604,11 +679,13 @@ 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
|
||||
)
|
||||
|
||||
__plugin_name__ = "Plugin Manager"
|
||||
@@ -623,5 +700,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,6 +72,15 @@ $(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");
|
||||
|
||||
self.plugins = new ItemListHelper(
|
||||
"plugin.pluginmanager.installedplugins",
|
||||
@@ -70,11 +146,46 @@ $(function() {
|
||||
self.loglines = ko.observableArray([]);
|
||||
self.installedPlugins = ko.observableArray([]);
|
||||
|
||||
self.followDependencyLinks = ko.observable(false);
|
||||
|
||||
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();
|
||||
});
|
||||
@@ -84,11 +195,16 @@ $(function() {
|
||||
};
|
||||
|
||||
self.enableUninstall = function(data) {
|
||||
return self.enableManagement() && !data.bundled && data.key != 'pluginmanager' && !data.pending_uninstall;
|
||||
return self.enableManagement()
|
||||
&& (data.origin != "entry_point" || self.pipAvailable())
|
||||
&& data.managable
|
||||
&& !data.bundled
|
||||
&& data.key != 'pluginmanager'
|
||||
&& !data.pending_uninstall;
|
||||
};
|
||||
|
||||
self.enableRepoInstall = function(data) {
|
||||
return self.enableManagement() && self.isCompatible(data);
|
||||
return self.enableManagement() && self.pipAvailable() && self.isCompatible(data);
|
||||
};
|
||||
|
||||
self.invalidUrl = ko.computed(function() {
|
||||
@@ -98,7 +214,7 @@ $(function() {
|
||||
|
||||
self.enableUrlInstall = ko.computed(function() {
|
||||
var url = self.installUrl();
|
||||
return self.enableManagement() && url !== undefined && url.trim() != "" && !self.invalidUrl();
|
||||
return self.enableManagement() && self.pipAvailable() && url !== undefined && url.trim() != "" && !self.invalidUrl();
|
||||
});
|
||||
|
||||
self.invalidArchive = ko.computed(function() {
|
||||
@@ -108,7 +224,7 @@ $(function() {
|
||||
|
||||
self.enableArchiveInstall = ko.computed(function() {
|
||||
var name = self.uploadFilename();
|
||||
return self.enableManagement() && name !== undefined && name.trim() != "" && !self.invalidArchive();
|
||||
return self.enableManagement() && self.pipAvailable() && name !== undefined && name.trim() != "" && !self.invalidArchive();
|
||||
});
|
||||
|
||||
self.uploadElement.fileupload({
|
||||
@@ -125,6 +241,9 @@ $(function() {
|
||||
self.uploadButton.unbind("click");
|
||||
self.uploadButton.bind("click", function() {
|
||||
self._markWorking(gettext("Installing plugin..."), gettext("Installing plugin from uploaded archive..."));
|
||||
data.formData = {
|
||||
dependency_links: self.followDependencyLinks()
|
||||
};
|
||||
data.submit();
|
||||
return false;
|
||||
});
|
||||
@@ -162,7 +281,8 @@ $(function() {
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
self._fromPluginsResponse(data.plugins);
|
||||
self._fromRepositoryResponse(data.repository)
|
||||
self._fromRepositoryResponse(data.repository);
|
||||
self._fromPipResponse(data.pip);
|
||||
};
|
||||
|
||||
self._fromPluginsResponse = function(data) {
|
||||
@@ -183,17 +303,34 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._fromPipResponse = function(data) {
|
||||
self.pipAvailable(data.available);
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
self.requestData = function(includeRepo) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
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) {
|
||||
@@ -207,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() {
|
||||
@@ -239,14 +382,10 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.installed(data)) {
|
||||
self.installPlugin(data.archive, data.title, data.id);
|
||||
} else {
|
||||
self.installPlugin(data.archive, data.title, undefined);
|
||||
}
|
||||
self.installPlugin(data.archive, data.title, (self.installed(data) ? data.id : undefined), data.follow_dependency_links || self.followDependencyLinks());
|
||||
};
|
||||
|
||||
self.installPlugin = function(url, name, reinstall) {
|
||||
self.installPlugin = function(url, name, reinstall, followDependencyLinks) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
}
|
||||
@@ -260,6 +399,10 @@ $(function() {
|
||||
}
|
||||
if (!url) return;
|
||||
|
||||
if (followDependencyLinks === undefined) {
|
||||
followDependencyLinks = self.followDependencyLinks();
|
||||
}
|
||||
|
||||
var workTitle, workText;
|
||||
if (!reinstall) {
|
||||
workTitle = gettext("Installing plugin...");
|
||||
@@ -274,26 +417,33 @@ $(function() {
|
||||
}
|
||||
self._markWorking(workTitle, workText);
|
||||
|
||||
var command = "install";
|
||||
var payload = {url: url};
|
||||
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) {
|
||||
@@ -310,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() {
|
||||
@@ -334,6 +483,60 @@ $(function() {
|
||||
self.requestData(true);
|
||||
};
|
||||
|
||||
self.showPluginSettings = function() {
|
||||
self._copyConfig();
|
||||
self.configurationDialog.modal();
|
||||
};
|
||||
|
||||
self.savePluginSettings = function() {
|
||||
var pipCommand = self.config_pipCommand();
|
||||
if (pipCommand != undefined && pipCommand.trim() == "") {
|
||||
pipCommand = null;
|
||||
}
|
||||
|
||||
var repository = self.config_repositoryUrl();
|
||||
if (repository != undefined && repository.trim() == "") {
|
||||
repository = null;
|
||||
}
|
||||
|
||||
var repositoryTtl;
|
||||
try {
|
||||
repositoryTtl = parseInt(self.config_repositoryTtl());
|
||||
} catch (ex) {
|
||||
repositoryTtl = null;
|
||||
}
|
||||
|
||||
var pipArgs = self.config_pipAdditionalArgs();
|
||||
if (pipArgs != undefined && pipArgs.trim() == "") {
|
||||
pipArgs = null;
|
||||
}
|
||||
|
||||
var data = {
|
||||
plugins: {
|
||||
pluginmanager: {
|
||||
repository: repository,
|
||||
repository_ttl: repositoryTtl,
|
||||
pip: pipCommand,
|
||||
pip_args: pipArgs,
|
||||
pip_force_user: self.config_pipForceUser()
|
||||
}
|
||||
}
|
||||
};
|
||||
self.settingsViewModel.saveData(data, function() {
|
||||
self.configurationDialog.modal("hide");
|
||||
self._copyConfig();
|
||||
self.refreshRepository();
|
||||
});
|
||||
};
|
||||
|
||||
self._copyConfig = function() {
|
||||
self.config_repositoryUrl(self.settingsViewModel.settings.plugins.pluginmanager.repository());
|
||||
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) {
|
||||
return _.includes(self.installedPlugins(), data.id);
|
||||
};
|
||||
@@ -347,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: {
|
||||
@@ -371,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) {
|
||||
@@ -460,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();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -613,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 %}
|
||||
@@ -4,7 +4,32 @@
|
||||
</div>
|
||||
{% endmacro %}
|
||||
|
||||
{% macro pluginmanager_nopip() %}
|
||||
<div class="alert" data-bind="visible: !pipAvailable()">{% trans %}
|
||||
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 %}
|
||||
|
||||
{% macro pluginmanager_sudopip() %}
|
||||
<div class="alert alert-error" data-bind="visible: pipUseSudo()">{% trans %}
|
||||
The <code>pip</code> command is configured to use <code>sudo</code>. This
|
||||
is <strong>not</strong> recommended due to security reasons. It is <strong>strongly</strong>
|
||||
suggested you install OctoPrint under a
|
||||
<a href="https://github.com/foosel/OctoPrint/#installation">user-owned virtual environment</a>
|
||||
so that the use of <code>sudo</code> is not needed for plugin management.
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_sudopip() }}
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Installed Plugins') }}</h3>
|
||||
|
||||
@@ -18,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"> </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>
|
||||
@@ -47,6 +72,23 @@
|
||||
|
||||
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
|
||||
|
||||
<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">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
@@ -67,6 +109,8 @@
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ 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="#">
|
||||
@@ -147,8 +191,79 @@
|
||||
</div>
|
||||
<span class="help-block" data-bind="visible: invalidArchive">{{ _('This does not look like a valid plugin archive. Valid plugin archives should be either zip files or tarballs and have the extension ".zip", ".tar.gz", ".tgz" or ".tar"') }}</span>
|
||||
</form>
|
||||
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: followDependencyLinks"> {{ _('Use <code>--process-dependency-links</code> with <code>pip install</code>') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_pluginmanager_configurationdialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Plugin Configuration') }}</h3>
|
||||
</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">{{ _('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 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">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_repositoryUrl">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('How long to cache repository data, in minutes. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Repository cache TTL') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" class="input-mini" data-bind="value: config_repositoryTtl">
|
||||
<span class="add-on">min</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: savePluginSettings" aria-hidden="true">{{ _('Save') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -14,6 +14,7 @@ import threading
|
||||
import time
|
||||
import logging
|
||||
import logging.handlers
|
||||
import hashlib
|
||||
|
||||
from . import version_checks, updaters, exceptions, util
|
||||
|
||||
@@ -74,6 +75,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._refresh_configured_checks = False
|
||||
self._configured_checks = self._settings.get(["checks"], merged=True)
|
||||
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
|
||||
check_providers = self._settings.get(["check_providers"], merged=True)
|
||||
for name, hook in update_check_hooks.items():
|
||||
try:
|
||||
hook_checks = hook()
|
||||
@@ -81,9 +83,23 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._logger.exception("Error while retrieving update information from plugin {name}".format(**locals()))
|
||||
else:
|
||||
for key, data in hook_checks.items():
|
||||
check_providers[key] = name
|
||||
if key in self._configured_checks:
|
||||
data = dict_merge(data, self._configured_checks[key])
|
||||
self._configured_checks[key] = data
|
||||
self._settings.set(["check_providers"], check_providers)
|
||||
self._settings.save()
|
||||
|
||||
# we only want to process checks that came from plugins for
|
||||
# which the plugins are still installed and enabled
|
||||
config_checks = self._settings.get(["checks"])
|
||||
plugin_and_not_enabled = lambda k: k in check_providers and \
|
||||
not check_providers[k] in self._plugin_manager.enabled_plugins
|
||||
obsolete_plugin_checks = filter(plugin_and_not_enabled,
|
||||
config_checks.keys())
|
||||
for key in obsolete_plugin_checks:
|
||||
self._logger.debug("Check for key {} was provided by plugin {} that's no longer available, ignoring it".format(key, check_providers[key]))
|
||||
del self._configured_checks[key]
|
||||
|
||||
return self._configured_checks
|
||||
|
||||
@@ -99,8 +115,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._logger.exception("Error while loading version cache from disk")
|
||||
else:
|
||||
try:
|
||||
if "octoprint" in data and len(data["octoprint"]) == 4 and "local" in data["octoprint"][1] and "value" in data["octoprint"][1]["local"]:
|
||||
data_version = data["octoprint"][1]["local"]["value"]
|
||||
if not isinstance(data, dict):
|
||||
self._logger.info("Version cache was created in a different format, not using it")
|
||||
return
|
||||
|
||||
if "__version" in data:
|
||||
data_version = data["__version"]
|
||||
else:
|
||||
self._logger.info("Can't determine version of OctoPrint version cache was created for, not using it")
|
||||
return
|
||||
@@ -118,24 +138,18 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._logger.exception("Error parsing in version cache data")
|
||||
|
||||
def _save_version_cache(self):
|
||||
import tempfile
|
||||
import yaml
|
||||
import shutil
|
||||
from octoprint.util import atomic_write
|
||||
from octoprint._version import get_versions
|
||||
|
||||
file_obj = tempfile.NamedTemporaryFile(delete=False)
|
||||
try:
|
||||
octoprint_version = get_versions()["version"]
|
||||
self._version_cache["__version"] = octoprint_version
|
||||
|
||||
with atomic_write(self._version_cache_path) as file_obj:
|
||||
yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
file_obj.close()
|
||||
shutil.move(file_obj.name, self._version_cache_path)
|
||||
|
||||
self._version_cache_dirty = False
|
||||
self._logger.info("Saved version cache to disk")
|
||||
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)))
|
||||
self._version_cache_dirty = False
|
||||
self._logger.info("Saved version cache to disk")
|
||||
|
||||
#~~ SettingsPlugin API
|
||||
|
||||
@@ -150,10 +164,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
"restart": "octoprint"
|
||||
},
|
||||
},
|
||||
|
||||
"octoprint_restart_command": None,
|
||||
"environment_restart_command": None,
|
||||
"pip_command": None,
|
||||
"check_providers": {},
|
||||
|
||||
"cache_ttl": 24 * 60,
|
||||
}
|
||||
@@ -162,28 +174,92 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
data = dict(octoprint.plugin.SettingsPlugin.on_settings_load(self))
|
||||
if "checks" in data:
|
||||
del data["checks"]
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
if "octoprint" in checks:
|
||||
if "checkout_folder" in checks["octoprint"]:
|
||||
data["octoprint_checkout_folder"] = checks["octoprint"]["checkout_folder"]
|
||||
elif "update_folder" in checks["octoprint"]:
|
||||
data["octoprint_checkout_folder"] = checks["octoprint"]["update_folder"]
|
||||
else:
|
||||
data["octoprint_checkout_folder"] = None
|
||||
data["octoprint_type"] = checks["octoprint"].get("type", None)
|
||||
else:
|
||||
data["octoprint_checkout_folder"] = None
|
||||
data["octoprint_type"] = None
|
||||
|
||||
return data
|
||||
|
||||
def on_settings_save(self, data):
|
||||
for key in self.get_settings_defaults():
|
||||
if key == "checks" or key == "cache_ttl":
|
||||
if key == "checks" or key == "cache_ttl" or key == "octoprint_checkout_folder" or key == "octoprint_type":
|
||||
continue
|
||||
if key in data:
|
||||
self._settings.set([key], data[key])
|
||||
|
||||
if "cache_ttl" in data:
|
||||
self._settings.set_int(["cache_ttl"], data["cache_ttl"])
|
||||
|
||||
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
if "octoprint" in checks:
|
||||
check = checks["octoprint"]
|
||||
update_type = check.get("type", None)
|
||||
checkout_folder = check.get("checkout_folder", None)
|
||||
update_folder = check.get("update_folder", None)
|
||||
|
||||
defaults = dict(
|
||||
plugins=dict(softwareupdate=dict(
|
||||
checks=dict(
|
||||
octoprint=dict(
|
||||
type=update_type,
|
||||
checkout_folder=checkout_folder,
|
||||
update_folder=update_folder
|
||||
)
|
||||
)
|
||||
))
|
||||
)
|
||||
|
||||
if "octoprint_checkout_folder" in data:
|
||||
self._settings.set(["checks", "octoprint", "checkout_folder"], data["octoprint_checkout_folder"], defaults=defaults, force=True)
|
||||
if update_folder and data["octoprint_checkout_folder"]:
|
||||
self._settings.set(["checks", "octoprint", "update_folder"], None, defaults=defaults, force=True)
|
||||
self._refresh_configured_checks = True
|
||||
|
||||
if "octoprint_type" in data and data["octoprint_type"] in ("github_release", "git_commit"):
|
||||
self._settings.set(["checks", "octoprint", "type"], data["octoprint_type"], defaults=defaults, force=True)
|
||||
self._refresh_configured_checks = True
|
||||
|
||||
def get_settings_version(self):
|
||||
return 3
|
||||
return 4
|
||||
|
||||
def on_settings_migrate(self, target, current=None):
|
||||
|
||||
if current is None or current < 4:
|
||||
# config version 4 and higher moves octoprint_restart_command and
|
||||
# environment_restart_command to the core configuration
|
||||
|
||||
# current plugin commands
|
||||
configured_octoprint_restart_command = self._settings.get(["octoprint_restart_command"])
|
||||
configured_environment_restart_command = self._settings.get(["environment_restart_command"])
|
||||
|
||||
# current global commands
|
||||
configured_system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||
configured_server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||
|
||||
# only set global commands if they are not yet set
|
||||
if configured_system_restart_command is None and configured_environment_restart_command is not None:
|
||||
self._settings.global_set(["server", "commands", "systemRestartCommand"], configured_environment_restart_command)
|
||||
if configured_server_restart_command is None and configured_octoprint_restart_command is not None:
|
||||
self._settings.global_set(["server", "commands", "serverRestartCommand"], configured_octoprint_restart_command)
|
||||
|
||||
# delete current plugin commands from config
|
||||
self._settings.set(["environment_restart_command"], None)
|
||||
self._settings.set(["octoprint_restart_command"], None)
|
||||
|
||||
if current is None or current == 2:
|
||||
# there might be some left over data from the time we still persisted everything to settings,
|
||||
# even the stuff that shouldn't be persisted but always provided by the hook - let's
|
||||
# clean up
|
||||
# No config version and config version 2 need the same fix, stripping
|
||||
# accidentally persisted data off the checks
|
||||
|
||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||
if configured_checks is None:
|
||||
@@ -229,6 +305,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._settings.set(["checks", key], None, defaults=dummy_defaults)
|
||||
|
||||
elif current == 1:
|
||||
# config version 1 had the error that the octoprint check got accidentally
|
||||
# included in checks["octoprint"], leading to recursion and hence to
|
||||
# yaml parser errors
|
||||
|
||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||
if configured_checks is None:
|
||||
return
|
||||
@@ -239,7 +319,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
|
||||
dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None
|
||||
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
|
||||
self._settings.save()
|
||||
|
||||
def _clean_settings_check(self, key, data, defaults, delete=None, save=True):
|
||||
if delete is None:
|
||||
@@ -353,14 +432,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if not target in check_targets:
|
||||
continue
|
||||
|
||||
populated_check = self._populated_check(target, check)
|
||||
|
||||
try:
|
||||
populated_check = self._populated_check(target, check)
|
||||
target_information, target_update_available, target_update_possible = self._get_current_version(target, populated_check, force=force)
|
||||
if target_information is None:
|
||||
continue
|
||||
target_information = dict()
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown update check type for %s" % target)
|
||||
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)
|
||||
@@ -377,22 +455,29 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
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))
|
||||
displayVersion=populated_check["displayVersion"].format(octoprint_version=octoprint_version, local_name=local_name, local_value=local_value),
|
||||
check=populated_check)
|
||||
|
||||
if self._version_cache_dirty:
|
||||
self._save_version_cache()
|
||||
return information, update_available, update_possible
|
||||
|
||||
def _get_check_hash(self, check):
|
||||
hash = hashlib.md5()
|
||||
hash.update(repr(check))
|
||||
return hash.hexdigest()
|
||||
|
||||
def _get_current_version(self, target, check, force=False):
|
||||
"""
|
||||
Determines the current version information for one target based on its check configuration.
|
||||
"""
|
||||
|
||||
current_hash = self._get_check_hash(check)
|
||||
if target in self._version_cache and not force:
|
||||
timestamp, information, update_available, update_possible = self._version_cache[target]
|
||||
if timestamp + self._version_cache_ttl >= time.time() > timestamp:
|
||||
data = self._version_cache[target]
|
||||
if data["hash"] == current_hash and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"]:
|
||||
# we also check that timestamp < now to not get confused too much by clock changes
|
||||
return information, update_available, update_possible
|
||||
return data["information"], data["available"], data["possible"]
|
||||
|
||||
information = dict()
|
||||
update_available = False
|
||||
@@ -415,7 +500,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
except:
|
||||
update_possible = False
|
||||
|
||||
self._version_cache[target] = (time.time(), information, update_available, update_possible)
|
||||
self._version_cache[target] = dict(timestamp=time.time(),
|
||||
hash=current_hash,
|
||||
information=information,
|
||||
available=update_available,
|
||||
possible=update_possible)
|
||||
self._version_cache_dirty = True
|
||||
return information, update_available, update_possible
|
||||
|
||||
@@ -496,7 +585,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if restart_type is not None and restart_type in ("octoprint", "environment"):
|
||||
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
|
||||
# we can actually perform that
|
||||
restart_command = self._settings.get(["%s_restart_command" % restart_type])
|
||||
|
||||
if restart_type == "octoprint":
|
||||
restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||
elif restart_type == "environment":
|
||||
restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||
|
||||
if restart_command is not None:
|
||||
self._send_client_message("restarting", dict(restart_type=restart_type, results=target_results))
|
||||
@@ -590,6 +683,33 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._logger.warn("Restart stderr:\n%s" % e.stderr)
|
||||
raise exceptions.RestartFailed()
|
||||
|
||||
def _populated_check(self, target, check):
|
||||
if not "type" in check:
|
||||
raise exceptions.UnknownCheckType()
|
||||
|
||||
result = dict(check)
|
||||
|
||||
if target == "octoprint":
|
||||
from flask.ext.babel import gettext
|
||||
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"))
|
||||
else:
|
||||
result["current"] = versions["version"]
|
||||
else:
|
||||
result["displayName"] = check.get("displayName", target)
|
||||
result["displayVersion"] = check.get("displayVersion", check.get("current", "unknown"))
|
||||
if check["type"] in ("github_commit"):
|
||||
result["current"] = check.get("current", None)
|
||||
else:
|
||||
result["current"] = check.get("current", check.get("displayVersion", None))
|
||||
|
||||
return result
|
||||
|
||||
def _log(self, lines, prefix=None, stream=None, strip=True):
|
||||
if strip:
|
||||
lines = map(lambda x: x.strip(), lines)
|
||||
@@ -601,22 +721,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
def _send_client_message(self, message_type, data=None):
|
||||
self._plugin_manager.send_plugin_message(self._identifier, dict(type=message_type, data=data))
|
||||
|
||||
def _populated_check(self, target, check):
|
||||
result = dict(check)
|
||||
|
||||
if target == "octoprint":
|
||||
from octoprint._version import get_versions
|
||||
from flask.ext.babel import gettext
|
||||
result["displayName"] = check.get("displayName", gettext("OctoPrint"))
|
||||
result["displayVersion"] = check.get("displayVersion", "{octoprint_version}")
|
||||
result["current"] = get_versions()["version"]
|
||||
else:
|
||||
result["displayName"] = check.get("displayName", target)
|
||||
result["displayVersion"] = check.get("displayVersion", check.get("current", "unknown"))
|
||||
result["current"] = check.get("current", check.get("displayVersion", None))
|
||||
|
||||
return result
|
||||
|
||||
def _get_version_checker(self, target, check):
|
||||
"""
|
||||
Retrieves the version checker to use for given target and check configuration. Will raise an UnknownCheckType
|
||||
|
||||
@@ -93,7 +93,8 @@ def _git(args, cwd, verbose=False, git_executable=None):
|
||||
|
||||
for c in commands:
|
||||
try:
|
||||
return _execute([c] + args, cwd=cwd)
|
||||
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:
|
||||
|
||||
@@ -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;
|
||||
@@ -19,12 +59,22 @@ $(function() {
|
||||
self.workingOutput = undefined;
|
||||
self.loglines = ko.observableArray([]);
|
||||
|
||||
self.config_restartCommand = ko.observable();
|
||||
self.config_rebootCommand = ko.observable();
|
||||
self.octoprintUnconfigured = ko.observable();
|
||||
self.octoprintUnreleased = ko.observable();
|
||||
|
||||
self.config_cacheTtl = ko.observable();
|
||||
self.config_checkoutFolder = ko.observable();
|
||||
self.config_checkType = ko.observable();
|
||||
|
||||
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
|
||||
|
||||
self.config_availableCheckTypes = [
|
||||
{"key": "github_release", "name": gettext("Release")},
|
||||
{"key": "git_commit", "name": gettext("Commit")}
|
||||
];
|
||||
|
||||
self.reloadOverlay = $("#reloadui_overlay");
|
||||
|
||||
self.versions = new ItemListHelper(
|
||||
"plugin.softwareupdate.versions",
|
||||
{
|
||||
@@ -80,23 +130,36 @@ $(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: {
|
||||
octoprint_restart_command: self.config_restartCommand(),
|
||||
environment_restart_command: self.config_rebootCommand(),
|
||||
cache_ttl: parseInt(self.config_cacheTtl())
|
||||
cache_ttl: parseInt(self.config_cacheTtl()),
|
||||
octoprint_checkout_folder: self.config_checkoutFolder(),
|
||||
octoprint_type: self.config_checkType()
|
||||
}
|
||||
}
|
||||
};
|
||||
self.settings.saveData(data, function() { self.configurationDialog.modal("hide"); self._copyConfig(); });
|
||||
self.settings.saveData(data, {
|
||||
success: function() {
|
||||
self.configurationDialog.modal("hide");
|
||||
self._copyConfig();
|
||||
self.performCheck();
|
||||
},
|
||||
complete: function() {
|
||||
$("i.icon-spinner", target).remove();
|
||||
},
|
||||
sending: true
|
||||
});
|
||||
};
|
||||
|
||||
self._copyConfig = function() {
|
||||
self.config_restartCommand(self.settings.settings.plugins.softwareupdate.octoprint_restart_command());
|
||||
self.config_rebootCommand(self.settings.settings.plugins.softwareupdate.environment_restart_command());
|
||||
self.config_cacheTtl(self.settings.settings.plugins.softwareupdate.cache_ttl());
|
||||
self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());
|
||||
self.config_checkType(self.settings.settings.plugins.softwareupdate.octoprint_type());
|
||||
};
|
||||
|
||||
self.fromCheckResponse = function(data, ignoreSeen, showIfNothingNew) {
|
||||
@@ -115,6 +178,25 @@ $(function() {
|
||||
});
|
||||
self.versions.updateItems(versions);
|
||||
|
||||
var octoprint = data.information["octoprint"];
|
||||
if (octoprint && octoprint.hasOwnProperty("check")) {
|
||||
var check = octoprint.check;
|
||||
if (BRANCH != "master" && check["type"] == "github_release") {
|
||||
self.octoprintUnreleased(true);
|
||||
} else {
|
||||
self.octoprintUnreleased(false);
|
||||
}
|
||||
|
||||
var checkoutFolder = (check["checkout_folder"] || "").trim();
|
||||
var updateFolder = (check["update_folder"] || "").trim();
|
||||
var checkType = check["type"] || "";
|
||||
if ((checkType == "github_release" || checkType == "git_commit") && checkoutFolder == "" && updateFolder == "") {
|
||||
self.octoprintUnconfigured(true);
|
||||
} else {
|
||||
self.octoprintUnconfigured(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (data.status == "updateAvailable" || data.status == "updatePossible") {
|
||||
var text = gettext("There are updates available for the following components:");
|
||||
|
||||
@@ -181,20 +263,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) {
|
||||
@@ -245,13 +317,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)
|
||||
.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!"),
|
||||
@@ -262,12 +333,7 @@ $(function() {
|
||||
sticker: false
|
||||
}
|
||||
});
|
||||
},
|
||||
success: function(data) {
|
||||
self.currentlyBeingUpdated = data.checks;
|
||||
self._markWorking(gettext("Updating..."), gettext("Updating, please wait."));
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
self.update = function(force) {
|
||||
@@ -283,10 +349,11 @@ $(function() {
|
||||
type: "error"
|
||||
});
|
||||
} else {
|
||||
showConfirmationDialog(gettext("This will update your OctoPrint installation and restart the server."), function(e) {
|
||||
e.preventDefault();
|
||||
$("#confirmation_dialog").modal("hide");
|
||||
self.performUpdate(force);
|
||||
showConfirmationDialog({
|
||||
message: gettext("This will update your OctoPrint installation and restart the server."),
|
||||
onproceed: function(e) {
|
||||
self.performUpdate(force);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -342,18 +409,10 @@ $(function() {
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
if (self.waitingForRestart) {
|
||||
self.waitingForRestart = false;
|
||||
|
||||
var options = {
|
||||
title: gettext("Restart successful!"),
|
||||
text: gettext("The server was restarted successfully. The page will now reload automatically."),
|
||||
type: "success",
|
||||
hide: false
|
||||
};
|
||||
self._showPopup(options);
|
||||
self.updateInProgress = false;
|
||||
|
||||
var delay = 5 + Math.floor(Math.random() * 5) + 1;
|
||||
setTimeout(function() {location.reload(true);}, delay * 1000);
|
||||
if (!self.reloadOverlay.is(":visible")) {
|
||||
self.reloadOverlay.show();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -438,7 +497,7 @@ $(function() {
|
||||
self.waitingForRestart = false;
|
||||
|
||||
self._markDone(text, "message_error");
|
||||
}, 30000);
|
||||
}, 60000);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,21 @@
|
||||
<div class="alert" data-bind="visible: octoprintUnconfigured()">{% trans %}
|
||||
Please configure the <strong>checkout folder</strong> of OctoPrint, otherwise
|
||||
this plugin won't be able to update it. Click on the <i class="icon-wrench"></i> button
|
||||
to do this. Also refer to the <a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
|
||||
{% endtrans %}</div>
|
||||
<div class="alert" data-bind="visible: !octoprintUnconfigured() && octoprintUnreleased()">{% trans %}
|
||||
<p>
|
||||
<strong>You are running a non-release version of OctoPrint but are tracking OctoPrint
|
||||
releases.</strong>
|
||||
</p><p>
|
||||
You probably want OctoPrint to track the matching development version instead.
|
||||
If you have a local OctoPrint checkout folder switched to another branch,
|
||||
<strong>simply switching over to "Commit" tracking</strong> will already
|
||||
take care of that. Otherwise please take a look at the
|
||||
<a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
|
||||
</p>
|
||||
{% endtrans %}</div>
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
|
||||
</div>
|
||||
@@ -11,7 +29,7 @@
|
||||
<span data-bind="invisible: !updateAvailable"><i class="icon-bell" title="{{ _('Update available') }}"></i></span>
|
||||
</td>
|
||||
<td class="settings_plugin_softwareupdate_column_information">
|
||||
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span><br>
|
||||
<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>
|
||||
@@ -44,7 +62,7 @@
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }">{{ _('Force check for update (overrides cache used for update checks)') }}</button>
|
||||
<button class="btn btn-block btn-danger" data-bind="click: function() { $root.update(true); }">{{ _('Force update now (even if no new versions are available)') }}</button>
|
||||
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.update(true); }">{{ _('Force update now (even if no new versions are available)') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -56,15 +74,15 @@
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Restart Command') }}</label>
|
||||
<label class="control-label">{{ _('OctoPrint checkout folder') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_restartCommand">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_checkoutFolder">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Reboot Command') }}</label>
|
||||
<label class="control-label">{{ _('OctoPrint version tracking') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_rebootCommand">
|
||||
<select data-bind="value: config_checkType, options: config_availableCheckTypes, optionsText: 'name', optionsValue: 'key'"></select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
|
||||
@@ -7,13 +7,16 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
|
||||
import logging
|
||||
import pkg_resources
|
||||
|
||||
from octoprint.util.pip import PipCaller, UnknownPip
|
||||
from .. import exceptions
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
|
||||
console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip.console")
|
||||
|
||||
_pip_callers = dict()
|
||||
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
|
||||
|
||||
def can_perform_update(target, check):
|
||||
pip_caller = _get_pip_caller(command=check["pip_command"] if "pip_command" in check else None)
|
||||
@@ -39,7 +42,7 @@ def perform_update(target, check, target_version, log_cb=None):
|
||||
|
||||
pip_caller = _get_pip_caller(command=pip_command)
|
||||
if pip_caller is None:
|
||||
raise RuntimeError("Can't run pip")
|
||||
raise exceptions.UpdateError("Can't run pip", None)
|
||||
|
||||
def _log_call(*lines):
|
||||
_log(lines, prefix=" ", stream="call")
|
||||
@@ -65,11 +68,18 @@ def perform_update(target, check, target_version, log_cb=None):
|
||||
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)]
|
||||
|
||||
pip_caller.execute(*pip_args)
|
||||
if "dependency_links" in check and check["dependency_links"]:
|
||||
pip_args += ["--process-dependency-links"]
|
||||
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||
if returncode != 0:
|
||||
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
|
||||
|
||||
logger.debug(u"Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg))
|
||||
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
||||
|
||||
pip_caller.execute(*pip_args)
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||
if returncode != 0:
|
||||
raise exceptions.UpdateError("Error while executing pip install --force-reinstall", (stdout, stderr))
|
||||
|
||||
return "ok"
|
||||
@@ -37,7 +37,17 @@ def _get_caller(log_cb=None):
|
||||
|
||||
|
||||
def can_perform_update(target, check):
|
||||
return "update_script" in check and ("checkout_folder" in check or "update_folder" in check)
|
||||
import os
|
||||
script_configured = bool("update_script" in check and check["update_script"])
|
||||
|
||||
folder = None
|
||||
if "update_folder" in check:
|
||||
folder = check["update_folder"]
|
||||
elif "checkout_folder" in check:
|
||||
folder = check["checkout_folder"]
|
||||
folder_configured = bool(folder and os.path.isdir(folder))
|
||||
|
||||
return script_configured and folder_configured
|
||||
|
||||
|
||||
def perform_update(target, check, target_version, log_cb=None):
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -16,17 +16,28 @@ from serial import SerialTimeoutException
|
||||
from octoprint.settings import settings
|
||||
from octoprint.plugin import plugin_manager
|
||||
|
||||
class VirtualPrinter():
|
||||
class VirtualPrinter(object):
|
||||
command_regex = re.compile("[GM]\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+)")
|
||||
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"])
|
||||
@@ -65,6 +76,7 @@ class VirtualPrinter():
|
||||
self._heatupThread = None
|
||||
|
||||
self._okBeforeCommandOutput = settings().getBoolean(["devel", "virtualPrinter", "okBeforeCommandOutput"])
|
||||
self._supportM112 = settings().getBoolean(["devel", "virtualPrinter", "supportM112"])
|
||||
|
||||
self._sendWait = settings().getBoolean(["devel", "virtualPrinter", "sendWait"])
|
||||
self._waitInterval = settings().getFloat(["devel", "virtualPrinter", "waitInterval"])
|
||||
@@ -83,9 +95,7 @@ class VirtualPrinter():
|
||||
|
||||
self._action_hooks = plugin_manager().get_hooks("octoprint.plugin.virtual_printer.custom_action")
|
||||
|
||||
|
||||
waitThread = threading.Thread(target=self._sendWaitAfterTimeout)
|
||||
waitThread.start()
|
||||
self._killed = False
|
||||
|
||||
readThread = threading.Thread(target=self._processIncoming)
|
||||
readThread.start()
|
||||
@@ -106,14 +116,14 @@ class VirtualPrinter():
|
||||
|
||||
def _processIncoming(self):
|
||||
next_wait_timeout = time.time() + self._waitInterval
|
||||
while self.incoming is not None:
|
||||
while self.incoming is not None and not self._killed:
|
||||
self._simulateTemps()
|
||||
|
||||
try:
|
||||
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
|
||||
|
||||
@@ -133,7 +143,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
|
||||
@@ -168,7 +178,7 @@ 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())
|
||||
@@ -192,7 +202,7 @@ class VirtualPrinter():
|
||||
self._listSd()
|
||||
elif 'M21' in data:
|
||||
self._sdCardReady = True
|
||||
self.outgoing.put("SD card ok")
|
||||
self._send("SD card ok")
|
||||
elif 'M22' in data:
|
||||
self._sdCardReady = False
|
||||
elif 'M23' in data:
|
||||
@@ -225,20 +235,22 @@ class VirtualPrinter():
|
||||
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"
|
||||
output = "C: X:{} Y:{} Z:{} E:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE)
|
||||
if not self._okBeforeCommandOutput:
|
||||
output = "ok " + output
|
||||
self.outgoing.put(output)
|
||||
self._send(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))
|
||||
self._send("echo:%s" % re.search("M117\s+(.*)", data).group(1))
|
||||
elif "M400" in data:
|
||||
self.buffered.join()
|
||||
elif "M999" in data:
|
||||
# mirror Marlin behaviour
|
||||
self.outgoing.put("Resend: 1")
|
||||
self._send("Resend: 1")
|
||||
elif data.startswith("T"):
|
||||
self.currentExtruder = int(re.search("T(\d+)", data).group(1))
|
||||
self.outgoing.put("Active Extruder: %d" % self.currentExtruder)
|
||||
self._send("Active Extruder: %d" % self.currentExtruder)
|
||||
elif "G20" in data:
|
||||
self._unitModifier = 1.0 / 2.54
|
||||
if self._lastX is not None:
|
||||
@@ -266,9 +278,10 @@ class VirtualPrinter():
|
||||
elif "G92" in data:
|
||||
self._setPosition(data)
|
||||
|
||||
elif data.startswith("G0") or data.startswith("G1") or data.startswith("G2") or data.startswith("G3") \
|
||||
or data.startswith("G28") or data.startswith("G29") or data.startswith("G30") \
|
||||
or data.startswith("G31") or data.startswith("G32"):
|
||||
elif data.startswith("G28"):
|
||||
self._performMove(data)
|
||||
|
||||
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)
|
||||
|
||||
@@ -285,12 +298,18 @@ class VirtualPrinter():
|
||||
del self._sleepAfterNext[command]
|
||||
|
||||
if interval is not None:
|
||||
self.outgoing.put("// sleeping for {interval} seconds".format(interval=interval))
|
||||
self._send("// sleeping for {interval} seconds".format(interval=interval))
|
||||
time.sleep(interval)
|
||||
|
||||
if len(data.strip()) > 0 and not self._okBeforeCommandOutput:
|
||||
self._sendOk()
|
||||
|
||||
def _kill(self):
|
||||
if not self._supportM112:
|
||||
return
|
||||
self._killed = True
|
||||
self._send("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.")
|
||||
|
||||
def _triggerResend(self, expected=None, actual=None):
|
||||
with self._incoming_lock:
|
||||
if expected is None:
|
||||
@@ -299,20 +318,25 @@ 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))
|
||||
|
||||
self.outgoing.put("Resend:%d" % expected)
|
||||
self.outgoing.put("ok")
|
||||
def request_resend():
|
||||
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")
|
||||
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":
|
||||
@@ -330,28 +354,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),
|
||||
@@ -363,20 +387,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:
|
||||
@@ -393,9 +417,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"])
|
||||
@@ -432,7 +456,7 @@ class VirtualPrinter():
|
||||
|
||||
if includeOk:
|
||||
output = "ok " + output
|
||||
self.outgoing.put(output)
|
||||
self._send(output)
|
||||
|
||||
def _parseHotendCommand(self, line):
|
||||
tool = 0
|
||||
@@ -454,7 +478,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:
|
||||
@@ -465,7 +489,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)
|
||||
@@ -516,14 +540,10 @@ class VirtualPrinter():
|
||||
pass
|
||||
|
||||
if duration:
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "waitOnLongMoves"]):
|
||||
slept = 0
|
||||
while duration - slept > self._read_timeout:
|
||||
time.sleep(self._read_timeout)
|
||||
self.outgoing.put("wait")
|
||||
slept += self._read_timeout
|
||||
else:
|
||||
time.sleep(duration)
|
||||
slept = 0
|
||||
while duration - slept > self._read_timeout and not self._killed:
|
||||
time.sleep(self._read_timeout)
|
||||
slept += self._read_timeout
|
||||
|
||||
def _setPosition(self, line):
|
||||
matchX = re.search("X([0-9.]+)", line)
|
||||
@@ -563,11 +583,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
|
||||
@@ -577,6 +597,9 @@ class VirtualPrinter():
|
||||
self._selectedSdFilePos = 0
|
||||
with open(self._selectedSdFile, "r") as f:
|
||||
for line in iter(f.readline, ""):
|
||||
if self._killed:
|
||||
break
|
||||
|
||||
# reset position if requested by client
|
||||
if self._newSdFilePos is not None:
|
||||
f.seek(self._newSdFilePos)
|
||||
@@ -599,21 +622,21 @@ 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
|
||||
delay = 1
|
||||
if heater.startswith("tool"):
|
||||
toolNum = int(heater[len("tool"):])
|
||||
while self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta:
|
||||
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 self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta:
|
||||
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):
|
||||
@@ -653,6 +676,7 @@ class VirtualPrinter():
|
||||
continue
|
||||
|
||||
self._performMove(line)
|
||||
self.buffered.task_done()
|
||||
|
||||
def write(self, data):
|
||||
if self._debug_drop_connection:
|
||||
@@ -662,8 +686,15 @@ class VirtualPrinter():
|
||||
with self._incoming_lock:
|
||||
if self.incoming is None or self.outgoing is None:
|
||||
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()
|
||||
@@ -675,6 +706,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 ""
|
||||
@@ -685,15 +717,22 @@ class VirtualPrinter():
|
||||
self.buffered = None
|
||||
|
||||
def _sendOk(self):
|
||||
if self.outgoing is None:
|
||||
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):
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -12,7 +12,7 @@ import re
|
||||
import logging
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import dict_merge, dict_clean, dict_contains_keys
|
||||
from octoprint.util import dict_merge, dict_sanitize, dict_contains_keys
|
||||
|
||||
class SaveError(Exception):
|
||||
pass
|
||||
@@ -214,7 +214,7 @@ class PrinterProfileManager(object):
|
||||
|
||||
identifier = self._sanitize(identifier)
|
||||
profile["id"] = identifier
|
||||
profile = dict_clean(profile, self.__class__.default)
|
||||
profile = dict_sanitize(profile, self.__class__.default)
|
||||
|
||||
if identifier == "_default":
|
||||
default_profile = dict_merge(self._load_default(), profile)
|
||||
@@ -329,12 +329,14 @@ class PrinterProfileManager(object):
|
||||
if os.path.exists(path) and not allow_overwrite:
|
||||
raise SaveError("Profile %s already exists and not allowed to overwrite" % profile["id"])
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
import yaml
|
||||
with open(path, "wb") as f:
|
||||
try:
|
||||
try:
|
||||
with atomic_write(path, "wb") as f:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
except Exception as e:
|
||||
raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e)))
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while trying to save profile %s" % profile["id"])
|
||||
raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e)))
|
||||
|
||||
def _remove_from_path(self, path):
|
||||
try:
|
||||
@@ -406,7 +408,7 @@ class PrinterProfileManager(object):
|
||||
for path in (("volume", "width"), ("volume", "depth"), ("volume", "height"), ("extruder", "nozzleDiameter")):
|
||||
try:
|
||||
convert_value(profile, path, float)
|
||||
except:
|
||||
except Exception as e:
|
||||
self._logger.warn("Profile has invalid value for path {path!r}: {msg}".format(path=".".join(path), msg=str(e)))
|
||||
return False
|
||||
|
||||
@@ -414,7 +416,7 @@ class PrinterProfileManager(object):
|
||||
for path in (("axes", "x", "inverted"), ("axes", "y", "inverted"), ("axes", "z", "inverted")):
|
||||
try:
|
||||
convert_value(profile, path, bool)
|
||||
except:
|
||||
except Exception as e:
|
||||
self._logger.warn("Profile has invalid value for path {path!r}: {msg}".format(path=".".join(path), msg=str(e)))
|
||||
return False
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -389,6 +391,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window, threshold=threshold, countdown=countdown)
|
||||
|
||||
self._lastProgressReport = None
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
self._comm.startPrint()
|
||||
|
||||
@@ -425,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()
|
||||
@@ -560,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)
|
||||
@@ -644,6 +656,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if filename is not None:
|
||||
if sd:
|
||||
path_in_storage = filename
|
||||
if path_in_storage.startswith("/"):
|
||||
path_in_storage = path_in_storage[1:]
|
||||
path_on_disk = None
|
||||
else:
|
||||
path_in_storage = self._fileManager.path_in_storage(FileDestinations.LOCAL, filename)
|
||||
@@ -679,7 +693,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
# Use a string for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
if not sd:
|
||||
date = int(os.stat(path_on_disk).st_ctime)
|
||||
date = int(os.stat(path_on_disk).st_mtime)
|
||||
|
||||
try:
|
||||
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk)
|
||||
@@ -774,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)
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -81,7 +82,7 @@ def on_identity_loaded(sender, identity):
|
||||
if user is None:
|
||||
return
|
||||
|
||||
identity.provides.add(UserNeed(user.get_name()))
|
||||
identity.provides.add(UserNeed(user.get_id()))
|
||||
if user.is_user():
|
||||
identity.provides.add(RoleNeed("user"))
|
||||
if user.is_admin():
|
||||
@@ -98,9 +99,9 @@ def load_user(id):
|
||||
|
||||
if userManager is not None:
|
||||
if sessionid:
|
||||
return userManager.findUser(username=id, session=sessionid)
|
||||
return userManager.findUser(userid=id, session=sessionid)
|
||||
else:
|
||||
return userManager.findUser(username=id)
|
||||
return userManager.findUser(userid=id)
|
||||
return users.DummyUser()
|
||||
|
||||
|
||||
@@ -187,6 +188,15 @@ class Server():
|
||||
appSessionManager = util.flask.AppSessionManager()
|
||||
pluginLifecycleManager = LifecycleManager(pluginManager)
|
||||
|
||||
# setup access control
|
||||
if self._settings.getBoolean(["accessControl", "enabled"]):
|
||||
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 %s, will run with accessControl disabled!" % userManagerName)
|
||||
|
||||
def octoprint_plugin_inject_factory(name, implementation):
|
||||
if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
|
||||
return None
|
||||
@@ -200,7 +210,8 @@ class Server():
|
||||
printer=printer,
|
||||
app_session_manager=appSessionManager,
|
||||
plugin_lifecycle_manager=pluginLifecycleManager,
|
||||
data_folder=os.path.join(self._settings.getBaseFolder("data"), name)
|
||||
data_folder=os.path.join(self._settings.getBaseFolder("data"), name),
|
||||
user_manager=userManager
|
||||
)
|
||||
|
||||
def settings_plugin_inject_factory(name, implementation):
|
||||
@@ -214,7 +225,7 @@ class Server():
|
||||
set_preprocessors=set_preprocessors)
|
||||
return dict(settings=plugin_settings)
|
||||
|
||||
def settings_plugin_config_migration(name, implementation):
|
||||
def settings_plugin_config_migration_and_cleanup(name, implementation):
|
||||
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
|
||||
return
|
||||
|
||||
@@ -222,11 +233,13 @@ class Server():
|
||||
settings_migrator = implementation.on_settings_migrate
|
||||
|
||||
if settings_version is not None and settings_migrator is not None:
|
||||
stored_version = implementation._settings.get_int(["_config_version"])
|
||||
stored_version = implementation._settings.get_int([octoprint.plugin.SettingsPlugin.config_version_key])
|
||||
if stored_version is None or stored_version < settings_version:
|
||||
settings_migrator(settings_version, stored_version)
|
||||
implementation._settings.set_int(["_config_version"], settings_version)
|
||||
implementation._settings.save()
|
||||
implementation._settings.set_int([octoprint.plugin.SettingsPlugin.config_version_key], settings_version)
|
||||
|
||||
implementation.on_settings_cleanup()
|
||||
implementation._settings.save()
|
||||
|
||||
implementation.on_settings_initialized()
|
||||
|
||||
@@ -236,11 +249,11 @@ class Server():
|
||||
settingsPlugins = pluginManager.get_implementations(octoprint.plugin.SettingsPlugin)
|
||||
for implementation in settingsPlugins:
|
||||
try:
|
||||
settings_plugin_config_migration(implementation._identifier, implementation)
|
||||
settings_plugin_config_migration_and_cleanup(implementation._identifier, implementation)
|
||||
except:
|
||||
self._logger.exception("Error while trying to migrate settings for plugin {}, ignoring it".format(implementation._identifier))
|
||||
|
||||
pluginManager.implementation_post_inits=[settings_plugin_config_migration]
|
||||
pluginManager.implementation_post_inits=[settings_plugin_config_migration_and_cleanup]
|
||||
|
||||
pluginManager.log_all_plugins()
|
||||
|
||||
@@ -276,15 +289,6 @@ class Server():
|
||||
if self._debug:
|
||||
events.DebugEventListener()
|
||||
|
||||
# setup access control
|
||||
if self._settings.getBoolean(["accessControl", "enabled"]):
|
||||
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 %s, will run with accessControl disabled!" % userManagerName)
|
||||
|
||||
app.wsgi_app = util.ReverseProxied(
|
||||
app.wsgi_app,
|
||||
self._settings.get(["server", "reverseProxy", "prefixHeader"]),
|
||||
@@ -331,13 +335,43 @@ class Server():
|
||||
|
||||
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
|
||||
return get_mime_type(path)
|
||||
|
||||
download_handler_kwargs = dict(
|
||||
as_attachment=True,
|
||||
allow_client_caching=False
|
||||
)
|
||||
additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
|
||||
admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))
|
||||
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not os.path.basename(path).startswith("."), status_code=404))
|
||||
|
||||
def joined_dict(*dicts):
|
||||
if not len(dicts):
|
||||
return dict()
|
||||
|
||||
joined = dict()
|
||||
for d in dicts:
|
||||
joined.update(d)
|
||||
return joined
|
||||
|
||||
server_routes = self._router.urls + [
|
||||
# various downloads
|
||||
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, dict(path=self._settings.getBaseFolder("timelapse"), as_attachment=True)),
|
||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, dict(path=self._settings.getBaseFolder("uploads"), as_attachment=True, path_validation=util.tornado.path_validation_factory(lambda path: not os.path.basename(path).startswith("."), status_code=404))),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, dict(path=self._settings.getBaseFolder("logs"), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.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.UrlForwardHandler, dict(url=self._settings.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(self._settings.getBaseFolder("generated"), "webassets")))
|
||||
]
|
||||
@@ -416,7 +450,8 @@ class Server():
|
||||
# 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)
|
||||
@@ -436,7 +471,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)
|
||||
@@ -457,7 +493,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)
|
||||
|
||||
@@ -519,6 +556,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
|
||||
@@ -546,19 +585,78 @@ 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.server.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
|
||||
filesystem_loader = jinja2.FileSystemLoader([])
|
||||
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"]
|
||||
|
||||
class SourceRootFilesystemLoader(jinja2.FileSystemLoader):
|
||||
def __init__(self, template_filter, prefix, *args, **kwargs):
|
||||
jinja2.FileSystemLoader.__init__(self, *args, **kwargs)
|
||||
self._filter = template_filter
|
||||
if not prefix.endswith("/"):
|
||||
prefix += "/"
|
||||
self._prefix = prefix
|
||||
|
||||
def get_source(self, environment, template):
|
||||
if not template.startswith(self._prefix):
|
||||
raise jinja2.TemplateNotFound(template)
|
||||
|
||||
template = template[len(self._prefix):]
|
||||
if not self._filter(template):
|
||||
raise jinja2.TemplateNotFound(template)
|
||||
|
||||
return jinja2.FileSystemLoader.get_source(self, environment, template)
|
||||
|
||||
def list_templates(self):
|
||||
templates = jinja2.FileSystemLoader.list_templates(self)
|
||||
return map(lambda t: self._prefix + t, filter(self._filter, templates))
|
||||
|
||||
loaders.append(SourceRootFilesystemLoader(lambda t: t in allowed, "_data/", root))
|
||||
|
||||
jinja_loader = jinja2.ChoiceLoader(loaders)
|
||||
app.jinja_loader = jinja_loader
|
||||
del jinja2
|
||||
|
||||
self._register_template_plugins()
|
||||
|
||||
@@ -660,16 +758,58 @@ class Server():
|
||||
# clean the folder
|
||||
if self._settings.getBoolean(["devel", "webassets", "clean_on_startup"]):
|
||||
import shutil
|
||||
import errno
|
||||
import sys
|
||||
|
||||
for entry in ("webassets", ".webassets-cache"):
|
||||
path = os.path.join(base_folder, entry)
|
||||
self._logger.debug("Deleting {path}...".format(**locals()))
|
||||
|
||||
# delete path if it exists
|
||||
if os.path.isdir(path):
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
elif os.path.isfile(path):
|
||||
try:
|
||||
os.remove(path)
|
||||
self._logger.debug("Deleting {path}...".format(**locals()))
|
||||
shutil.rmtree(path)
|
||||
except:
|
||||
self._logger.exception("Exception while trying to delete {entry} from {base_folder}".format(**locals()))
|
||||
self._logger.exception("Error while trying to delete {path}, leaving it alone".format(**locals()))
|
||||
continue
|
||||
|
||||
# re-create path
|
||||
self._logger.debug("Creating {path}...".format(**locals()))
|
||||
error_text = "Error while trying to re-create {path}, that might cause errors with the webassets cache".format(**locals())
|
||||
try:
|
||||
os.makedirs(path)
|
||||
except OSError as e:
|
||||
if e.errno == errno.EACCES:
|
||||
# that might be caused by the user still having the folder open somewhere, let's try again after
|
||||
# waiting a bit
|
||||
import time
|
||||
for n in xrange(3):
|
||||
time.sleep(0.5)
|
||||
self._logger.debug("Creating {path}: Retry #{retry} after {time}s".format(path=path, retry=n+1, time=(n + 1)*0.5))
|
||||
try:
|
||||
os.makedirs(path)
|
||||
break
|
||||
except:
|
||||
if self._logger.isEnabledFor(logging.DEBUG):
|
||||
self._logger.exception("Ignored error while creating directory {path}".format(**locals()))
|
||||
pass
|
||||
else:
|
||||
# this will only get executed if we never did
|
||||
# successfully execute makedirs above
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
else:
|
||||
# not an access error, so something we don't understand
|
||||
# went wrong -> log an error and stop
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
except:
|
||||
# not an OSError, so something we don't understand
|
||||
# went wrong -> log an error and stop
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
|
||||
self._logger.info("Reset webasset folder {path}...".format(**locals()))
|
||||
|
||||
AdjustedEnvironment = type(Environment)(Environment.__name__, (Environment,), dict(
|
||||
resolver_class=util.flask.PluginAssetResolver
|
||||
@@ -688,17 +828,16 @@ class Server():
|
||||
assets.updater = UpdaterType
|
||||
|
||||
enable_gcodeviewer = self._settings.getBoolean(["gcodeViewer", "enabled"])
|
||||
enable_timelapse = (self._settings.get(["webcam", "snapshot"]) and self._settings.get(["webcam", "ffmpeg"]))
|
||||
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,
|
||||
enable_timelapse=enable_timelapse,
|
||||
preferred_stylesheet=preferred_stylesheet
|
||||
)
|
||||
|
||||
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",
|
||||
@@ -719,6 +858,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",
|
||||
@@ -728,6 +868,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",
|
||||
@@ -781,9 +941,11 @@ class Server():
|
||||
register_filter(JsDelimiterBundle)
|
||||
|
||||
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters="js_delimiter_bundler")
|
||||
if self._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")
|
||||
@@ -792,6 +954,7 @@ class Server():
|
||||
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)
|
||||
|
||||
@@ -19,7 +19,7 @@ import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util import noCachingResponseHandler, apiKeyRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login
|
||||
|
||||
|
||||
@@ -38,10 +38,13 @@ 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"
|
||||
|
||||
api.after_request(noCachingResponseHandler)
|
||||
|
||||
api.before_request(apiKeyRequestHandler)
|
||||
api.after_request(corsResponseHandler)
|
||||
|
||||
@@ -98,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
|
||||
|
||||
|
||||
@@ -139,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 is not None 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
|
||||
@@ -203,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
|
||||
|
||||
@@ -245,6 +254,9 @@ def utilTestPath():
|
||||
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 = []
|
||||
|
||||
@@ -296,6 +308,12 @@ def utilTestPath():
|
||||
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),
|
||||
@@ -334,4 +352,27 @@ def utilTestPath():
|
||||
except:
|
||||
status = False
|
||||
|
||||
return jsonify(url=url, status=response.status_code, result=status)
|
||||
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)
|
||||
@@ -7,7 +7,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
from flask import request, jsonify, make_response, url_for
|
||||
|
||||
import octoprint.util as util
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT
|
||||
@@ -18,6 +17,8 @@ import octoprint.filemanager
|
||||
import octoprint.filemanager.util
|
||||
import octoprint.slicing
|
||||
|
||||
import psutil
|
||||
|
||||
|
||||
#~~ GCODE file handling
|
||||
|
||||
@@ -29,7 +30,8 @@ def readGcodeFiles():
|
||||
filter = request.values["filter"]
|
||||
files = _getFileList(FileDestinations.LOCAL, filter=filter)
|
||||
files.extend(_getFileList(FileDestinations.SDCARD))
|
||||
return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads")))
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
|
||||
return jsonify(files=files, free=usage.free, total=usage.total)
|
||||
|
||||
|
||||
@api.route("/files/<string:origin>", methods=["GET"])
|
||||
@@ -40,7 +42,8 @@ def readGcodeFilesForOrigin(origin):
|
||||
files = _getFileList(origin)
|
||||
|
||||
if origin == FileDestinations.LOCAL:
|
||||
return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads")))
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
|
||||
return jsonify(files=files, free=usage.free, total=usage.total)
|
||||
else:
|
||||
return jsonify(files=files)
|
||||
|
||||
|
||||
@@ -15,15 +15,18 @@ from octoprint.settings import settings
|
||||
from octoprint.server import NO_CONTENT, admin_permission
|
||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
|
||||
from octoprint.server.api import api
|
||||
from octoprint.util import get_free_bytes
|
||||
|
||||
|
||||
@api.route("/logs", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def getLogFiles():
|
||||
import psutil
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("logs"))
|
||||
|
||||
files = _getLogFiles()
|
||||
return jsonify(files=files, free=get_free_bytes(settings().getBaseFolder("logs")))
|
||||
|
||||
return jsonify(files=files, free=usage.free, total=usage.total)
|
||||
|
||||
|
||||
@api.route("/logs/<path:filename>", methods=["GET"])
|
||||
|
||||
@@ -63,13 +63,15 @@ 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"]),
|
||||
"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]),
|
||||
"externalHeatupDetection": s.getBoolean(["feature", "externalHeatupDetection"]),
|
||||
"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
|
||||
"pollWatched": s.getBoolean(["feature", "pollWatched"])
|
||||
"pollWatched": s.getBoolean(["feature", "pollWatched"]),
|
||||
"ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"])
|
||||
},
|
||||
"serial": {
|
||||
"port": connectionOptions["portPreference"],
|
||||
@@ -81,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"),
|
||||
@@ -105,6 +111,7 @@ def getSettings():
|
||||
"scripts": {
|
||||
"gcode": {
|
||||
"afterPrinterConnected": None,
|
||||
"beforePrinterDisconnected": None,
|
||||
"beforePrintStarted": None,
|
||||
"afterPrintCancelled": None,
|
||||
"afterPrintDone": None,
|
||||
@@ -112,6 +119,17 @@ def getSettings():
|
||||
"afterPrintResumed": None,
|
||||
"snippets": dict()
|
||||
}
|
||||
},
|
||||
"server": {
|
||||
"commands": {
|
||||
"systemShutdownCommand": s.get(["server", "commands", "systemShutdownCommand"]),
|
||||
"systemRestartCommand": s.get(["server", "commands", "systemRestartCommand"]),
|
||||
"serverRestartCommand": s.get(["server", "commands", "serverRestartCommand"])
|
||||
},
|
||||
"diskspace": {
|
||||
"warning": s.getInt(["server", "diskspace", "warning"]),
|
||||
"critical": s.getInt(["server", "diskspace", "critical"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,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)
|
||||
|
||||
@@ -162,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():
|
||||
@@ -194,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"])
|
||||
@@ -201,6 +225,7 @@ def setSettings():
|
||||
if "externalHeatupDetection" in data["feature"].keys(): s.setBoolean(["feature", "externalHeatupDetection"], data["feature"]["externalHeatupDetection"])
|
||||
if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
|
||||
if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"])
|
||||
if "ignoreIdenticalResends" in data["feature"]: s.setBoolean(["feature", "ignoreIdenticalResends"], data["feature"]["ignoreIdenticalResends"])
|
||||
|
||||
if "serial" in data.keys():
|
||||
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
||||
@@ -210,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"])
|
||||
@@ -250,6 +279,15 @@ def setSettings():
|
||||
continue
|
||||
s.saveScript("gcode", name, script.replace("\r\n", "\n").replace("\r", "\n"))
|
||||
|
||||
if "server" in data:
|
||||
if "commands" in data["server"]:
|
||||
if "systemShutdownCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemShutdownCommand"], data["server"]["commands"]["systemShutdownCommand"])
|
||||
if "systemRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemRestartCommand"], data["server"]["commands"]["systemRestartCommand"])
|
||||
if "serverRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "serverRestartCommand"], data["server"]["commands"]["serverRestartCommand"])
|
||||
if "diskspace" in data["server"]:
|
||||
if "warning" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "warning"], data["server"]["diskspace"]["warning"])
|
||||
if "critical" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "critical"], data["server"]["diskspace"]["critical"])
|
||||
|
||||
if "plugins" in data:
|
||||
for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
|
||||
plugin_id = plugin._identifier
|
||||
@@ -265,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)
|
||||
@@ -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"])
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -29,14 +29,14 @@ def getTimelapseData():
|
||||
config = {"type": "off"}
|
||||
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
|
||||
config["type"] = "zchange"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
config["fps"] = timelapse.fps()
|
||||
config["postRoll"] = timelapse.post_roll
|
||||
config["fps"] = timelapse.fps
|
||||
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
|
||||
config["type"] = "timed"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
config["fps"] = timelapse.fps()
|
||||
config["postRoll"] = timelapse.post_roll
|
||||
config["fps"] = timelapse.fps
|
||||
config.update({
|
||||
"interval": timelapse.interval()
|
||||
"interval": timelapse.interval
|
||||
})
|
||||
|
||||
files = octoprint.timelapse.getFinishedTimelapses()
|
||||
@@ -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 +10,15 @@ from flask import Blueprint, request, make_response, jsonify
|
||||
|
||||
import octoprint.server
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.server.util import noCachingResponseHandler, corsResponseHandler
|
||||
from octoprint.settings import settings as s
|
||||
|
||||
apps = Blueprint("apps", __name__)
|
||||
|
||||
apps.after_request(noCachingResponseHandler)
|
||||
apps.after_request(corsResponseHandler)
|
||||
|
||||
@apps.route("/auth", methods=["GET"])
|
||||
def getSessionKey():
|
||||
unverified_key, valid_until = octoprint.server.appSessionManager.create()
|
||||
|
||||
@@ -80,6 +80,18 @@ def corsResponseHandler(resp):
|
||||
return resp
|
||||
|
||||
|
||||
def noCachingResponseHandler(resp):
|
||||
"""
|
||||
``after_request`` handler for blueprints which shall set no caching headers
|
||||
on their responses.
|
||||
|
||||
Sets ``Cache-Control``, ``Pragma`` and ``Expires`` headers accordingly
|
||||
to prevent all client side caching from taking place.
|
||||
"""
|
||||
|
||||
return flask.add_non_caching_response_headers(resp)
|
||||
|
||||
|
||||
def optionsAllowOrigin(request):
|
||||
"""
|
||||
Shortcut for request handling for CORS OPTIONS requests to set CORS headers.
|
||||
|
||||
@@ -123,12 +123,19 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
|
||||
|
||||
def fix_webassets_cache():
|
||||
from webassets import cache
|
||||
import os
|
||||
import tempfile
|
||||
import pickle
|
||||
import shutil
|
||||
|
||||
error_logger = logging.getLogger(__name__ + ".fix_webassets_cache")
|
||||
|
||||
def fixed_set(self, key, data):
|
||||
import os
|
||||
import tempfile
|
||||
import pickle
|
||||
import shutil
|
||||
|
||||
if not os.path.exists(self.directory):
|
||||
error_logger.warn("Cache directory {} doesn't exist, not going "
|
||||
"to attempt to write cache file".format(self.directory))
|
||||
|
||||
md5 = '%s' % cache.make_md5(self.V, key)
|
||||
filename = os.path.join(self.directory, md5)
|
||||
fd, temp_filename = tempfile.mkstemp(prefix='.' + md5,
|
||||
@@ -148,6 +155,11 @@ def fix_webassets_cache():
|
||||
import warnings
|
||||
from webassets.cache import make_md5
|
||||
|
||||
if not os.path.exists(self.directory):
|
||||
error_logger.warn("Cache directory {} doesn't exist, not going "
|
||||
"to attempt to read cache file".format(self.directory))
|
||||
return None
|
||||
|
||||
try:
|
||||
hash = make_md5(self.V, key)
|
||||
except IOError as e:
|
||||
@@ -194,12 +206,15 @@ def fix_webassets_filtertool():
|
||||
try:
|
||||
content = func().getvalue()
|
||||
if self.cache:
|
||||
log.debug('Storing result in cache with key %s', key,)
|
||||
self.cache.set(key, content)
|
||||
try:
|
||||
log.debug('Storing result in cache with key %s', key,)
|
||||
self.cache.set(key, content)
|
||||
except:
|
||||
error_logger.exception("Got an exception while trying to save file to cache, not caching")
|
||||
return MemoryHunk(content)
|
||||
except:
|
||||
error_logger.exception("Got an exception while trying to apply filter, ignoring file")
|
||||
return MemoryHunk("")
|
||||
return MemoryHunk(u"")
|
||||
|
||||
FilterTool._wrap_cache = fixed_wrap_cache
|
||||
|
||||
@@ -212,8 +227,10 @@ def passive_login():
|
||||
user = flask.ext.login.current_user
|
||||
|
||||
if user is not None and not user.is_anonymous():
|
||||
flask.g.user = user
|
||||
flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id()))
|
||||
if hasattr(user, "get_session"):
|
||||
flask.session["usersession.id"] = user.get_session()
|
||||
flask.g.user = user
|
||||
return flask.jsonify(user.asDict())
|
||||
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
|
||||
and settings().get(["accessControl", "autologinAs"]) is not None \
|
||||
@@ -237,7 +254,7 @@ def passive_login():
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
|
||||
|
||||
return ("", 204)
|
||||
return "", 204
|
||||
|
||||
|
||||
#~~ cache decorator for cacheable views
|
||||
@@ -266,11 +283,11 @@ def cached(timeout=5 * 60, key=lambda: "view/%s" % flask.request.path, unless=No
|
||||
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))
|
||||
logger.debug("Serving entry for {path} from cache (key: {key})".format(path=flask.request.path, key=cache_key))
|
||||
return rv
|
||||
|
||||
# get value from wrapped function
|
||||
logger.debug("No cache entry or refreshing cache for {path}, calling wrapped function".format(path=flask.request.path))
|
||||
logger.debug("No cache entry or refreshing cache for {path} (key: {key}), calling wrapped function".format(path=flask.request.path, key=cache_key))
|
||||
rv = f(*args, **kwargs)
|
||||
|
||||
# do not store if the "unless_response" condition is true
|
||||
@@ -307,6 +324,14 @@ def cache_check_response_headers(response):
|
||||
|
||||
return False
|
||||
|
||||
|
||||
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"
|
||||
response.headers["Expires"] = "-1"
|
||||
return response
|
||||
|
||||
|
||||
#~~ access validators for use with tornado
|
||||
|
||||
|
||||
@@ -505,7 +530,8 @@ def get_remote_address(request):
|
||||
|
||||
|
||||
def get_json_command_from_request(request, valid_commands):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
content_type = request.headers.get("Content-Type", None)
|
||||
if content_type is None or not "application/json" in content_type:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
data = request.json
|
||||
@@ -585,7 +611,7 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater):
|
||||
|
||||
##~~ plugin assets collector
|
||||
|
||||
def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, preferred_stylesheet="css"):
|
||||
def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
logger = logging.getLogger(__name__ + ".collect_plugin_assets")
|
||||
|
||||
supported_stylesheets = ("css", "less")
|
||||
@@ -598,7 +624,6 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
|
||||
'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',
|
||||
@@ -606,11 +631,15 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
|
||||
'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"] += [
|
||||
@@ -619,8 +648,6 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
|
||||
'gcodeviewer/js/gCodeReader.js',
|
||||
'gcodeviewer/js/renderer.js'
|
||||
]
|
||||
if enable_timelapse:
|
||||
assets["js"].append('js/app/viewmodels/timelapse.js')
|
||||
|
||||
if preferred_stylesheet == "less":
|
||||
assets["less"].append('less/octoprint.less')
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# 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"
|
||||
|
||||
from jinja2 import nodes
|
||||
from jinja2.ext import Extension
|
||||
|
||||
import logging
|
||||
|
||||
class ExceptionHandlerExtension(Extension):
|
||||
tags = {"try"}
|
||||
|
||||
def __init__(self, environment):
|
||||
super(ExceptionHandlerExtension, self).__init__(environment)
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
def parse(self, parser):
|
||||
token = parser.stream.next()
|
||||
lineno = token.lineno
|
||||
filename = parser.name
|
||||
error = parser.parse_expression()
|
||||
|
||||
args = [error, nodes.Const(filename), nodes.Const(lineno)]
|
||||
try:
|
||||
body = parser.parse_statements(["name:endtry"], drop_needle=True)
|
||||
node = nodes.CallBlock(self.call_method("_handle_body", args),
|
||||
[], [], body).set_lineno(lineno)
|
||||
except Exception as e:
|
||||
# that was expected
|
||||
self._logger.exception("Caught exception while parsing template")
|
||||
node = nodes.CallBlock(self.call_method("_handle_error", [nodes.Const(self._format_error(error, e, filename, lineno))]),
|
||||
[], [], []).set_lineno(lineno)
|
||||
|
||||
return node
|
||||
|
||||
def _handle_body(self, error, filename, lineno, caller):
|
||||
try:
|
||||
return caller()
|
||||
except Exception as e:
|
||||
self._logger.exception("Caught exception while compiling template {filename} at line {lineno}".format(**locals()))
|
||||
error_string = self._format_error(error, e, filename, lineno)
|
||||
return error_string if error_string else ""
|
||||
|
||||
def _handle_error(self, error, caller):
|
||||
return error if error else ""
|
||||
|
||||
def _format_error(self, error, exception, filename, lineno):
|
||||
if not error:
|
||||
return ""
|
||||
|
||||
try:
|
||||
return error.format(exception=exception, filename=filename, lineno=lineno)
|
||||
except:
|
||||
self._logger.exception("Error while compiling exception output for template {filename} at line {lineno}".format(**locals()))
|
||||
return "Unknown error"
|
||||
|
||||
trycatch = ExceptionHandlerExtension
|
||||
@@ -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,8 +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, "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)
|
||||
|
||||
@@ -245,7 +245,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
||||
self._on_part_header(self._buffer[delimiter_len+2:end_of_header])
|
||||
self._buffer = self._buffer[end_of_header + 4:]
|
||||
|
||||
if delimiter_loc != -1 and self._buffer[delimiter_len:delimiter_len+2] == "--":
|
||||
if delimiter_loc != -1 and self._buffer.strip() == delimiter + "--":
|
||||
# we saw the last boundary and are at the end of our request
|
||||
if self._current_part:
|
||||
self._on_part_finish(self._current_part)
|
||||
@@ -360,13 +360,24 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
||||
for name, part in self._parts.iteritems():
|
||||
if "filename" in part:
|
||||
# add form fields for filename, path, size and content_type for all files contained in the request
|
||||
fields = dict((self._suffixes[key], value) for (key, value) in dict(name=part["filename"], path=part["path"], size=str(os.stat(part["path"]).st_size), content_type=part["content_type"]).iteritems())
|
||||
if not "path" in part:
|
||||
continue
|
||||
|
||||
parameters = dict(
|
||||
name=part["filename"],
|
||||
path=part["path"],
|
||||
size=str(os.stat(part["path"]).st_size)
|
||||
)
|
||||
if "content_type" in part:
|
||||
parameters["content_type"] = part["content_type"]
|
||||
|
||||
fields = dict((self._suffixes[key], value) for (key, value) in parameters.iteritems())
|
||||
for n, p in fields.iteritems():
|
||||
key = name + "." + n
|
||||
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
||||
self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key
|
||||
self._new_body += b"\r\n"
|
||||
self._new_body += p + b"\r\n"
|
||||
self._new_body += b"%s\r\n" % p
|
||||
elif "data" in part:
|
||||
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
||||
value = part["data"]
|
||||
@@ -757,6 +768,8 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
:class:``~tornado.web.StaticFileHandler`` as the ``default_filename`` keyword parameter). Defaults to ``None``.
|
||||
as_attachment (bool): Whether to serve requested files with ``Content-Disposition: attachment`` header (``True``)
|
||||
or not. Defaults to ``False``.
|
||||
allow_client_caching (bool): Whether to allow the client to cache (by not setting any ``Cache-Control`` or
|
||||
``Expires`` headers on the response) or not.
|
||||
access_validation (function): Callback to call in the ``get`` method to validate access to the resource. Will
|
||||
be called with ``self.request`` as parameter which contains the full tornado request object. Should raise
|
||||
a ``tornado.web.HTTPError`` if access is not allowed in which case the request will not be further processed.
|
||||
@@ -765,13 +778,22 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
with the requested path as parameter. Should raise a ``tornado.web.HTTPError`` (e.g. an 404) if the requested
|
||||
path does not pass validation in which case the request will not be further processed.
|
||||
Defaults to ``None`` and hence no path validation being performed.
|
||||
etag_generator (function): Callback to call for generating the value of the ETag response header. Will be
|
||||
called with the response handler as parameter. May return ``None`` to prevent the ETag response header
|
||||
from being set. If not provided the last modified time of the file in question will be used as returned
|
||||
by ``get_content_version``.
|
||||
"""
|
||||
|
||||
def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None, path_validation=None):
|
||||
def initialize(self, path, default_filename=None, as_attachment=False, allow_client_caching=True,
|
||||
access_validation=None, path_validation=None, etag_generator=None,
|
||||
mime_type_guesser=None):
|
||||
tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename)
|
||||
self._as_attachment = as_attachment
|
||||
self._allow_client_caching = allow_client_caching
|
||||
self._access_validation = access_validation
|
||||
self._path_validation = path_validation
|
||||
self._etag_generator = etag_generator
|
||||
self._mime_type_guesser = mime_type_guesser
|
||||
|
||||
def get(self, path, include_body=True):
|
||||
if self._access_validation is not None:
|
||||
@@ -785,6 +807,24 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
if self._as_attachment:
|
||||
self.set_header("Content-Disposition", "attachment")
|
||||
|
||||
if not self._allow_client_caching:
|
||||
self.set_header("Cache-Control", "max-age=0, must-revalidate, private")
|
||||
self.set_header("Expires", "-1")
|
||||
|
||||
def compute_etag(self):
|
||||
if self._etag_generator is not None:
|
||||
return self._etag_generator(self)
|
||||
else:
|
||||
return self.get_content_version(self.absolute_path)
|
||||
|
||||
def get_content_type(self):
|
||||
if self._mime_type_guesser is not None:
|
||||
type = self._mime_type_guesser(self.absolute_path)
|
||||
if type is not None:
|
||||
return type
|
||||
|
||||
return tornado.web.StaticFileHandler.get_content_type(self)
|
||||
|
||||
@classmethod
|
||||
def get_content_version(cls, abspath):
|
||||
import os
|
||||
@@ -794,7 +834,7 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
##~~ URL Forward Handler for forwarding requests to a preconfigured static URL
|
||||
|
||||
|
||||
class UrlForwardHandler(tornado.web.RequestHandler):
|
||||
class UrlProxyHandler(tornado.web.RequestHandler):
|
||||
"""
|
||||
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that proxies
|
||||
requests to a preconfigured url and returns the response. Allows delivery of the requested content as attachment
|
||||
@@ -804,7 +844,7 @@ class UrlForwardHandler(tornado.web.RequestHandler):
|
||||
for making the request to the configured endpoint and return the body of the client response with the status code
|
||||
from the client response and the following headers:
|
||||
|
||||
* ``Date``, ``Cache-Control``, ``Server``, ``Content-Type`` and ``Location`` will be copied over.
|
||||
* ``Date``, ``Cache-Control``, ``Expires``, ``ETag``, ``Server``, ``Content-Type`` and ``Location`` will be copied over.
|
||||
* If ``as_attachment`` is set to True, ``Content-Disposition`` will be set to ``attachment``. If ``basename`` is
|
||||
set including the attachement's ``filename`` attribute will be set to the base name followed by the extension
|
||||
guessed based on the MIME type from the ``Content-Type`` header of the response. If no extension can be guessed
|
||||
@@ -854,7 +894,7 @@ class UrlForwardHandler(tornado.web.RequestHandler):
|
||||
filename = None
|
||||
|
||||
self.set_status(response.code)
|
||||
for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location"):
|
||||
for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location", "Expires", "ETag"):
|
||||
value = response.headers.get(name)
|
||||
if value:
|
||||
self.set_header(name, value)
|
||||
@@ -924,4 +964,4 @@ def path_validation_factory(path_filter, status_code=404):
|
||||
def f(path):
|
||||
if not path_filter(path):
|
||||
raise tornado.web.HTTPError(status_code)
|
||||
return f
|
||||
return f
|
||||
+191
-52
@@ -6,34 +6,122 @@ __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
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.server import app, userManager, pluginManager, gettext, debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY
|
||||
from octoprint.server import app, userManager, pluginManager, gettext, \
|
||||
debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY, BRANCH
|
||||
from octoprint.settings import settings
|
||||
|
||||
import re
|
||||
|
||||
from . import util
|
||||
|
||||
import logging
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
@app.route("/")
|
||||
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values,
|
||||
key=lambda: "view/%s/%s" % (request.path, g.locale),
|
||||
unless_response=util.flask.cache_check_response_headers)
|
||||
def index():
|
||||
_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("/")
|
||||
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_cached_view(key, view):
|
||||
return util.flask.cached(refreshif=lambda: force_refresh,
|
||||
key=lambda: "ui:{}:{}".format(key, g.locale),
|
||||
unless_response=util.flask.cache_check_response_headers)(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)
|
||||
response = cached(now, request, render_kwargs)
|
||||
if response is not None:
|
||||
break
|
||||
|
||||
else:
|
||||
wizard = wizard_active(_templates)
|
||||
enable_accesscontrol = userManager is not None
|
||||
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)
|
||||
response = cached()
|
||||
|
||||
response.headers["Last-Modified"] = now
|
||||
|
||||
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 is not None
|
||||
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
|
||||
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
|
||||
|
||||
@@ -46,6 +134,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)
|
||||
)
|
||||
|
||||
@@ -56,6 +146,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)
|
||||
)
|
||||
|
||||
@@ -142,7 +234,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),
|
||||
@@ -150,6 +242,7 @@ def index():
|
||||
folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)),
|
||||
appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)),
|
||||
logs=(gettext("Logs"), dict(template="dialogs/settings/logs.jinja2", _div="settings_logs")),
|
||||
server=(gettext("Server"), dict(template="dialogs/settings/server.jinja2", _div="settings_server", custom_bindings=False)),
|
||||
)
|
||||
if enable_accesscontrol:
|
||||
templates["settings"]["entries"]["accesscontrol"] = (gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False))
|
||||
@@ -162,19 +255,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
|
||||
@@ -189,6 +315,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":
|
||||
@@ -226,12 +355,48 @@ def index():
|
||||
if len(missing_in_order) == 0:
|
||||
continue
|
||||
|
||||
# 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 default_value
|
||||
|
||||
# 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:
|
||||
# anything but navbar and generic components get sorted by their name
|
||||
if template_sorting[t]["key"] == "name":
|
||||
sorted_missing = sorted(missing_in_order, key=lambda x: templates[t]["entries"][x][0])
|
||||
# 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"]):
|
||||
def create_safe_extractor(extractor):
|
||||
def f(x, k):
|
||||
try:
|
||||
return extractor(x, k)
|
||||
except:
|
||||
_logger.exception("Error while extracting sorting keys for template {}".format(t))
|
||||
return None
|
||||
return f
|
||||
extractor = create_safe_extractor(template_sorting[t]["key_extractor"])
|
||||
|
||||
sort_key = template_sorting[t]["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"]
|
||||
@@ -243,44 +408,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,
|
||||
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.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0"
|
||||
response.headers["Pragma"] = "no-cache"
|
||||
response.headers["Expires"] = "-1"
|
||||
|
||||
return response
|
||||
return templates, plugin_names, plugin_vars
|
||||
|
||||
|
||||
def _process_template_configs(name, implementation, configs, rules):
|
||||
@@ -319,6 +451,8 @@ def _process_template_configs(name, implementation, configs, rules):
|
||||
app.jinja_env.get_or_select_template(data["template"])
|
||||
except TemplateNotFound:
|
||||
pass
|
||||
except:
|
||||
_logger.exception("Error in template {}, not going to include it".format(data["template"]))
|
||||
else:
|
||||
includes[template_type].append(rule["to_entry"](data))
|
||||
|
||||
@@ -343,6 +477,9 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
|
||||
data["_div"] = rule["div"](name)
|
||||
if "suffix" in data:
|
||||
data["_div"] = data["_div"] + data["suffix"]
|
||||
if not _valid_div_re.match(data["_div"]):
|
||||
_logger.warn("Template config {} contains invalid div identifier {}, skipping it".format(name, data["_div"]))
|
||||
return None
|
||||
|
||||
if not "template" in data:
|
||||
data["template"] = rule["template"](name)
|
||||
@@ -354,6 +491,7 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
|
||||
data_bind = "allowBindings: true"
|
||||
if "data_bind" in data:
|
||||
data_bind = data_bind + ", " + data["data_bind"]
|
||||
data_bind = data_bind.replace("\"", "\\\"")
|
||||
data["data_bind"] = data_bind
|
||||
|
||||
data["_key"] = "plugin_" + name
|
||||
@@ -362,13 +500,15 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
@app.route("/robots.txt")
|
||||
def robotsTxt():
|
||||
return send_from_directory(app.static_folder, "robots.txt")
|
||||
|
||||
|
||||
@app.route("/i18n/<string:locale>/<string:domain>.js")
|
||||
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values, key=lambda: "view/%s/%s" % (request.path, g.locale))
|
||||
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values,
|
||||
key=lambda: "{}:{}".format(request.path, g.locale))
|
||||
def localeJs(locale, domain):
|
||||
messages = dict()
|
||||
plural_expr = None
|
||||
@@ -448,4 +588,3 @@ def localeJs(locale, domain):
|
||||
def plugin_assets(name, filename):
|
||||
return redirect(url_for("plugin." + name + ".static", filename=filename))
|
||||
|
||||
|
||||
+126
-35
@@ -30,6 +30,8 @@ import logging
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
_APPNAME = "OctoPrint"
|
||||
|
||||
_instance = None
|
||||
@@ -80,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",
|
||||
@@ -104,6 +111,15 @@ default_settings = {
|
||||
"pathSuffix": "path"
|
||||
},
|
||||
"maxSize": 100 * 1024, # 100 KB
|
||||
"commands": {
|
||||
"systemShutdownCommand": None,
|
||||
"systemRestartCommand": None,
|
||||
"serverRestartCommand": None
|
||||
},
|
||||
"diskspace": {
|
||||
"warning": 500 * 1024 * 1024, # 500 MB
|
||||
"critical": 200 * 1024 * 1024, # 200 MB
|
||||
}
|
||||
},
|
||||
"webcam": {
|
||||
"stream": None,
|
||||
@@ -134,6 +150,7 @@ default_settings = {
|
||||
"temperatureGraph": True,
|
||||
"waitForStartOnConnect": False,
|
||||
"alwaysSendChecksum": False,
|
||||
"neverSendChecksum": False,
|
||||
"sendChecksumWithUnknownCommands": False,
|
||||
"unknownCommandsNeedAck": False,
|
||||
"sdSupport": True,
|
||||
@@ -143,7 +160,9 @@ default_settings = {
|
||||
"externalHeatupDetection": True,
|
||||
"supportWait": True,
|
||||
"keyboardControl": True,
|
||||
"pollWatched": False
|
||||
"pollWatched": False,
|
||||
"ignoreIdenticalResends": False,
|
||||
"identicalResendsCountdown": 7
|
||||
},
|
||||
"folder": {
|
||||
"uploads": None,
|
||||
@@ -188,9 +207,11 @@ default_settings = {
|
||||
"settings": [
|
||||
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
|
||||
"section_features", "features", "webcam", "accesscontrol", "api",
|
||||
"section_octoprint", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate"
|
||||
"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": {
|
||||
@@ -271,6 +292,7 @@ default_settings = {
|
||||
},
|
||||
"hasBed": True,
|
||||
"repetierStyleTargetTemperature": False,
|
||||
"repetierStyleResends": False,
|
||||
"okBeforeCommandOutput": False,
|
||||
"smoothieTemperatureReporting": False,
|
||||
"extendedSdFileList": False,
|
||||
@@ -280,7 +302,8 @@ default_settings = {
|
||||
"txBuffer": 40,
|
||||
"commandBuffer": 4,
|
||||
"sendWait": True,
|
||||
"waitInterval": 1.0
|
||||
"waitInterval": 1.0,
|
||||
"supportM112": True
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -289,6 +312,11 @@ default_settings = {
|
||||
valid_boolean_trues = [True, "true", "yes", "y", "1"]
|
||||
""" Values that are considered to be equivalent to the boolean ``True`` value, used for type conversion in various places."""
|
||||
|
||||
|
||||
class NoSuchSettingsPath(BaseException):
|
||||
pass
|
||||
|
||||
|
||||
class Settings(object):
|
||||
"""
|
||||
The :class:`Settings` class allows managing all of OctoPrint's settings. It takes care of initializing the settings
|
||||
@@ -321,14 +349,14 @@ class Settings(object):
|
||||
|
||||
"/dev/ttyACM0"
|
||||
|
||||
``["serial", "timeouts"]`` ::
|
||||
``["serial", "timeout"]`` ::
|
||||
|
||||
communication: 20.0
|
||||
temperature: 5.0
|
||||
sdStatus: 1.0
|
||||
connection: 10.0
|
||||
|
||||
``["serial", "timeouts", "temperature"]`` ::
|
||||
``["serial", "timeout", "temperature"]`` ::
|
||||
|
||||
5.0
|
||||
|
||||
@@ -536,6 +564,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):
|
||||
@@ -774,11 +816,17 @@ class Settings(object):
|
||||
if not self._dirty and not force:
|
||||
return False
|
||||
|
||||
with open(self._configfile, "wb") as configFile:
|
||||
yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._dirty = False
|
||||
self.load()
|
||||
return True
|
||||
from octoprint.util import atomic_write
|
||||
try:
|
||||
with atomic_write(self._configfile, "wb", prefix="octoprint-config-", suffix=".yaml") as configFile:
|
||||
yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._dirty = False
|
||||
except:
|
||||
self._logger.exception("Error while saving config.yaml!")
|
||||
raise
|
||||
else:
|
||||
self.load()
|
||||
return True
|
||||
|
||||
@property
|
||||
def last_modified(self):
|
||||
@@ -789,13 +837,13 @@ class Settings(object):
|
||||
stat = os.stat(self._configfile)
|
||||
return stat.st_mtime
|
||||
|
||||
#~~ getter
|
||||
##~~ Internal getter
|
||||
|
||||
def get(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True):
|
||||
def _get_value(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True):
|
||||
import octoprint.util as util
|
||||
|
||||
if len(path) == 0:
|
||||
return None
|
||||
raise NoSuchSettingsPath()
|
||||
|
||||
if config is None:
|
||||
config = self._config
|
||||
@@ -813,7 +861,7 @@ class Settings(object):
|
||||
config = {}
|
||||
defaults = defaults[key]
|
||||
else:
|
||||
return None
|
||||
raise NoSuchSettingsPath()
|
||||
|
||||
if preprocessors and isinstance(preprocessors, dict) and key in preprocessors:
|
||||
preprocessors = preprocessors[key]
|
||||
@@ -837,7 +885,7 @@ class Settings(object):
|
||||
elif incl_defaults and key in defaults:
|
||||
value = defaults[key]
|
||||
else:
|
||||
value = None
|
||||
raise NoSuchSettingsPath()
|
||||
|
||||
if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]):
|
||||
value = preprocessors[key](value)
|
||||
@@ -855,8 +903,34 @@ class Settings(object):
|
||||
else:
|
||||
return results
|
||||
|
||||
def getInt(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
|
||||
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
|
||||
#~~ has
|
||||
|
||||
def has(self, path, **kwargs):
|
||||
try:
|
||||
self._get_value(path, **kwargs)
|
||||
except NoSuchSettingsPath:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
#~~ getter
|
||||
|
||||
def get(self, path, **kwargs):
|
||||
error_on_path = kwargs.get("error_on_path", False)
|
||||
new_kwargs = dict(kwargs)
|
||||
if "error_on_path" in new_kwargs:
|
||||
del new_kwargs["error_on_path"]
|
||||
|
||||
try:
|
||||
return self._get_value(path, **new_kwargs)
|
||||
except NoSuchSettingsPath:
|
||||
if error_on_path:
|
||||
raise
|
||||
else:
|
||||
return None
|
||||
|
||||
def getInt(self, path, **kwargs):
|
||||
value = self.get(path, **kwargs)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
@@ -866,8 +940,8 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
|
||||
def getFloat(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
|
||||
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
|
||||
def getFloat(self, path, **kwargs):
|
||||
value = self.get(path, **kwargs)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
@@ -877,8 +951,8 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
|
||||
def getBoolean(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
|
||||
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
|
||||
def getBoolean(self, path, **kwargs):
|
||||
value = self.get(path, **kwargs)
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
@@ -931,6 +1005,23 @@ class Settings(object):
|
||||
|
||||
return script
|
||||
|
||||
#~~ remove
|
||||
|
||||
def remove(self, path, config=None):
|
||||
if config is None:
|
||||
config = self._config
|
||||
|
||||
while len(path) > 1:
|
||||
key = path.pop(0)
|
||||
if not isinstance(config, dict) or key not in config:
|
||||
return
|
||||
config = config[key]
|
||||
|
||||
key = path.pop(0)
|
||||
if isinstance(config, dict) and key in config:
|
||||
del config[key]
|
||||
self._dirty = True
|
||||
|
||||
#~~ setter
|
||||
|
||||
def set(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
@@ -970,16 +1061,16 @@ class Settings(object):
|
||||
if not force and key in defaults and key in config and defaults[key] == value:
|
||||
del config[key]
|
||||
self._dirty = True
|
||||
elif force or (not key in config and defaults[key] != value) or (key in config and config[key] != value):
|
||||
elif force or (not key in config and key in defaults and defaults[key] != value) or (key in config and config[key] != value):
|
||||
if value is None and key in config:
|
||||
del config[key]
|
||||
else:
|
||||
config[key] = value
|
||||
self._dirty = True
|
||||
|
||||
def setInt(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
def setInt(self, path, value, **kwargs):
|
||||
if value is None:
|
||||
self.set(path, None, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, None, **kwargs)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -988,11 +1079,11 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
|
||||
return
|
||||
|
||||
self.set(path, intValue, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, intValue, **kwargs)
|
||||
|
||||
def setFloat(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
def setFloat(self, path, value, **kwargs):
|
||||
if value is None:
|
||||
self.set(path, None, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, None, **kwargs)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -1001,15 +1092,15 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
|
||||
return
|
||||
|
||||
self.set(path, floatValue, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, floatValue, **kwargs)
|
||||
|
||||
def setBoolean(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
def setBoolean(self, path, value, **kwargs):
|
||||
if value is None or isinstance(value, bool):
|
||||
self.set(path, value, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, value, **kwargs)
|
||||
elif value.lower() in valid_boolean_trues:
|
||||
self.set(path, True, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, True, **kwargs)
|
||||
else:
|
||||
self.set(path, False, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, False, **kwargs)
|
||||
|
||||
def setBaseFolder(self, type, path, force=False):
|
||||
if type not in default_settings["folder"].keys():
|
||||
@@ -1031,14 +1122,14 @@ class Settings(object):
|
||||
def saveScript(self, script_type, name, script):
|
||||
script_folder = self.getBaseFolder("scripts")
|
||||
filename = os.path.realpath(os.path.join(script_folder, script_type, name))
|
||||
if not filename.startswith(script_folder):
|
||||
if not filename.startswith(os.path.realpath(script_folder)):
|
||||
# oops, jail break, that shouldn't happen
|
||||
raise ValueError("Invalid script path to save to: {filename} (from {script_type}:{name})".format(**locals()))
|
||||
|
||||
path, _ = os.path.split(filename)
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
with open(filename, "w+") as f:
|
||||
with atomic_write(filename, "wb") as f:
|
||||
f.write(script)
|
||||
|
||||
def _default_basedir(applicationName):
|
||||
|
||||
@@ -39,14 +39,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):
|
||||
@@ -449,6 +451,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``.
|
||||
@@ -463,7 +509,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.
|
||||
@@ -539,7 +585,7 @@ class SlicingManager(object):
|
||||
name = self._sanitize(name)
|
||||
|
||||
path = os.path.join(self.get_slicer_profile_path(slicer), "{name}.profile".format(name=name))
|
||||
if not os.path.realpath(path).startswith(self._profile_path):
|
||||
if not os.path.realpath(path).startswith(os.path.realpath(self._profile_path)):
|
||||
raise IOError("Path to profile {name} tried to break out of allows sub path".format(**locals()))
|
||||
if must_exist and not (os.path.exists(path) and os.path.isfile(path)):
|
||||
raise UnknownProfile(slicer, name)
|
||||
@@ -559,7 +605,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 @@
|
||||
.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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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, 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);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrint"], factory);
|
||||
} else {
|
||||
factory(window.OctoPrint);
|
||||
}
|
||||
})(window || this, function(OctoPrint) {
|
||||
var customUrl = "api/printer/command/custom";
|
||||
var commandUrl = "api/printer/command";
|
||||
|
||||
var sendGcodeWithParameters = function(commands, parameters, opts) {
|
||||
commands = commands || [];
|
||||
parameters = parameters || {};
|
||||
|
||||
if (typeof commands === "string") {
|
||||
commands = [commands];
|
||||
}
|
||||
|
||||
return OctoPrint.postJson(commandUrl, {
|
||||
commands: commands,
|
||||
parameters: parameters
|
||||
}, opts);
|
||||
};
|
||||
|
||||
var sendGcodeScriptWithParameters = function(script, context, parameters, opts) {
|
||||
script = script || "";
|
||||
context = context || {};
|
||||
parameters = parameters || {};
|
||||
|
||||
return OctoPrint.postJson(commandUrl, {
|
||||
script: script,
|
||||
context: context,
|
||||
parameters: parameters
|
||||
}, opts);
|
||||
};
|
||||
|
||||
OctoPrint.control = {
|
||||
sendGcodeWithParameters: sendGcodeWithParameters,
|
||||
sendGcodeScriptWithParameters: sendGcodeScriptWithParameters,
|
||||
|
||||
getCustomControls: function (opts) {
|
||||
return OctoPrint.get(customUrl, opts);
|
||||
},
|
||||
|
||||
sendGcode: function (commands, opts) {
|
||||
return sendGcodeWithParameters(commands, undefined, opts);
|
||||
},
|
||||
|
||||
sendGcodeScript: function (script, context, opts) {
|
||||
return sendGcodeScriptWithParameters(script, context, undefined, opts);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
(function (factory) {
|
||||
'use strict';
|
||||
if (typeof define === 'function' && define.amd) {
|
||||
// Register as an anonymous AMD module:
|
||||
define(["OctoPrint", "jquery"], factory);
|
||||
} else {
|
||||
// Browser globals:
|
||||
factory(window.OctoPrint, window.jQuery);
|
||||
}
|
||||
})(function(OctoPrint, $) {
|
||||
var url = "api/files";
|
||||
|
||||
var resourceForLocation = function(location) {
|
||||
return url + "/" + location;
|
||||
};
|
||||
|
||||
var resourceForFile = function(location, filename) {
|
||||
return resourceForLocation(location) + "/" + filename;
|
||||
};
|
||||
|
||||
var issueFileCommand = function(location, filename, command, data, opts) {
|
||||
var url = resourceForFile(location, filename);
|
||||
return OctoPrint.issueCommand(url, command, data, opts);
|
||||
};
|
||||
|
||||
var getFile = function(location, filename, opts) {
|
||||
return OctoPrint.get(resourceForFile(location, filename), opts);
|
||||
};
|
||||
|
||||
OctoPrint.files = {
|
||||
get: getFile,
|
||||
|
||||
list: function (opts) {
|
||||
return OctoPrint.get(url, opts);
|
||||
},
|
||||
|
||||
listForLocation: function (location, opts) {
|
||||
return OctoPrint.get(resourceForLocation(location), opts);
|
||||
},
|
||||
|
||||
select: function (location, filename, print, opts) {
|
||||
print = print || false;
|
||||
|
||||
var data = {
|
||||
print: print
|
||||
};
|
||||
|
||||
return issueFileCommand(location, filename, "select", data, opts);
|
||||
},
|
||||
|
||||
slice: function (location, filename, parameters, opts) {
|
||||
return issueFileCommand(location, filename, "slice",
|
||||
parameters || {}, opts);
|
||||
},
|
||||
|
||||
delete: function (location, filename, opts) {
|
||||
return OctoPrint.delete(resourceForFile(location, filename), opts);
|
||||
},
|
||||
|
||||
upload: function (location, file, data) {
|
||||
data = data || {};
|
||||
|
||||
var filename = data.filename || undefined;
|
||||
return OctoPrint.upload(resourceForLocation(location), file, filename, data);
|
||||
},
|
||||
|
||||
download: function (location, filename, opts) {
|
||||
var deferred = $.Deferred();
|
||||
getFile(location, filename, opts)
|
||||
.done(function (response) {
|
||||
OctoPrint.download(response.refs.download, opts)
|
||||
.done(function () {
|
||||
deferred.resolve.apply(null, arguments);
|
||||
})
|
||||
.fail(function () {
|
||||
deferred.reject.apply(null, arguments);
|
||||
});
|
||||
})
|
||||
.fail(function () {
|
||||
deferred.reject.apply(null, arguments);
|
||||
});
|
||||
return deferred.promise();
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrint"], factory);
|
||||
} else {
|
||||
factory(window.OctoPrint);
|
||||
}
|
||||
})(window || this, function(OctoPrint) {
|
||||
var url = "api/job";
|
||||
|
||||
var issueCommand = function(command, opts) {
|
||||
return OctoPrint.issueCommand(url, command, {}, opts);
|
||||
};
|
||||
|
||||
OctoPrint.job = {
|
||||
get: function(opts) {
|
||||
return OctoPrint.get(url, opts);
|
||||
},
|
||||
start: function(opts) {
|
||||
return issueCommand("start", opts);
|
||||
},
|
||||
restart: function(opts) {
|
||||
return issueCommand("restart", opts);
|
||||
},
|
||||
pause: function(opts) {
|
||||
return issueCommand("pause", opts);
|
||||
},
|
||||
cancel: function(opts) {
|
||||
return issueCommand("cancel", opts);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrint"], factory);
|
||||
} else {
|
||||
factory(window.OctoPrint);
|
||||
}
|
||||
})(window || this, function(OctoPrint) {
|
||||
var url = "api/languages";
|
||||
|
||||
OctoPrint.languages = {
|
||||
list: function(opts) {
|
||||
return OctoPrint.get(url, opts);
|
||||
},
|
||||
upload: function(file) {
|
||||
return OctoPrint.upload(url, file);
|
||||
},
|
||||
delete: function(locale, pack, opts) {
|
||||
var packUrl = url + "/" + locale + "/" + pack;
|
||||
return OctoPrint.delete(packUrl, opts);
|
||||
}
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrint"], factory);
|
||||
} else {
|
||||
factory(window.OctoPrint);
|
||||
}
|
||||
})(window || this, function(OctoPrint) {
|
||||
var url = "api/logs";
|
||||
|
||||
OctoPrint.logs = {
|
||||
list: function(opts) {
|
||||
return OctoPrint.get(url, opts);
|
||||
},
|
||||
|
||||
delete: function(file, opts) {
|
||||
var fileUrl = url + "/" + file;
|
||||
return OctoPrint.delete(fileUrl, opts);
|
||||
},
|
||||
|
||||
download: function(file, opts) {
|
||||
var fileUrl = url + "/" + file;
|
||||
return OctoPrint.download(fileUrl, opts);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrint"], factory);
|
||||
} else {
|
||||
factory(window.OctoPrint);
|
||||
}
|
||||
})(window || this, function(OctoPrint) {
|
||||
var url = "api/printer";
|
||||
var printheadUrl = url + "/printhead";
|
||||
var toolUrl = url + "/tool";
|
||||
var bedUrl = url + "/bed";
|
||||
var sdUrl = url + "/sd";
|
||||
|
||||
var issuePrintheadCommand = function (command, payload, opts) {
|
||||
return OctoPrint.issueCommand(printheadUrl, command, payload, opts);
|
||||
};
|
||||
|
||||
var issueToolCommand = function (command, payload, opts) {
|
||||
return OctoPrint.issueCommand(toolUrl, command, payload, opts);
|
||||
};
|
||||
|
||||
var issueBedCommand = function (command, payload, opts) {
|
||||
return OctoPrint.issueCommand(bedUrl, command, payload, opts);
|
||||
};
|
||||
|
||||
var issueSdCommand = function (command, payload, opts) {
|
||||
return OctoPrint.issueCommand(sdUrl, command, payload, opts);
|
||||
};
|
||||
|
||||
OctoPrint.printer = {
|
||||
getFullState: function (data, opts) {
|
||||
data = data || {};
|
||||
|
||||
var history = data.history || undefined;
|
||||
var limit = data.limit || undefined;
|
||||
var exclude = data.exclude || undefined;
|
||||
|
||||
var getUrl = url;
|
||||
if (history || exclude) {
|
||||
getUrl += "?";
|
||||
if (history) {
|
||||
getUrl += "history=true&";
|
||||
if (limit) {
|
||||
getUrl += "limit=" + limit + "&";
|
||||
}
|
||||
}
|
||||
|
||||
if (exclude) {
|
||||
getUrl += "exclude=" + exclude.join(",") + "&";
|
||||
}
|
||||
}
|
||||
|
||||
return OctoPrint.get(getUrl, opts);
|
||||
},
|
||||
|
||||
getToolState: function (data, opts) {
|
||||
data = data || {};
|
||||
|
||||
var history = data.history || undefined;
|
||||
var limit = data.limit || undefined;
|
||||
|
||||
var getUrl = toolUrl;
|
||||
if (history) {
|
||||
getUrl += "?history=true";
|
||||
if (limit) {
|
||||
getUrl += "&limit=" + limit;
|
||||
}
|
||||
}
|
||||
|
||||
return OctoPrint.get(getUrl, opts);
|
||||
},
|
||||
|
||||
getBedState: function (data, opts) {
|
||||
data = data || {};
|
||||
|
||||
var history = data.history || undefined;
|
||||
var limit = data.limit || undefined;
|
||||
|
||||
var getUrl = bedUrl;
|
||||
if (history) {
|
||||
getUrl += "?history=true";
|
||||
if (limit) {
|
||||
getUrl += "&limit=" + limit;
|
||||
}
|
||||
}
|
||||
|
||||
return OctoPrint.get(getUrl, opts);
|
||||
},
|
||||
|
||||
getSdState: function (opts) {
|
||||
return OctoPrint.get(sdUrl, opts);
|
||||
},
|
||||
|
||||
jog: function (data, opts) {
|
||||
data = data || {};
|
||||
|
||||
var payload = {};
|
||||
if (data.x) payload.x = data.x;
|
||||
if (data.y) payload.y = data.y;
|
||||
if (data.z) payload.z = data.z;
|
||||
|
||||
return issuePrintheadCommand("jog", payload, opts);
|
||||
},
|
||||
|
||||
home: function (axes, opts) {
|
||||
axes = axes || [];
|
||||
|
||||
var payload = {
|
||||
axes: axes
|
||||
};
|
||||
|
||||
return issuePrintheadCommand("home", payload, opts);
|
||||
},
|
||||
|
||||
setFeedrate: function (factor, opts) {
|
||||
factor = factor || 100;
|
||||
|
||||
var payload = {
|
||||
factor: factor
|
||||
};
|
||||
|
||||
return issuePrintheadCommand("feedrate", payload, opts);
|
||||
},
|
||||
|
||||
setToolTargetTemperatures: function (targets, opts) {
|
||||
targets = targets || {};
|
||||
|
||||
var payload = {
|
||||
targets: targets
|
||||
};
|
||||
|
||||
return issueToolCommand("target", payload, opts);
|
||||
},
|
||||
|
||||
setToolTemperatureOffsets: function (offsets, opts) {
|
||||
offsets = offsets || {};
|
||||
|
||||
var payload = {
|
||||
offsets: offsets
|
||||
};
|
||||
|
||||
return issueToolCommand("offset", payload, opts);
|
||||
},
|
||||
|
||||
selectTool: function (tool, opts) {
|
||||
tool = tool || undefined;
|
||||
|
||||
var payload = {
|
||||
tool: tool
|
||||
};
|
||||
|
||||
return issueToolCommand("select", payload, opts);
|
||||
},
|
||||
|
||||
extrude: function (amount, opts) {
|
||||
amount = amount || undefined;
|
||||
|
||||
var payload = {
|
||||
amount: amount
|
||||
};
|
||||
|
||||
return issueToolCommand("extrude", payload, opts);
|
||||
},
|
||||
|
||||
setFlowrate: function (factor, opts) {
|
||||
factor = factor || 100;
|
||||
|
||||
var payload = {
|
||||
factor: factor
|
||||
};
|
||||
|
||||
return issueToolCommand("flowrate", payload, opts);
|
||||
},
|
||||
|
||||
setBedTargetTemperature: function (temperature, opts) {
|
||||
temperature = temperature || 0;
|
||||
|
||||
var payload = {
|
||||
target: temperature
|
||||
};
|
||||
|
||||
return issueBedCommand("target", payload, opts);
|
||||
},
|
||||
|
||||
setBedTemperatureOffset: function (offset, opts) {
|
||||
offset = offset || 0;
|
||||
|
||||
var payload = {
|
||||
offset: offset
|
||||
};
|
||||
|
||||
return issueBedCommand("offset", payload, opts);
|
||||
},
|
||||
|
||||
initSd: function (opts) {
|
||||
return issueSdCommand("init", {}, opts);
|
||||
},
|
||||
|
||||
refreshSd: function (opts) {
|
||||
return issueSdCommand("refresh", {}, opts);
|
||||
},
|
||||
|
||||
releaseSd: function (opts) {
|
||||
return issueSdCommand("release", {}, opts);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrint", "jquery"], factory);
|
||||
} else {
|
||||
factory(window.OctoPrint, window.$);
|
||||
}
|
||||
})(window || this, function(OctoPrint, $) {
|
||||
var url = "api/printerprofiles";
|
||||
|
||||
var profileUrl = function(profile) {
|
||||
return url + "/" + profile;
|
||||
};
|
||||
|
||||
OctoPrint.printerprofiles = {
|
||||
get: function (opts) {
|
||||
return OctoPrint.get(url, opts);
|
||||
},
|
||||
|
||||
add: function (profile, additional, opts) {
|
||||
profile = profile || {};
|
||||
additional = additional || {};
|
||||
|
||||
var data = $.extend({}, additional);
|
||||
data.profile = profile;
|
||||
|
||||
return OctoPrint.postJson(url, data, opts);
|
||||
},
|
||||
|
||||
update: function (id, profile, additional, opts) {
|
||||
profile = profile || {};
|
||||
additional = addtional || {};
|
||||
|
||||
var data = $.extend({}, additional);
|
||||
data.profile = profile;
|
||||
|
||||
return OctoPrint.patchJson(profileUrl(id), data, opts);
|
||||
},
|
||||
|
||||
delete: function (id, opts) {
|
||||
return OctoPrint.delete(profileUrl(id), opts);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrint", "jquery"], factory);
|
||||
} else {
|
||||
factory(window.OctoPrint, window.$);
|
||||
}
|
||||
})(window || this, function(OctoPrint, $) {
|
||||
var url = "api/settings";
|
||||
|
||||
var get = function(opts) {
|
||||
return OctoPrint.get(url, opts);
|
||||
};
|
||||
|
||||
var save = function(settings, opts) {
|
||||
settings = settings || {};
|
||||
return OctoPrint.postJson(url, settings, opts);
|
||||
};
|
||||
|
||||
OctoPrint.settings = {
|
||||
get: get,
|
||||
save: save,
|
||||
|
||||
getPluginSettings: function (plugin, opts) {
|
||||
return get(opts)
|
||||
.then(function (settings, statusText, request) {
|
||||
if (!settings.plugins || !settings.plugins[plugin]) {
|
||||
return $.Deferred()
|
||||
.reject(request, "dataerror", "No settings for plugin " + plugin)
|
||||
.promise();
|
||||
} else {
|
||||
return settings.plugins[plugin];
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
savePluginSettings: function (plugin, settings, opts) {
|
||||
var data = {};
|
||||
data["plugins"] = {};
|
||||
data["plugins"][plugin] = settings;
|
||||
return save(data, opts);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrint"], factory);
|
||||
} else {
|
||||
factory(window.OctoPrint);
|
||||
}
|
||||
})(window || this, function(OctoPrint) {
|
||||
var url = "api/slicing";
|
||||
|
||||
var slicerUrl = function(slicer) {
|
||||
return url + "/" + slicer;
|
||||
};
|
||||
|
||||
var profileUrl = function(slicer, profileId) {
|
||||
return slicerUrl(slicer) + "/profiles/" + profileId;
|
||||
};
|
||||
|
||||
OctoPrint.slicing = {
|
||||
listAllSlicersAndProfiles: function(opts) {
|
||||
return OctoPrint.get(url, opts);
|
||||
},
|
||||
|
||||
listProfilesForSlicer: function(slicer, opts) {
|
||||
return OctoPrint.get(slicerUrl(slicer) + "/profiles", opts);
|
||||
},
|
||||
|
||||
getProfileForSlicer: function(slicer, profileId, opts) {
|
||||
return OctoPrint.get(profileUrl(slicer, profileId), opts);
|
||||
},
|
||||
|
||||
addProfileForSlicer: function(slicer, profileId, profile, opts) {
|
||||
profile = profile || {};
|
||||
return OctoPrint.putJson(profileUrl(slicer, profileId), profile, opts);
|
||||
},
|
||||
|
||||
updateProfileForSlicer: function(slicer, profileId, profile, opts) {
|
||||
profile = profile || {};
|
||||
return OctoPrint.patchJson(profileUrl(slicer, profileId), profile, opts);
|
||||
},
|
||||
|
||||
deleteProfileForSlicer: function(slicer, profileId, opts) {
|
||||
return OctoPrint.delete(profileUrl(slicer, profileId), opts);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrint", "jquery", "lodash", "sockjs"], factory);
|
||||
} else {
|
||||
factory(window.OctoPrint, window.$, window._, window.SockJS);
|
||||
}
|
||||
})(window || this, function(OctoPrint, $, _, SockJS) {
|
||||
var exports = {};
|
||||
|
||||
exports.options = {
|
||||
timeouts: [0, 1, 1, 2, 3, 5, 8, 13, 20, 40, 100]
|
||||
};
|
||||
|
||||
var normalClose = 1000;
|
||||
|
||||
var socket = undefined;
|
||||
var reconnecting = false;
|
||||
var reconnectTrial = 0;
|
||||
var registeredHandlers = {};
|
||||
|
||||
var onOpen = function() {
|
||||
reconnecting = false;
|
||||
reconnectTrial = 0;
|
||||
};
|
||||
|
||||
var onClose = function(e) {
|
||||
if (e.code == normalClose) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (exports.onReconnectAttempt(reconnectTrial)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (reconnectTrial < exports.options.timeouts.length) {
|
||||
var timeout = exports.options.timeouts[reconnectTrial];
|
||||
setTimeout(exports.reconnect, timeout * 1000);
|
||||
reconnectTrial++;
|
||||
} else {
|
||||
exports.onReconnectFailed();
|
||||
}
|
||||
};
|
||||
|
||||
var onMessage = function(msg) {
|
||||
_.each(msg.data, function(data, key) {
|
||||
propagateMessage(key, data);
|
||||
});
|
||||
};
|
||||
|
||||
var propagateMessage = function(event, data) {
|
||||
if (!registeredHandlers.hasOwnProperty(event)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var eventObj = {event: event, data: data};
|
||||
|
||||
var catchAllHandlers = registeredHandlers["*"];
|
||||
if (catchAllHandlers && catchAllHandlers.length) {
|
||||
_.each(catchAllHandlers, function(handler) {
|
||||
handler({event: eventObj})
|
||||
});
|
||||
}
|
||||
|
||||
var handlers = registeredHandlers[event];
|
||||
if (handlers && handlers.length) {
|
||||
_.each(handlers, function(handler) {
|
||||
handler(eventObj);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
exports.connect = function(opts) {
|
||||
opts = opts || {};
|
||||
|
||||
exports.disconnect();
|
||||
|
||||
var url = OctoPrint.options.baseurl;
|
||||
if (!_.endsWith(url, "/")) {
|
||||
url += "/";
|
||||
}
|
||||
|
||||
socket = new SockJS(url + "sockjs", undefined, opts);
|
||||
socket.onopen = onOpen;
|
||||
socket.onclose = onClose;
|
||||
socket.onmessage = onMessage;
|
||||
};
|
||||
|
||||
exports.reconnect = function() {
|
||||
exports.disconnect();
|
||||
socket = undefined;
|
||||
exports.connect();
|
||||
};
|
||||
|
||||
exports.disconnect = function() {
|
||||
if (socket != undefined) {
|
||||
socket.close();
|
||||
}
|
||||
};
|
||||
|
||||
exports.onMessage = function(message, handler) {
|
||||
if (!registeredHandlers.hasOwnProperty(message)) {
|
||||
registeredHandlers[message] = [];
|
||||
}
|
||||
registeredHandlers[message].push(handler);
|
||||
return exports;
|
||||
};
|
||||
|
||||
exports.onReconnectAttempt = function(trial) {};
|
||||
exports.onReconnectFailed = function() {};
|
||||
|
||||
OctoPrint.socket = exports;
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrint"], factory);
|
||||
} else {
|
||||
factory(window.OctoPrint);
|
||||
}
|
||||
})(window || this, function(OctoPrint) {
|
||||
var url = "api/system";
|
||||
var commandUrl = "api/system/commands";
|
||||
|
||||
OctoPrint.system = {
|
||||
getCommands: function (opts) {
|
||||
return OctoPrint.get(commandUrl, opts);
|
||||
},
|
||||
|
||||
getCommandsForSource: function (source, opts) {
|
||||
return OctoPrint.get(commandUrl + "/" + source, opts);
|
||||
},
|
||||
|
||||
executeCommand: function (source, action, opts) {
|
||||
return OctoPrint.postJson(commandUrl + "/" + source + "/" + action, {}, opts);
|
||||
}
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrint", "jquery"], factory);
|
||||
} else {
|
||||
factory(window.OctoPrint, window.$);
|
||||
}
|
||||
})(window || this, function(OctoPrint, $) {
|
||||
var url = "api/timelapse";
|
||||
|
||||
var timelapseUrl = function(filename) {
|
||||
return url + "/" + filename;
|
||||
};
|
||||
|
||||
var getTimelapseData = function (opts) {
|
||||
return OctoPrint.get(url, opts);
|
||||
};
|
||||
|
||||
OctoPrint.timelapse = {
|
||||
get: getTimelapseData,
|
||||
|
||||
list: function (opts) {
|
||||
var deferred = $.Deferred();
|
||||
|
||||
getTimelapseData(opts)
|
||||
.done(function (response, status, request) {
|
||||
deferred.resolve(response.files, status, request);
|
||||
})
|
||||
.fail(function () {
|
||||
deferred.reject.apply(null, arguments);
|
||||
});
|
||||
|
||||
return deferred.promise();
|
||||
},
|
||||
|
||||
download: function (filename, opts) {
|
||||
return OctoPrint.download(timelapseUrl(filename), opts);
|
||||
},
|
||||
|
||||
delete: function (filename, opts) {
|
||||
return OctoPrint.delete(timelapseUrl(filename), opts);
|
||||
},
|
||||
|
||||
getConfig: function (opts) {
|
||||
var deferred = $.Deferred();
|
||||
getTimelapseData(opts)
|
||||
.done(function (response, status, request) {
|
||||
deferred.resolve(response.config, status, request);
|
||||
})
|
||||
.fail(function () {
|
||||
deferred.reject.apply(null, arguments);
|
||||
});
|
||||
return deferred.promise();
|
||||
},
|
||||
|
||||
saveConfig: function (config, opts) {
|
||||
config = config || {};
|
||||
return OctoPrint.postJson(url, config, opts);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrint"], factory);
|
||||
} else {
|
||||
factory(window.OctoPrint);
|
||||
}
|
||||
})(window || this, function(OctoPrint) {
|
||||
var baseUrl = "api/users";
|
||||
|
||||
var url = function() {
|
||||
if (arguments.length) {
|
||||
return baseUrl + "/" + Array.prototype.join.call(arguments, "/");
|
||||
} else {
|
||||
return baseUrl;
|
||||
}
|
||||
};
|
||||
|
||||
OctoPrint.users = {
|
||||
list: function (opts) {
|
||||
return OctoPrint.get(url(), opts);
|
||||
},
|
||||
|
||||
add: function (user, opts) {
|
||||
if (!user.name || !user.password) {
|
||||
throw new OctoPrint.InvalidArgumentError("Both user's name and password need to be set");
|
||||
}
|
||||
|
||||
var data = {
|
||||
name: user.name,
|
||||
password: user.password,
|
||||
active: user.hasOwnProperty("active") ? !!user.active : true,
|
||||
admin: user.hasOwnProperty("admin") ? !!user.admin : false
|
||||
};
|
||||
|
||||
return OctoPrint.postJson(url(), data, opts);
|
||||
},
|
||||
|
||||
get: function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrint.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
return OctoPrint.get(url(name), opts);
|
||||
},
|
||||
|
||||
update: function (name, active, admin, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrint.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
var data = {
|
||||
active: !!active,
|
||||
admin: !!admin
|
||||
};
|
||||
return OctoPrint.putJson(url(name), data, opts);
|
||||
},
|
||||
|
||||
delete: function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrint.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
return OctoPrint.delete(url(name), opts);
|
||||
},
|
||||
|
||||
changePassword: function (name, password, opts) {
|
||||
if (!name || !password) {
|
||||
throw new OctoPrint.InvalidArgumentError("user name and password must be set");
|
||||
}
|
||||
|
||||
var data = {
|
||||
password: password
|
||||
};
|
||||
return OctoPrint.putJson(url(name, "password"), data, opts);
|
||||
},
|
||||
|
||||
generateApiKey: function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrint.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
return OctoPrint.postJson(url(name, "apikey"), opts);
|
||||
},
|
||||
|
||||
resetApiKey: function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrint.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
return OctoPrint.delete(url(name, "apikey"), opts);
|
||||
},
|
||||
|
||||
getSettings: function (name, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrint.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
return OctoPrint.get(url(name, "settings"), opts);
|
||||
},
|
||||
|
||||
saveSettings: function (name, settings, opts) {
|
||||
if (!name) {
|
||||
throw new OctoPrint.InvalidArgumentError("user name must be set");
|
||||
}
|
||||
|
||||
settings = settings || {};
|
||||
return OctoPrint.patchJson(url(name, "settings"), settings, opts);
|
||||
}
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrint", "jquery"], factory);
|
||||
} else {
|
||||
factory(window.OctoPrint, window.$);
|
||||
}
|
||||
})(window || this, function(OctoPrint, $) {
|
||||
var url = "api/util";
|
||||
var testUrl = url + "/test";
|
||||
|
||||
var test = function(command, data, opts) {
|
||||
return OctoPrint.issueCommand(testUrl, command, data, opts);
|
||||
};
|
||||
|
||||
OctoPrint.util = {
|
||||
test: test,
|
||||
|
||||
testPath: function(path, additional, opts) {
|
||||
additional = additional || {};
|
||||
|
||||
var data = $.extend({}, additional);
|
||||
data.path = path;
|
||||
|
||||
return test("path", data, opts);
|
||||
},
|
||||
|
||||
testExecutable: function(path, additional, opts) {
|
||||
additional = additional || {};
|
||||
|
||||
var data = $.extend({}, additional);
|
||||
data.path = path;
|
||||
data.check_type = "file";
|
||||
data.check_access = "x";
|
||||
|
||||
return test("path", data, opts);
|
||||
},
|
||||
|
||||
testUrl: function(url, additional, opts) {
|
||||
additional = additional || {};
|
||||
|
||||
var data = $.extend({}, additional);
|
||||
data.url = url;
|
||||
|
||||
return test("url", data, opts);
|
||||
}
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
(function (global, factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["OctoPrint"], factory);
|
||||
} else {
|
||||
factory(window.OctoPrint);
|
||||
}
|
||||
})(window || this, function(OctoPrint) {
|
||||
var url = "api/setup/wizard";
|
||||
|
||||
OctoPrint.wizard = {
|
||||
get: function(opts) {
|
||||
return OctoPrint.get(url, opts);
|
||||
},
|
||||
finish: function(handled, opts) {
|
||||
return OctoPrint.postJson(url, {handled: handled || []}, opts);
|
||||
}
|
||||
};
|
||||
});
|
||||
@@ -3,94 +3,52 @@ function DataUpdater(allViewModels) {
|
||||
|
||||
self.allViewModels = allViewModels;
|
||||
|
||||
self._socket = undefined;
|
||||
self._autoReconnecting = false;
|
||||
self._autoReconnectTrial = 0;
|
||||
self._autoReconnectTimeouts = [0, 1, 1, 2, 3, 5, 8, 13, 20, 40, 100];
|
||||
self._autoReconnectDialogIndex = 1;
|
||||
|
||||
self._pluginHash = undefined;
|
||||
self._configHash = undefined;
|
||||
|
||||
self.reloadOverlay = $("#reloadui_overlay");
|
||||
$("#reloadui_overlay_reload").click(function() { location.reload(true); });
|
||||
|
||||
self.connect = function() {
|
||||
var options = {};
|
||||
if (SOCKJS_DEBUG) {
|
||||
options["debug"] = true;
|
||||
}
|
||||
|
||||
self._socket = new SockJS(SOCKJS_URI, undefined, options);
|
||||
self._socket.onopen = self._onconnect;
|
||||
self._socket.onclose = self._onclose;
|
||||
self._socket.onmessage = self._onmessage;
|
||||
OctoPrint.socket.connect({debug: !!SOCKJS_DEBUG});
|
||||
};
|
||||
|
||||
self.reconnect = function() {
|
||||
self._socket.close();
|
||||
delete self._socket;
|
||||
self.connect();
|
||||
OctoPrint.socket.reconnect();
|
||||
};
|
||||
|
||||
self._onconnect = function() {
|
||||
self._autoReconnecting = false;
|
||||
self._autoReconnectTrial = 0;
|
||||
};
|
||||
|
||||
self._onclose = function(e) {
|
||||
if (e.code == SOCKJS_CLOSE_NORMAL) {
|
||||
self._onReconnectAttempt = function(trial) {
|
||||
if (trial <= 0) {
|
||||
// Only consider it a real disconnect if the trial number has exceeded our threshold.
|
||||
return;
|
||||
}
|
||||
if (self._autoReconnectTrial >= self._autoReconnectDialogIndex) {
|
||||
// Only consider it a real disconnect if the trial number has exceeded our threshold.
|
||||
|
||||
var handled = false;
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (handled == true) {
|
||||
return;
|
||||
}
|
||||
var handled = false;
|
||||
callViewModelsIf(
|
||||
self.allViewModels,
|
||||
"onServerDisconnect",
|
||||
function() { return !handled; },
|
||||
function(method) { handled = !method() || handled; }
|
||||
);
|
||||
|
||||
if (viewModel.hasOwnProperty("onServerDisconnect")) {
|
||||
if (!viewModel.onServerDisconnect()) {
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (handled) {
|
||||
return;
|
||||
}
|
||||
|
||||
showOfflineOverlay(
|
||||
gettext("Server is offline"),
|
||||
gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below."),
|
||||
self.reconnect
|
||||
);
|
||||
if (handled) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (self._autoReconnectTrial < self._autoReconnectTimeouts.length) {
|
||||
var timeout = self._autoReconnectTimeouts[self._autoReconnectTrial];
|
||||
log.info("Reconnect trial #" + self._autoReconnectTrial + ", waiting " + timeout + "s");
|
||||
setTimeout(self.reconnect, timeout * 1000);
|
||||
self._autoReconnectTrial++;
|
||||
} else {
|
||||
self._onreconnectfailed();
|
||||
}
|
||||
showOfflineOverlay(
|
||||
gettext("Server is offline"),
|
||||
gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below."),
|
||||
self.reconnect
|
||||
);
|
||||
};
|
||||
|
||||
self._onreconnectfailed = function() {
|
||||
self._onReconnectFailed = function() {
|
||||
var handled = false;
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (handled == true) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (viewModel.hasOwnProperty("onServerDisconnect")) {
|
||||
if (!viewModel.onServerDisconnect()) {
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
callViewModelsIf(
|
||||
self.allViewModels,
|
||||
"onServerDisconnect",
|
||||
function() { return !handled; },
|
||||
function(method) { handled = !method() || handled; }
|
||||
);
|
||||
|
||||
if (handled) {
|
||||
return;
|
||||
@@ -100,172 +58,189 @@ function DataUpdater(allViewModels) {
|
||||
$("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I <strong>could not reconnect automatically</strong>, but you may try a manual reconnect using the button below."));
|
||||
};
|
||||
|
||||
self._onmessage = function(e) {
|
||||
for (var prop in e.data) {
|
||||
if (!e.data.hasOwnProperty(prop)) {
|
||||
continue;
|
||||
self._onConnected = function(event) {
|
||||
var data = event.data;
|
||||
|
||||
// update version information
|
||||
var oldVersion = VERSION;
|
||||
VERSION = data["version"];
|
||||
DISPLAY_VERSION = data["display_version"];
|
||||
BRANCH = data["branch"];
|
||||
$("span.version").text(DISPLAY_VERSION);
|
||||
|
||||
// update plugin hash
|
||||
var oldPluginHash = self._pluginHash;
|
||||
self._pluginHash = data["plugin_hash"];
|
||||
|
||||
// update config hash
|
||||
var oldConfigHash = self._configHash;
|
||||
self._configHash = data["config_hash"];
|
||||
|
||||
// if the offline overlay is still showing, now's a good time to
|
||||
// hide it, plus reload the camera feed if it's currently displayed
|
||||
if ($("#offline_overlay").is(":visible")) {
|
||||
hideOfflineOverlay();
|
||||
callViewModels(self.allViewModels, "onDataUpdaterReconnect");
|
||||
|
||||
if ($('#tabs li[class="active"] a').attr("href") == "#control") {
|
||||
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
|
||||
}
|
||||
}
|
||||
|
||||
var data = e.data[prop];
|
||||
|
||||
var gcodeUploadProgress = $("#gcode_upload_progress");
|
||||
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
|
||||
|
||||
switch (prop) {
|
||||
case "connected": {
|
||||
// update the current UI API key and send it with any request
|
||||
UI_API_KEY = data["apikey"];
|
||||
$.ajaxSetup({
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
|
||||
var oldVersion = VERSION;
|
||||
VERSION = data["version"];
|
||||
DISPLAY_VERSION = data["display_version"];
|
||||
$("span.version").text(DISPLAY_VERSION);
|
||||
|
||||
var oldPluginHash = self._pluginHash;
|
||||
self._pluginHash = data["plugin_hash"];
|
||||
|
||||
if ($("#offline_overlay").is(":visible")) {
|
||||
hideOfflineOverlay();
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onDataUpdaterReconnect")) {
|
||||
viewModel.onDataUpdaterReconnect();
|
||||
}
|
||||
});
|
||||
|
||||
if ($('#tabs li[class="active"] a').attr("href") == "#control") {
|
||||
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
|
||||
}
|
||||
}
|
||||
|
||||
if (oldVersion != VERSION || (oldPluginHash != undefined && oldPluginHash != self._pluginHash)) {
|
||||
self.reloadOverlay.show();
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case "history": {
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("fromHistoryData")) {
|
||||
viewModel.fromHistoryData(data);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "current": {
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("fromCurrentData")) {
|
||||
viewModel.fromCurrentData(data);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "slicingProgress": {
|
||||
gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(data["progress"])}));
|
||||
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onSlicingProgress")) {
|
||||
viewModel.onSlicingProgress(data["slicer"], data["model_path"], data["machinecode_path"], data["progress"]);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "event": {
|
||||
var type = data["type"];
|
||||
var payload = data["payload"];
|
||||
var html = "";
|
||||
|
||||
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
|
||||
|
||||
if (type == "MovieRendering") {
|
||||
new PNotify({title: gettext("Rendering timelapse"), text: _.sprintf(gettext("Now rendering timelapse %(movie_basename)s"), payload)});
|
||||
} else if (type == "MovieDone") {
|
||||
new PNotify({title: gettext("Timelapse ready"), text: _.sprintf(gettext("New timelapse %(movie_basename)s is done rendering."), payload)});
|
||||
} else if (type == "MovieFailed") {
|
||||
html = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"), payload) + "</p>";
|
||||
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + payload.error + '</pre>');
|
||||
new PNotify({title: gettext("Rendering failed"), text: html, type: "error", hide: false});
|
||||
} else if (type == "SlicingStarted") {
|
||||
gcodeUploadProgress.addClass("progress-striped").addClass("active");
|
||||
gcodeUploadProgressBar.css("width", "100%");
|
||||
if (payload.progressAvailable) {
|
||||
gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: 0}));
|
||||
} else {
|
||||
gcodeUploadProgressBar.text(gettext("Slicing ..."));
|
||||
}
|
||||
} else if (type == "SlicingDone") {
|
||||
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
|
||||
gcodeUploadProgressBar.css("width", "0%");
|
||||
gcodeUploadProgressBar.text("");
|
||||
new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload), type: "success"});
|
||||
} else if (type == "SlicingCancelled") {
|
||||
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
|
||||
gcodeUploadProgressBar.css("width", "0%");
|
||||
gcodeUploadProgressBar.text("");
|
||||
} else if (type == "SlicingFailed") {
|
||||
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
|
||||
gcodeUploadProgressBar.css("width", "0%");
|
||||
gcodeUploadProgressBar.text("");
|
||||
|
||||
html = _.sprintf(gettext("Could not slice %(stl)s to %(gcode)s: %(reason)s"), payload);
|
||||
new PNotify({title: gettext("Slicing failed"), text: html, type: "error", hide: false});
|
||||
} else if (type == "TransferStarted") {
|
||||
gcodeUploadProgress.addClass("progress-striped").addClass("active");
|
||||
gcodeUploadProgressBar.css("width", "100%");
|
||||
gcodeUploadProgressBar.text(gettext("Streaming ..."));
|
||||
} else if (type == "TransferDone") {
|
||||
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
|
||||
gcodeUploadProgressBar.css("width", "0%");
|
||||
gcodeUploadProgressBar.text("");
|
||||
new PNotify({
|
||||
title: gettext("Streaming done"),
|
||||
text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload),
|
||||
type: "success"
|
||||
});
|
||||
gcodeFilesViewModel.requestData(payload.remote, "sdcard");
|
||||
}
|
||||
|
||||
var legacyEventHandlers = {
|
||||
"UpdatedFiles": "onUpdatedFiles",
|
||||
"MetadataStatisticsUpdated": "onMetadataStatisticsUpdated",
|
||||
"MetadataAnalysisFinished": "onMetadataAnalysisFinished",
|
||||
"SlicingDone": "onSlicingDone",
|
||||
"SlicingCancelled": "onSlicingCancelled",
|
||||
"SlicingFailed": "onSlicingFailed"
|
||||
};
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onEvent" + type)) {
|
||||
viewModel["onEvent" + type](payload);
|
||||
} else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) {
|
||||
// there might still be code that uses the old callbacks, make sure those still get called
|
||||
// but log a warning
|
||||
log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]);
|
||||
viewModel[legacyEventHandlers[type]](payload);
|
||||
}
|
||||
});
|
||||
|
||||
break;
|
||||
}
|
||||
case "timelapse": {
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("fromTimelapseData")) {
|
||||
viewModel.fromTimelapseData(data);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "plugin": {
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onDataUpdaterPluginMessage")) {
|
||||
viewModel.onDataUpdaterPluginMessage(data.plugin, data.data);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
// if the version, the plugin hash or the config hash changed, we
|
||||
// want the user to reload the UI since it might be stale now
|
||||
var versionChanged = oldVersion != VERSION;
|
||||
var pluginsChanged = oldPluginHash != undefined && oldPluginHash != self._pluginHash;
|
||||
var configChanged = oldConfigHash != undefined && oldConfigHash != self._configHash;
|
||||
if (versionChanged || pluginsChanged || configChanged) {
|
||||
self.reloadOverlay.show();
|
||||
}
|
||||
};
|
||||
|
||||
self._onHistoryData = function(event) {
|
||||
callViewModels(self.allViewModels, "fromHistoryData", [event.data]);
|
||||
};
|
||||
|
||||
self._onCurrentData = function(event) {
|
||||
callViewModels(self.allViewModels, "fromCurrentData", [event.data]);
|
||||
};
|
||||
|
||||
self._onSlicingProgress = function(event) {
|
||||
$("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])}));
|
||||
|
||||
callViewModels(self.allViewModels, "onSlicingProgress", [
|
||||
data["slicer"],
|
||||
data["model_path"],
|
||||
data["machinecode_path"],
|
||||
data["progress"]
|
||||
]);
|
||||
};
|
||||
|
||||
self._onEvent = function(event) {
|
||||
var gcodeUploadProgress = $("#gcode_upload_progress");
|
||||
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
|
||||
|
||||
var type = event.data["type"];
|
||||
var payload = event.data["payload"];
|
||||
var html = "";
|
||||
var format = {};
|
||||
|
||||
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
|
||||
|
||||
if (type == "SettingsUpdated") {
|
||||
if (payload && payload.hasOwnProperty("config_hash")) {
|
||||
self._configHash = payload.config_hash;
|
||||
}
|
||||
} else if (type == "MovieRendering") {
|
||||
new PNotify({title: gettext("Rendering timelapse"), text: _.sprintf(gettext("Now rendering timelapse %(movie_basename)s"), payload)});
|
||||
} else if (type == "MovieDone") {
|
||||
new PNotify({title: gettext("Timelapse ready"), text: _.sprintf(gettext("New timelapse %(movie_basename)s is done rendering."), payload)});
|
||||
} else if (type == "MovieFailed") {
|
||||
html = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"), payload) + "</p>";
|
||||
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + payload.error + '</pre>');
|
||||
new PNotify({
|
||||
title: gettext("Rendering failed"),
|
||||
text: html,
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
} else if (type == "PostRollStart") {
|
||||
var title = gettext("Capturing timelapse postroll");
|
||||
|
||||
var text;
|
||||
if (!payload.postroll_duration) {
|
||||
text = _.sprintf(gettext("Now capturing timelapse post roll, this will take only a moment..."), format);
|
||||
} else {
|
||||
if (payload.postroll_duration > 60) {
|
||||
format = {duration: _.sprintf(gettext("%(minutes)d min"), {minutes: payload.postroll_duration / 60})};
|
||||
} else {
|
||||
format = {duration: _.sprintf(gettext("%(seconds)d sec"), {seconds: payload.postroll_duration})};
|
||||
}
|
||||
text = _.sprintf(gettext("Now capturing timelapse post roll, this will take approximately %(duration)s..."), format);
|
||||
}
|
||||
|
||||
new PNotify({
|
||||
title: title,
|
||||
text: text
|
||||
});
|
||||
} else if (type == "SlicingStarted") {
|
||||
gcodeUploadProgress.addClass("progress-striped").addClass("active");
|
||||
gcodeUploadProgressBar.css("width", "100%");
|
||||
if (payload.progressAvailable) {
|
||||
gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: 0}));
|
||||
} else {
|
||||
gcodeUploadProgressBar.text(gettext("Slicing ..."));
|
||||
}
|
||||
} else if (type == "SlicingDone") {
|
||||
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
|
||||
gcodeUploadProgressBar.css("width", "0%");
|
||||
gcodeUploadProgressBar.text("");
|
||||
new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload), type: "success"});
|
||||
} else if (type == "SlicingCancelled") {
|
||||
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
|
||||
gcodeUploadProgressBar.css("width", "0%");
|
||||
gcodeUploadProgressBar.text("");
|
||||
} else if (type == "SlicingFailed") {
|
||||
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
|
||||
gcodeUploadProgressBar.css("width", "0%");
|
||||
gcodeUploadProgressBar.text("");
|
||||
|
||||
html = _.sprintf(gettext("Could not slice %(stl)s to %(gcode)s: %(reason)s"), payload);
|
||||
new PNotify({title: gettext("Slicing failed"), text: html, type: "error", hide: false});
|
||||
} else if (type == "TransferStarted") {
|
||||
gcodeUploadProgress.addClass("progress-striped").addClass("active");
|
||||
gcodeUploadProgressBar.css("width", "100%");
|
||||
gcodeUploadProgressBar.text(gettext("Streaming ..."));
|
||||
} else if (type == "TransferDone") {
|
||||
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
|
||||
gcodeUploadProgressBar.css("width", "0%");
|
||||
gcodeUploadProgressBar.text("");
|
||||
new PNotify({
|
||||
title: gettext("Streaming done"),
|
||||
text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload),
|
||||
type: "success"
|
||||
});
|
||||
gcodeFilesViewModel.requestData(payload.remote, "sdcard");
|
||||
}
|
||||
|
||||
var legacyEventHandlers = {
|
||||
"UpdatedFiles": "onUpdatedFiles",
|
||||
"MetadataStatisticsUpdated": "onMetadataStatisticsUpdated",
|
||||
"MetadataAnalysisFinished": "onMetadataAnalysisFinished",
|
||||
"SlicingDone": "onSlicingDone",
|
||||
"SlicingCancelled": "onSlicingCancelled",
|
||||
"SlicingFailed": "onSlicingFailed"
|
||||
};
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onEvent" + type)) {
|
||||
viewModel["onEvent" + type](payload);
|
||||
} else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) {
|
||||
// there might still be code that uses the old callbacks, make sure those still get called
|
||||
// but log a warning
|
||||
log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]);
|
||||
viewModel[legacyEventHandlers[type]](payload);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self._onTimelapse = function(event) {
|
||||
callViewModels(self.allViewModels, "fromTimelapseData", [event.data]);
|
||||
};
|
||||
|
||||
self._onPluginMessage = function(event) {
|
||||
callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]);
|
||||
};
|
||||
|
||||
OctoPrint.socket.onReconnectAttempt = self._onReconnectAttempt;
|
||||
OctoPrint.socket.onReconnectFailed = self._onReconnectFailed;
|
||||
OctoPrint.socket
|
||||
.onMessage("connected", self._onConnected)
|
||||
.onMessage("history", self._onHistoryData)
|
||||
.onMessage("current", self._onCurrentData)
|
||||
.onMessage("slicingProgress", self._onSlicingProgress)
|
||||
.onMessage("event", self._onEvent)
|
||||
.onMessage("timelapse", self._onTimelapse)
|
||||
.onMessage("plugin", self._onPluginMessage);
|
||||
|
||||
self.connect();
|
||||
}
|
||||
@@ -333,6 +333,34 @@ function formatSize(bytes) {
|
||||
return _.sprintf("%.1f%s", bytes, "TB");
|
||||
}
|
||||
|
||||
function bytesFromSize(size) {
|
||||
if (size == undefined || size.trim() == "") return undefined;
|
||||
|
||||
var parsed = size.match(/^([+]?[0-9]*\.?[0-9]+)(?:\s*)?(.*)$/);
|
||||
var number = parsed[1];
|
||||
var unit = parsed[2].trim();
|
||||
|
||||
if (unit == "") return parseFloat(number);
|
||||
|
||||
var units = {
|
||||
b: 1,
|
||||
byte: 1,
|
||||
bytes: 1,
|
||||
kb: 1024,
|
||||
mb: Math.pow(1024, 2),
|
||||
gb: Math.pow(1024, 3),
|
||||
tb: Math.pow(1024, 4)
|
||||
};
|
||||
unit = unit.toLowerCase();
|
||||
|
||||
if (!units.hasOwnProperty(unit)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
var factor = units[unit];
|
||||
return number * factor;
|
||||
}
|
||||
|
||||
function formatDuration(seconds) {
|
||||
if (!seconds) return "-";
|
||||
if (seconds < 0) return "00:00:00";
|
||||
@@ -434,18 +462,95 @@ function hideOfflineOverlay() {
|
||||
$("#offline_overlay").hide();
|
||||
}
|
||||
|
||||
function showConfirmationDialog(message, onacknowledge) {
|
||||
var confirmationDialog = $("#confirmation_dialog");
|
||||
var confirmationDialogAck = $(".confirmation_dialog_acknowledge", confirmationDialog);
|
||||
function showMessageDialog(msg, options) {
|
||||
options = options || {};
|
||||
if (_.isPlainObject(msg)) {
|
||||
options = msg;
|
||||
} else {
|
||||
options.message = msg;
|
||||
}
|
||||
|
||||
$(".confirmation_dialog_message", confirmationDialog).text(message);
|
||||
confirmationDialogAck.unbind("click");
|
||||
confirmationDialogAck.bind("click", function (e) {
|
||||
e.preventDefault();
|
||||
$("#confirmation_dialog").modal("hide");
|
||||
onacknowledge(e);
|
||||
var title = options.title || "";
|
||||
var message = options.message || "";
|
||||
var close = options.close || gettext("Close");
|
||||
var onclose = options.onclose || undefined;
|
||||
var onshow = options.onshow || undefined;
|
||||
var onshown = options.onshown || undefined;
|
||||
|
||||
if (_.isString(message)) {
|
||||
message = $("<p>" + message + "</p>");
|
||||
}
|
||||
|
||||
var modalHeader = $('<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">×</a><h3>' + title + '</h3>');
|
||||
var modalBody = $(message);
|
||||
var modalFooter = $('<a href="javascript:void(0)" class="btn" data-dismiss="modal" aria-hidden="true">' + close + '</a>');
|
||||
|
||||
var modal = $('<div></div>')
|
||||
.addClass('modal hide fade')
|
||||
.append($('<div></div>').addClass('modal-header').append(modalHeader))
|
||||
.append($('<div></div>').addClass('modal-body').append(modalBody))
|
||||
.append($('<div></div>').addClass('modal-footer').append(modalFooter));
|
||||
|
||||
modal.on("hidden", function() {
|
||||
if (onclose && _.isFunction(onclose)) {
|
||||
onclose();
|
||||
}
|
||||
});
|
||||
confirmationDialog.modal("show");
|
||||
|
||||
if (onshow) {
|
||||
modal.on("show", onshow);
|
||||
}
|
||||
|
||||
if (onshown) {
|
||||
modal.on("shown", onshown);
|
||||
}
|
||||
|
||||
modal.modal("show");
|
||||
return modal;
|
||||
}
|
||||
|
||||
function showConfirmationDialog(msg, onacknowledge, options) {
|
||||
options = options || {};
|
||||
if (_.isPlainObject(msg)) {
|
||||
options = msg;
|
||||
} else {
|
||||
options.message = msg;
|
||||
options.onproceed = onacknowledge;
|
||||
}
|
||||
|
||||
var title = options.title || gettext("Are you sure?");
|
||||
var message = options.message || "";
|
||||
var question = options.question || gettext("Are you sure you want to proceed?");
|
||||
var cancel = options.cancel || gettext("Cancel");
|
||||
var proceed = options.proceed || gettext("Proceed");
|
||||
var proceedClass = options.proceedClass || "danger";
|
||||
var onproceed = options.onproceed || undefined;
|
||||
|
||||
var modalHeader = $('<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">×</a><h3>' + title + '</h3>');
|
||||
var modalBody = $('<p>' + message + '</p><p>' + question + '</p>');
|
||||
|
||||
var cancelButton = $('<a href="javascript:void(0)" class="btn">' + cancel + '</a>')
|
||||
.attr("data-dismiss", "modal")
|
||||
.attr("aria-hidden", "true");
|
||||
var proceedButton = $('<a href="javascript:void(0)" class="btn">' + proceed + '</a>')
|
||||
.addClass("btn-" + proceedClass);
|
||||
|
||||
var modal = $('<div></div>')
|
||||
.addClass('modal hide fade')
|
||||
.append($('<div></div>').addClass('modal-header').append(modalHeader))
|
||||
.append($('<div></div>').addClass('modal-body').append(modalBody))
|
||||
.append($('<div></div>').addClass('modal-footer').append(cancelButton).append(proceedButton));
|
||||
modal.modal("show");
|
||||
|
||||
proceedButton.click(function(e) {
|
||||
e.preventDefault();
|
||||
modal.modal("hide");
|
||||
if (onproceed && _.isFunction(onproceed)) {
|
||||
onproceed(e);
|
||||
}
|
||||
});
|
||||
|
||||
return modal;
|
||||
}
|
||||
|
||||
function commentableLinesToArray(lines) {
|
||||
@@ -461,3 +566,177 @@ function splitTextToArray(text, sep, stripEmpty, filter) {
|
||||
function(item) { return (stripEmpty ? item : true) && (filter ? filter(item) : true); }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if comparing data and oldData yields changes, false otherwise.
|
||||
*
|
||||
* E.g.
|
||||
*
|
||||
* hasDataChanged(
|
||||
* {foo: "bar", fnord: {one: "1", two: "2", three: "three", key: "value"}},
|
||||
* {foo: "bar", fnord: {one: "1", two: "2", three: "3", four: "4"}}
|
||||
* )
|
||||
*
|
||||
* will return
|
||||
*
|
||||
* true
|
||||
*
|
||||
* and
|
||||
*
|
||||
* hasDataChanged(
|
||||
* {foo: "bar", fnord: {one: "1", two: "2", three: "3"}},
|
||||
* {foo: "bar", fnord: {one: "1", two: "2", three: "3"}}
|
||||
* )
|
||||
*
|
||||
* will return
|
||||
*
|
||||
* false
|
||||
*
|
||||
* Note that this will assume data and oldData to be structurally identical (same keys)
|
||||
* and is optimized to check for value changes, not key updates.
|
||||
*/
|
||||
function hasDataChanged(data, oldData) {
|
||||
if (data == undefined) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (oldData == undefined) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (_.isPlainObject(data)) {
|
||||
return _.any(_.keys(data), function(key) {return hasDataChanged(data[key], oldData[key]);});
|
||||
} else {
|
||||
return !_.isEqual(data, oldData);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare provided data and oldData plain objects and only return those
|
||||
* substructures of data that actually changed.
|
||||
*
|
||||
* E.g.
|
||||
*
|
||||
* getOnlyChangedData(
|
||||
* {foo: "bar", fnord: {one: "1", two: "2", three: "three"}},
|
||||
* {foo: "bar", fnord: {one: "1", two: "2", three: "3"}}
|
||||
* )
|
||||
*
|
||||
* will return
|
||||
*
|
||||
* {fnord: {three: "three"}}
|
||||
*
|
||||
* and
|
||||
*
|
||||
* getOnlyChangedData(
|
||||
* {foo: "bar", fnord: {one: "1", two: "2", three: "3"}},
|
||||
* {foo: "bar", fnord: {one: "1", two: "2", three: "3"}}
|
||||
* )
|
||||
*
|
||||
* will return
|
||||
*
|
||||
* {}
|
||||
*
|
||||
* Note that this will assume data and oldData to be structurally identical (same keys)
|
||||
* and is optimized to check for value changes, not key updates.
|
||||
*/
|
||||
function getOnlyChangedData(data, oldData) {
|
||||
if (data == undefined) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (oldData == undefined) {
|
||||
return data;
|
||||
}
|
||||
|
||||
var f = function(root, oldRoot) {
|
||||
if (!_.isPlainObject(root)) {
|
||||
return root;
|
||||
}
|
||||
|
||||
var retval = {};
|
||||
_.forOwn(root, function(value, key) {
|
||||
var oldValue = oldRoot[key];
|
||||
if (_.isPlainObject(value)) {
|
||||
if (hasDataChanged(value, oldValue)) {
|
||||
retval[key] = f(value, oldValue);
|
||||
}
|
||||
} else {
|
||||
if (!_.isEqual(value, oldValue)) {
|
||||
retval[key] = value;
|
||||
}
|
||||
}
|
||||
});
|
||||
return retval;
|
||||
};
|
||||
|
||||
return f(data, oldData);
|
||||
}
|
||||
|
||||
function callViewModels(allViewModels, method, callback) {
|
||||
callViewModelsIf(allViewModels, method, undefined, callback);
|
||||
}
|
||||
|
||||
function callViewModelsIf(allViewModels, method, condition, callback) {
|
||||
if (condition == undefined || !_.isFunction(condition)) {
|
||||
condition = function() { return true; };
|
||||
}
|
||||
|
||||
var parameters = undefined;
|
||||
if (!_.isFunction(callback)) {
|
||||
// if callback is not a function that means we are supposed to directly
|
||||
// call the view model method instead of providing it to the callback
|
||||
// - let's figure out how
|
||||
|
||||
if (callback == undefined) {
|
||||
// directly call view model method with no parameters
|
||||
parameters = undefined;
|
||||
log.trace("Calling method", method, "on view models");
|
||||
} else if (_.isArray(callback)) {
|
||||
// directly call view model method with these parameters
|
||||
parameters = callback;
|
||||
log.trace("Calling method", method, "on view models with specified parameters", parameters);
|
||||
} else {
|
||||
// ok, this doesn't make sense, callback is neither undefined nor
|
||||
// an array, we'll return without doing anything
|
||||
return;
|
||||
}
|
||||
|
||||
// we reset this here so we now further down that we want to call
|
||||
// the method directly
|
||||
callback = undefined;
|
||||
} else {
|
||||
log.trace("Providing method", method, "on view models to specified callback", callback);
|
||||
}
|
||||
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty(method) && condition(viewModel, method)) {
|
||||
if (callback == undefined) {
|
||||
if (parameters != undefined) {
|
||||
// call the method with the provided parameters
|
||||
viewModel[method].apply(viewModel, parameters);
|
||||
} else {
|
||||
// call the method without parameters
|
||||
viewModel[method]();
|
||||
}
|
||||
} else {
|
||||
// provide the method to the callback
|
||||
callback(viewModel[method]);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var sizeObservable = function(observable) {
|
||||
return ko.computed({
|
||||
read: function() {
|
||||
return formatSize(observable());
|
||||
},
|
||||
write: function(value) {
|
||||
var result = bytesFromSize(value);
|
||||
if (result != undefined) {
|
||||
observable(result);
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
@@ -1,4 +1,6 @@
|
||||
$(function() {
|
||||
OctoPrint = window.OctoPrint;
|
||||
|
||||
//~~ Lodash setup
|
||||
|
||||
_.mixin({"sprintf": sprintf, "vsprintf": vsprintf});
|
||||
@@ -7,6 +9,23 @@ $(function() {
|
||||
|
||||
log.setLevel(CONFIG_DEBUG ? "debug" : "info");
|
||||
|
||||
//~~ OctoPrint client setup
|
||||
OctoPrint.options.baseurl = BASEURL;
|
||||
OctoPrint.options.apikey = UI_API_KEY;
|
||||
|
||||
OctoPrint.socket.onMessage("connected", function(data) {
|
||||
var payload = data.data;
|
||||
OctoPrint.options.apikey = payload.apikey;
|
||||
|
||||
// update the API key directly in jquery's ajax options too,
|
||||
// to ensure the fileupload plugin and any plugins still using
|
||||
// $.ajax directly still work fine too
|
||||
UI_API_KEY = payload["apikey"];
|
||||
$.ajaxSetup({
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
});
|
||||
|
||||
//~~ AJAX setup
|
||||
|
||||
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
|
||||
@@ -21,6 +40,15 @@ $(function() {
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
|
||||
//~~ Initialize file upload plugin
|
||||
|
||||
$.widget("blueimp.fileupload", $.blueimp.fileupload, {
|
||||
options: {
|
||||
dropZone: null,
|
||||
pasteZone: null
|
||||
}
|
||||
});
|
||||
|
||||
//~~ Initialize i18n
|
||||
|
||||
var catalog = window["BABEL_TO_LOAD_" + LOCALE];
|
||||
@@ -51,6 +79,27 @@ $(function() {
|
||||
//~~ Initialize PNotify
|
||||
|
||||
PNotify.prototype.options.styling = "bootstrap2";
|
||||
PNotify.prototype.options.mouse_reset = false;
|
||||
|
||||
PNotify.singleButtonNotify = function(options) {
|
||||
if (!options.confirm || !options.confirm.buttons || !options.confirm.buttons.length) {
|
||||
return new PNotify(options);
|
||||
}
|
||||
|
||||
var autoDisplay = options.auto_display != false;
|
||||
|
||||
var params = $.extend(true, {}, options);
|
||||
params.auto_display = false;
|
||||
|
||||
var notify = new PNotify(params);
|
||||
notify.options.confirm.buttons = [notify.options.confirm.buttons[0]];
|
||||
notify.modules.confirm.makeDialog(notify, notify.options.confirm);
|
||||
|
||||
if (autoDisplay) {
|
||||
notify.open();
|
||||
}
|
||||
return notify;
|
||||
};
|
||||
|
||||
//~~ Initialize view models
|
||||
|
||||
@@ -58,7 +107,7 @@ $(function() {
|
||||
var viewModelMap = {};
|
||||
|
||||
// Fix Function#name on browsers that do not support it (IE):
|
||||
// see: http://stackoverflow.com/questions/6903762/function-name-not-supported-in-ie
|
||||
// see: http://stackoverflow.com/questions/6903762/function-name-not-supported-in-ie
|
||||
if (!(function f() {}).name) {
|
||||
Object.defineProperty(Function.prototype, 'name', {
|
||||
get: function() {
|
||||
@@ -320,7 +369,7 @@ $(function() {
|
||||
.data("contextParent", $(this))
|
||||
.show()
|
||||
.css({
|
||||
position: "absolute",
|
||||
position: "fixed",
|
||||
left: getMenuPosition(e.clientX, 'width', 'scrollLeft'),
|
||||
top: getMenuPosition(e.clientY, 'height', 'scrollTop'),
|
||||
"z-index": 9999
|
||||
@@ -365,23 +414,13 @@ $(function() {
|
||||
tabs.on('show', function (e) {
|
||||
var current = e.target.hash;
|
||||
var previous = e.relatedTarget.hash;
|
||||
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onTabChange")) {
|
||||
viewModel.onTabChange(current, previous);
|
||||
}
|
||||
});
|
||||
callViewModels(allViewModels, "onTabChange", [current, previous]);
|
||||
});
|
||||
|
||||
tabs.on('shown', function (e) {
|
||||
var current = e.target.hash;
|
||||
var previous = e.relatedTarget.hash;
|
||||
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onAfterTabChange")) {
|
||||
viewModel.onAfterTabChange(current, previous);
|
||||
}
|
||||
});
|
||||
callViewModels(allViewModels, "onAfterTabChange", [current, previous]);
|
||||
});
|
||||
|
||||
// Fix input element click problems on dropdowns
|
||||
@@ -396,11 +435,7 @@ $(function() {
|
||||
|
||||
//~~ Starting up the app
|
||||
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onStartup")) {
|
||||
viewModel.onStartup();
|
||||
}
|
||||
});
|
||||
callViewModels(allViewModels, "onStartup");
|
||||
|
||||
//~~ view model binding
|
||||
|
||||
@@ -431,6 +466,8 @@ $(function() {
|
||||
targets = [targets];
|
||||
}
|
||||
|
||||
viewModel._bindings = [];
|
||||
|
||||
_.each(targets, function(target) {
|
||||
if (target == undefined) {
|
||||
return;
|
||||
@@ -456,6 +493,12 @@ $(function() {
|
||||
|
||||
try {
|
||||
ko.applyBindings(viewModel, element);
|
||||
viewModel._bindings.push(target);
|
||||
|
||||
if (viewModel.hasOwnProperty("onBoundTo")) {
|
||||
viewModel.onBoundTo(target, element);
|
||||
}
|
||||
|
||||
log.debug("View model", viewModel.constructor.name, "bound to", target);
|
||||
} catch (exc) {
|
||||
log.error("Could not bind view model", viewModel.constructor.name, "to target", target, ":", (exc.stack || exc));
|
||||
@@ -463,29 +506,24 @@ $(function() {
|
||||
});
|
||||
}
|
||||
|
||||
viewModel._unbound = viewModel._bindings != undefined && viewModel._bindings.length == 0;
|
||||
|
||||
if (viewModel.hasOwnProperty("onAfterBinding")) {
|
||||
viewModel.onAfterBinding();
|
||||
}
|
||||
});
|
||||
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onAllBound")) {
|
||||
viewModel.onAllBound(allViewModels);
|
||||
}
|
||||
});
|
||||
callViewModels(allViewModels, "onAllBound", [allViewModels]);
|
||||
log.info("... binding done");
|
||||
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onStartupComplete")) {
|
||||
viewModel.onStartupComplete();
|
||||
}
|
||||
});
|
||||
callViewModels(allViewModels, "onStartupComplete");
|
||||
};
|
||||
|
||||
if (!_.has(viewModelMap, "settingsViewModel")) {
|
||||
throw new Error("settingsViewModel is missing, can't run UI")
|
||||
}
|
||||
viewModelMap["settingsViewModel"].requestData(bindViewModels);
|
||||
viewModelMap["settingsViewModel"].requestData()
|
||||
.done(bindViewModels);
|
||||
}
|
||||
);
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
$(function() {
|
||||
function AboutViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.aboutDialog = undefined;
|
||||
|
||||
self.show = function() {
|
||||
self.aboutDialog.modal({
|
||||
minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); }
|
||||
}).css({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
});
|
||||
return false;
|
||||
};
|
||||
|
||||
self.hide = function() {
|
||||
self.aboutDialog.modal("hide");
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.aboutDialog = $('#about_dialog');
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
AboutViewModel,
|
||||
[],
|
||||
["#about_dialog", "#footer_about"]
|
||||
]);
|
||||
});
|
||||
Loaded 100 of 197 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user