diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
index 97a7e30cc..c65e40fb2 100644
--- a/.github/ISSUE_TEMPLATE.md
+++ b/.github/ISSUE_TEMPLATE.md
@@ -1,29 +1,25 @@
+
#### What were you doing?
-[Please be as specific as possible here. The maintainers will need to
+
1. ...
2. ...
3. ...
+
#### What did you expect to happen?
@@ -59,50 +54,75 @@ to also include a link to a file with which to reproduce the problem.]
#### Did the same happen when running OctoPrint in safe mode?
-[Try to reproduce your problem in safe mode. You can find information
-on how to enable safe mode in the Contribution Guidelines.]
+
+
+#### Version of OctoPrint
+
+
#### Operating System running OctoPrint
-[OctoPi, Linux, Windows, MacOS, something else? With version please.
-OctoPi's version can be found in /etc/octopi_version]
+
#### Printer model & used firmware incl. version
-[If applicable, always include if unsure.]
+
-#### Browser and Version of Browser, Operating System running Browser
+#### Browser and version of browser, operating system running browser
-[If applicable, always include if unsure.]
+
#### Link to octoprint.log
-[On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.
-The Contribution Guidelines tell you where to find that.]
+
#### Link to contents of terminal tab or serial.log
-[On gist.github.com or pastebin.com. If applicable, always include if unsure or
+
#### Link to contents of Javascript console in the browser
-[On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
+
#### Screenshot(s)/video(s) showing the problem:
-[If applicable. Always include if unsure or reporting UI issues.]
+
I have read the FAQ.
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 4c18b123c..c9b4d9f22 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -1,3 +1,4 @@
+
* [ ] Your changes are not possible to do through a plugin and relevant
to a large audience (ideally all users of OctoPrint)
@@ -16,12 +18,13 @@ checklist:
Brainstorming ticket
* [ ] Your PR targets OctoPrint's devel branch, or maintenance if it's
a bug fix for an issue present in the current stable version (no PRs
- against master or anything else)
+ against master or anything else please)
* [ ] Your PR was opened from a custom branch on your repository
(no PRs from your version of master, maintenance or devel please),
- e.g. dev/my_new_feature
+ e.g. dev/my_new_feature or fix/my_bugfix
* [ ] Your PR only contains relevant changes: no unrelated files,
- no dead code, ideally only one commit - rebase your PR if necessary!
+ no dead code, ideally only one commit - rebase and squash your PR
+ if necessary!
* [ ] Your changes follow the existing coding style
* [ ] If your changes include style sheets: You have modified the
.less source files, not the .css files (those are generated with
@@ -32,11 +35,10 @@ checklist:
nothing broke
* [ ] You have added yourself to the AUTHORS.md file :)
-Feel free to delete all this help text, then describe
-your PR further. You may use the template provided below to do that.
-The more details the better!
-
-----
+
#### What does this PR do and why is it necessary?
diff --git a/.versioneer-lookup b/.versioneer-lookup
index ed09d1585..acbff62a1 100644
--- a/.versioneer-lookup
+++ b/.versioneer-lookup
@@ -7,23 +7,27 @@
# The file is processed from top to bottom, the first matching line wins. If or are left out,
# the lookup table does not apply to the matched branches
-# master and rc shall not use the lookup table, only tags
+# master, meta, rc and prerelease shall not use the lookup table, only tags
master
+meta/.*
rc/.*
+hotfix/.*
prerelease
# neither should disconnected checkouts, e.g. 'git checkout '
HEAD
\(detached.*
-# maintenance is currently the branch for preparation of maintenance release 1.3.5
+# maintenance is currently the branch for preparation of maintenance release 1.3.9
# so are any fix/... and improve/... branches
-maintenance 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
-fix/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
-improve/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
+maintenance 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
+fix/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
+improve/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
-# staging/maintenance is currently the branch for preparation of 1.3.5rc1
-staging/maintenance 1.3.5rc1 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
+# staging/maintenance is currently the branch for preparation of 1.3.7rc5
+# so is regressionfix/...
+staging/maintenance 1.3.7rc5 e5caa3d0bf77ed23f04c1d96ab0fa997d19d2006 pep440-dev
+regressionfix/.* 1.3.7rc5 e5caa3d0bf77ed23f04c1d96ab0fa997d19d2006 pep440-dev
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
diff --git a/AUTHORS.md b/AUTHORS.md
index 21add4213..47bf5a210 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -1,6 +1,6 @@
# Authors
-The following people have contributed to OctoPrint's code base (ordered by
+The following people have contributed to OctoPrint's code base (ordered roughly by
date of first contribution):
* [Gina Häußge](https://github.com/foosel)
@@ -61,10 +61,11 @@ date of first contribution):
* [Siim Raud](https://github.com/2ndalpha)
* ["geoporalis"](https://github.com/geoporalis)
* [Andrew Malota](https://github.com/2bitoperations)
- * [Alexander Leisentritt](https://github.com/Alex9779)
- * [therealbstern](https://github.com/therealbstern)
* [Ishwar Agarwal](https://github.com/agarwali)
* [Kye Hoover](https://github.com/eykrevooh)
+ * [Joseph Carrick](https://github.com/carricktel)
+ * [Alexander Leisentritt](https://github.com/Alex9779)
+ * [therealbstern](https://github.com/therealbstern)
* [Philipp Baum](https://github.com/philphilphil)
* [Kyle Evans](https://github.com/kevans91)
* [Javier Martínez Arrieta](https://github.com/Javierma)
@@ -80,8 +81,16 @@ date of first contribution):
* [Greg Hulands](https://github.com/ghulands)
* [Andreas Werner](https://github.com/gallore)
* [Shawn Bruce](https://github.com/kantlivelong)
- * [Claudiu Ceia] (https://github.com/ClaudiuCeia)
+ * [Claudiu Ceia](https://github.com/ClaudiuCeia)
* [Goswin von Brederlow](https://github.com/mrvn)
+ * [Luke McKechnie](https://github.com/galamdring)
+ * [Peter Backx](https://github.com/pbackx)
+ * [Josh Major](https://github.com/astateofblank)
+ * ["alex-gh"](https://github.com/alex-gh)
+ * [Bernd Zeimetz](https://github.com/bzed)
+ * [Daniele Forsi](https://github.com/dforsi)
+ * [Ganey](https://github.com/ganey)
+ * [Sven Lohrmann](https://github.com/malnvenshorn)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
[Daid Braam](https://github.com/daid). Parts of its communication layer and
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3a36cf58f..7660f4901 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,332 @@
# OctoPrint Changelog
+## 1.3.8 (2018-04-13)
+
+### Bug fixes
+
+ * [#2577](https://github.com/foosel/OctoPrint/issues/2577) - Pin `psutil` dependency to version 5.4.3 since 5.4.4 as released today introduces a breaking change.
+
+([Commits](https://github.com/foosel/OctoPrint/compare/1.3.7...1.3.8))
+
+## 1.3.7 (2018-04-09)
+
+### Improvements
+
+ * [#324](https://github.com/foosel/OctoPrint/issues/324) & [#2414](https://github.com/foosel/OctoPrint/issues/2414) - Native support for the following [@ commands](http://docs.octoprint.org/en/maintenance/features/atcommands.html): `@pause` (pauses the print), `@resume` (resumes the print), `@cancel` or `@abort` (cancels the print). More commands can be added through the plugin hooks [`octoprint.comm.protocol.atcommand.*`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-atcommand-phase).
+ * [#1951](http://github.com/foosel/OctoPrint/issues/1951) - Fixed plugins being able to modify internal state data (e.g. progress, job), causing concurrent modification and resulting run time errors in the printer state processing.
+ * [#2208](https://github.com/foosel/OctoPrint/issues/2208) - New plugin hook [`octoprint.comm.protocol.gcode.error`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-gcode-error) to allow plugins to override OctoPrint's handling of `Error:`/`!!` messages reported by the firmware. Can be used to "downgrade" errors that aren't actually fatal errors that make the printer halt.
+ * [#2213](https://github.com/foosel/OctoPrint/issues/2213) - Made sure to prevent accidental configuration of a temperature cutoff value less than 1min for the temperature graph.
+ * [#2250](https://github.com/foosel/OctoPrint/pull/2250) - Added [`octoprint.util.ResettableTimer`](http://docs.octoprint.org/en/maintenance/modules/util.html#octoprint.util.ResettableTimer) helper class.
+ * [#2287](https://github.com/foosel/OctoPrint/issues/2287) - Added confirmation for attempting to disconnect during an ongoing print. See also [#2466](https://github.com/foosel/OctoPrint/pull/2466).
+ * [#2302](https://github.com/foosel/OctoPrint/issues/2302) - Detect invalid tools as reported by firmware and blacklist them for `T` commands.
+ * [#2317](https://github.com/foosel/OctoPrint/issues/2317) - Removed capturing of post roll images for time based timelapses, was causing too much confusion and surprise.
+ * [#2335](https://github.com/foosel/OctoPrint/issues/2335) - First throw at detecting if a print from the printer's SD was started outside of OctoPrint via the printer's control panel. Requires some specific requirements to be fulfilled by the printer's firmware to function properly:
+ * Firmware must send a "File opened: ..." message on start of the print
+ * Firmware must respond to an immediately sent `M27` with `SD printing byte /`
+ * Firmware must stay responsive during ongoing print to allow for regular M27 polls (or push those automatically) or M25 to pause/cancel the print through OctoPrint.
+ * Firmware must send `Done printing file` or respond to `M27` with `Not SD printing` when SD printing finishes (either due to being done or to having been cancelled by the user).
+ * [#2362](https://github.com/foosel/OctoPrint/issues/2362) - Added option to configure timelapse snapshot timeout.
+ * [#2367](https://github.com/foosel/OctoPrint/issues/2367) - Added support for `//action:cancel` action command.
+ * [#2378](https://github.com/foosel/OctoPrint/issues/2378) - Made GCODE viewer gracefully handle GCODE subcodes.
+ * [#2385](https://github.com/foosel/OctoPrint/pull/2385) - Made valid boolean trues check case insensitive.
+ * [#2304](https://github.com/foosel/OctoPrint/pull/2304) & [#2405](https://github.com/foosel/OctoPrint/pull/2405) - Added support to trust Basic Authentication headers for user login. Currently requires [manual configuration through `config.yaml`](http://docs.octoprint.org/en/maintenance/configuration/config_yaml.html#access-control), see the `accessControl.trustBasicAuthentication` and `accessControl.checkBasicAuthenticationPassword` settings.
+ * [#2338](https://github.com/foosel/OctoPrint/pull/2338) - Allowed plugins to define GCODE script variables using the `octoprint.comm.protocol.scripts` hook.
+ * [#2406](https://github.com/foosel/OctoPrint/pull/2406) - Extracted log management into its own bundled plugin and allow fine tuning of log levels.
+ * [#2409](https://github.com/foosel/OctoPrint/pull/2409) - Added `m4v` and `mkv` to the list of accepted timelapse extensions.
+ * [#2444](https://github.com/foosel/OctoPrint/pull/2444) - Support additional CSS classes on custom control buttons.
+ * [#2448](https://github.com/foosel/OctoPrint/issues/2448) - Also detect plugins in `~/.octoprint/plugins` that are provided as bytecode `pyc` instead of source `py` files.
+ * [#2455](https://github.com/foosel/OctoPrint/issues/2455) - Added option to configure SSL validation for snapshot URL.
+ * Support `M114` response format of RepRapFirmware (uses `X:... Y:... Z:... E0:... E1:...` instead of
+`X:... Y:... Z:... E:...`)
+ * Added refresh button to connection panel for easy refresh of the available ports to connect to without having to reload the whole page.
+ * Increased upper bound of PySerial dependency from 2.7 to 3.4. See also [#2333](https://github.com/foosel/OctoPrint/issues/2333).
+ * Switch to lower communication timeouts if support of the `busy` protocol by the firmware is detected.
+ * Refactored serial settings dialog, now has sub tabs and more explanations.
+ * Allow to disable support for certain firmware capabilities, even if reported as supported by the firmware: `busy` protocol, temperature auto reporting, SD status auto reporting
+ * Attached tags to GCODE commands moving through the comm layer and allowed plugins to access and extend these tags through the GCODE hooks. Makes it possible for plugins to detect the origin of a command (streamed file vs. GCODE script vs. user input vs. plugin), the point where it entered the system and so on. Also added a new logger `octoprint.util.comm.command_phases` that if set to `DEBUG` will log the lifecycle of commands through the comm layer including tags to `octoprint.log`. See also [the docs here](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-gcode-phase).
+ * Added new [`job_on_hold`](http://docs.octoprint.org/en/maintenance/modules/printer.html#octoprint.printer.PrinterInterface.job_on_hold) and [`set_job_on_hold`](http://docs.octoprint.org/en/maintenance/modules/printer.html#octoprint.printer.PrinterInterface.set_job_on_hold) methods on the printer instance, allowing plugins to quickly stall the streaming of a queue. This should be used sparingly - abuse will have significant negative effects on the print job. Read the docs if you plan to utilize this.
+ * Support extraction of plugin metadata even from disabled and blacklisted plugins through the AST of the module.
+ * Better logging of printer callback errors and utilization of `frozendict` for internal printer state propagation in an attempt to narrow down on [#1951](https://github.com/foosel/OctoPrint/issues/1951). Should `frozendict` cause issues it can be disabled through the settings in `config.yaml`, just set `devel.useFrozenDictForPrinterState` to `false`
+ * Log comm state changes to `octoprint.log`.
+ * Added a regular server heartbeat to the log (every 15min).
+ * Support SD status auto report by the firmware.
+ * Added `Not SD printing` to default "SD status" terminal filters.
+ * Added custom `readline` implementation for the serial port. Instead of relying on PySerial's `readline` that depending on the installed version might only read from the port one byte at the time, we now wait for one byte and then read everything available into a persistent buffer which then is used to fetch lines from.
+ * Ensure that `callViewModelIf` doesn't try to call null or uncallable `method`s.
+ * Added links to the new [Community Forum](https://discourse.octoprint.org) and the new location of the [FAQ](https://faq.octoprint.org).
+ * Improved pip utility logging, `LocalPipHelper` wasn't producing output, making it hard to debug such non writable install directories.
+ * Added a new bundled plugin "Printer Safety Check" that will try to identify printer/printer firmware with known safety issues such as missing thermal runaway protection.
+ * Plugin Manager: Reduce notification spam. See also [#2260](https://github.com/foosel/OctoPrint/issues/2260).
+ * Software Update Plugin: Better detection if an update is already running.
+ * Software Update Plugin: Refer to `plugin_softwareupdate_console.log` on update errors in log and notification.
+
+### Bugfixes
+
+ * [#2294](https://github.com/foosel/OctoPrint/issues/2294) - Improved resilience against errors during gathering the file list (e.g. permission errors)
+ * [#2296](https://github.com/foosel/OctoPrint/issues/2296) - Fixed `X-Forwarded-For` handling in Flask Login through monkey patched backport.
+ * [#2297](https://github.com/foosel/OctoPrint/issues/2297) - Return `403` instead of `401` on missing/insufficient credentials.
+ * [#2311](https://github.com/foosel/OctoPrint/issues/2311) - Fixed server not auto connecting on startup if port is set to `AUTO` (see also [#2311](https://github.com/foosel/OctoPrint/pull/2337)).
+ * [#2316](https://github.com/foosel/OctoPrint/issues/2316) - Check for valid queue entry in file analysis queue before trying to dequeue, fix for a HTTP `500` on upload of a file not supported for analysis.
+ * [#2321](https://github.com/foosel/OctoPrint/issues/2321) & [#2449](https://github.com/foosel/OctoPrint/issues/2449) - Fixed wrong queuing order of cancel script & first line from printed file on quick start-cancel-start scenarios by introducing a two new states "Cancelling" and "Pausing".
+ * [#2324](https://github.com/foosel/OctoPrint/pull/2324) - Fixed 500 error when
+ * [#2333](https://github.com/foosel/OctoPrint/issues/2333) (Part 1/3) - Workaround for an update problem caused by interaction of `pip` with dependencies formerly installed as eggs through `python setup.py install`.
+ * [#2333](https://github.com/foosel/OctoPrint/issues/2333) (Part 2/3) - If supported by the underlying PySerial version, cancel all reads and writes on disconnect if possible for a faster connection release. Part 3 (forcing an upgrade of PySerial to 3.4 so this should work in more cases) will in OctoPrint 1.3.8.
+ * [#2364](https://github.com/foosel/OctoPrint/issues/2364) - Fixed firmware error reporting in case of cancelling a print due to a firmware error.
+ * [#2368](https://github.com/foosel/OctoPrint/issues/2368) - Fixed for incorrect handling of unicode filenames in cura slicer profiles
+ * [#2371](https://github.com/foosel/OctoPrint/issues/2371) - Removed "just now"/"gerade eben" label from temperature graph to work around a graph resize issue caused by that.
+ * [#2392](https://github.com/foosel/OctoPrint/issues/2392) - Fixed "Copy all" on terminal tab only working the first time.
+ * [#2406](https://github.com/foosel/OctoPrint/pull/2406) - Fixed `showTab` JS function of about dialog.
+ * [#2426](https://github.com/foosel/OctoPrint/issues/2426) - Made resend logging to `octoprint.log` unicode safe
+ * [#2442](https://github.com/foosel/OctoPrint/issues/2442) - Don't even import disabled plugins, use a dummy entry for them just like for backlisted plugins. More resilience against misbehaving plugins.
+ * [#2461](https://github.com/foosel/OctoPrint/issues/2461) - Fixed OctoPrint not properly disconnecting in case of a firmware error.
+ * [#2494](https://github.com/foosel/OctoPrint/issues/2494) - Fixed `undefined` values not saving in the settings.
+ * [#2499](https://github.com/foosel/OctoPrint/issues/2499) (regression) - Fixed communication error notification lacking the actual error message.
+ * [#2501](https://github.com/foosel/OctoPrint/issues/2501) (regression) - Fixed a bug causing log downloads to fail with an HTTP 500 error.
+ * [#2506](https://github.com/foosel/OctoPrint/issues/2506) (regression) - Fixed `printer.get_current_data` and `printer.get_current_job` returning `frozendict` instead of `dict` instances, causing issues with plugins relying on being able to modify the returned data (e.g. [dattas/OctoPrint-DetailedProgress#26](https://github.com/dattas/OctoPrint-DetailedProgress/issues/26)).
+ * [#2508](https://github.com/foosel/OctoPrint/issues/2508) (regression) - Fixed HTTP 500 error on `/api/slicing` in case of an unconfigured slicer.
+ * [#2524](https://github.com/foosel/OctoPrint/issues/2524) - Ignore `wait` while job is on hold.
+ * [#2536](https://github.com/foosel/OctoPrint/issues/2536) - Fix a wrong state tracking when starting an SD print through the controller, causing a disconnect due to a timeout.
+ * [#2544](https://github.com/foosel/OctoPrint/issues/2544) (regression) - Fix an exception when connecting to the raw websocket at `/sockjs/websocket` (instead of `/sockjs///websocket`).
+ * [#2546](https://github.com/foosel/OctoPrint/issues/2546) (regression) - Fix the `PRINT_FAILED` event getting triggered twice on print failure due to disconnect
+ * Use `pkg_resources` to determine pip version during environment check instead of `import pip; pip.__version__` since the latter causes issues with pip version 9.0.2. In the same spirit make `pip.main` approach of calling `pip` in the PipCaller the last resort during auto detection, only after trying `pip` or `pip.exe` inside the same folder as the Python executable.
+ * Use `octoprint.util.monotonic_time` instead of `monotonic.monotonic` in comm layer.
+ * Fixed timelapse not stopping on print failure due to firmware error due to missing `PrintFailed` event.
+ * Announcement Plugin: Fixed a missing line break in case of more than three announcements in a notification.
+ * Docs: Documentation for printer profile related bits and pieces
+ * Docs: Various fixes of typos and grammar.
+ * Have `OctoPrintJsonEncoder` fall back to regular flask JSON encoder, otherwise we might not be able to serialize some data types we need to be able to serialize. (regression)
+
+### Known bugs
+
+ * [#2547](https://github.com/foosel/OctoPrint/issues/2547) - Error during processing of afterPrintJobDone script will trigger PRINT_FAILED event even though PRINT_DONE event was already triggered
+
+### More Information
+
+ * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.6...1.3.7)
+ * Release Candidates:
+ * [1.3.7rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc1)
+ * [1.3.7rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc2)
+ * [1.3.7rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc3)
+ * [1.3.7rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc4)
+ * A special **Thank you!** to everyone who reported back on these release candidates this time:
+ [aaronkeck](https://github.com/aaronkeck), [akurz42](https://github.com/akurz42), [andrivet](https://github.com/andrivet), [anthonyst91](https://github.com/anthonyst91), [arhi](https://github.com/arhi), [b-morgan](https://github.com/b-morgan), [BryanSmithDev](https://github.com/BryanSmithDev), [chippypilot](https://github.com/chippypilot), [ChrisHeerschap](https://github.com/ChrisHeerschap), [Crowlord](https://github.com/Crowlord), [dforsi](https://github.com/dforsi), [drdelaney](https://github.com/drdelaney), [FormerLurker](https://github.com/FormerLurker), [goeland86](https://github.com/goeland86), [inspiredbylife](https://github.com/inspiredbylife), [jbjones27](https://github.com/jbjones27), [jesasi](https://github.com/jesasi), [jneilliii](https://github.com/jneilliii), [JohnOCFII](https://github.com/JohnOCFII), [kantlivelong](https://github.com/kantlivelong), [lnx13](https://github.com/lnx13), [makaper](https://github.com/makaper), [markwal](https://github.com/markwal), [MiquelAdell](https://discourse.octoprint.org/u/MiquelAdell), [ml0w](https://github.com/ml0w), [mmotley999](https://github.com/mmotley999), [mrhanman](https://github.com/mrhanman), [SCiunczyk](https://github.com/SCiunczyk), [tdub415](https://github.com/tdub415), [tedder42](https://discourse.octoprint.org/u/tedder42), [thatjoshguy](https://github.com/thatjoshguy), [wescrockett](https://github.com/wescrockett)
+
+## 1.3.6 (2017-12-12)
+
+### Note for upgraders and plugin authors: Change in the bundling of JS assets can lead to issues in plugins
+
+A change to solve issues with plugins bundling JS assets that cause interference with other plugins (e.g. through the declaration of `"use strict"`) and in general to add better isolation and error handling might cause errors for some plugins that go beyond your run-off-the-mill view model and also implicitly declare new globals.
+
+If you happen to run into any such issues, you can switch back to the old way of bundling JS assets via the newly introduced "Settings > Feature > Enable legacy plugin asset bundling" toggle (check it, save the settings, restart the server). This is provided to allow for a minimally invasive adjustment period until affected plugins have been updated.
+
+You can find out more about the change, how to know if a plugin is even affected and what do about it [on the OctoBlog](https://octoprint.org/blog/2017/12/01/heads-up-plugin-authors/).
+
+### Improvements
+
+ * [#203](https://github.com/foosel/OctoPrint/issues/203) - Allow selecting the current tab via URL hashs. Also update URL hash when switching tabs, thus adding this to the browser history and allowing quicker back and forth navigation through the browser's back and forward buttons.
+ * [#1026](https://github.com/foosel/OctoPrint/issues/1026) - Automatically upper case parameters in GCODE commands sent from the Terminal tab. A black list is in place that prevent upper casing of parameters for GCODE commands where it doesn't make sense (default: `M117`). See also [#2177](https://github.com/foosel/OctoPrint/pull/2177).
+ * [#2050](https://github.com/foosel/OctoPrint/issues/2050) - New hook [`octoprint.comm.protocol.temperatures.received`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-temperatures-received) that allows plugins to further preprocess/sanitize temperature data received from the printer.
+ * [#2055](https://github.com/foosel/OctoPrint/issues/2055) - Increased the size of the API key field in the settings.
+ * [#2056](https://github.com/foosel/OctoPrint/issues/2056) - Added a Copy button to the API key field in the settings and user settings.
+ * [#2094](https://github.com/foosel/OctoPrint/issues/2094) - Allow UTF-8 display names for uploaded files. The files will still get an ASCII only name on disk, but the UTF-8 name used during upload will also be persisted and shown in the file list. This also allows using emojis in your file and folder names now.
+ * [#2104](https://github.com/foosel/OctoPrint/issues/2104) - Allow more URL schemes for installing plugins from. Supported schemes should now mirror what `pip` itself supports: `http`, `https`, `git`, `git+http`, `git+https`, `git+ssh`, `git+git`, `hg+http`, `hg+https`, `hg+static-http`, `hg+ssh`, `svn`, `svn+svn`, `svn+http`, `svn+https`, `svn+ssh`, `bzr+http`, `bzr+https`, `bzr+ssh`, `bzr+sftp`, `bzr+ftp`, `bzr+lp`.
+ * [#2109](https://github.com/foosel/OctoPrint/pull/2109) - New decorator `@firstrun_only_access` for API endpoints that should only be available before first setup has been completed.
+ * [#2111](https://github.com/foosel/OctoPrint/issues/2111) - Made the file list's scroll bar wider.
+ * [#2131](https://github.com/foosel/OctoPrint/issues/2131) - Added warning to restart, shutdown, reboot and update confirmations that that may disrupt ongoing prints, even those run from the printer's internal storage/SD. See also [#2146](https://github.com/foosel/OctoPrint/pull/2146) and [#2152](https://github.com/foosel/OctoPrint/pull/2152).
+ * [#2138](https://github.com/foosel/OctoPrint/issues/2138) - Slightly longer timeout when attempting to read from serial during auto detection via programming mode. Might help with detection of some slower printer controllers under certain circumstances.
+ * [#2200](https://github.com/foosel/OctoPrint/issues/2200) - Wrap all JS assets of plugins into one anonymous function per plugin. That way plugins using `"use strict";` won't cause hard to debug and weird issues with other plugins bundled after them. The down side is that plugins currently relying on implicit declaration of global helper functions or variables (`function convert(value) { ... }`) to be available outside of their own plugin's JS assets will now run into errors. To compensate for that while affected plugins are adjusted to declare globals explicitly (`window.convert = function(value) { ... }`), a temporary feature flag was added as "Settings > Features > Enable legacy plugin asset bundling" that switches back to the old form of bundling until plugins you rely on are updated. This flag will be removed again in a later version (currently planned for 1.3.8). See also the note above and [#2246](https://github.com/foosel/OctoPrint/issues/2246).
+ * [#2229](https://github.com/foosel/OctoPrint/issues/2229) - Added note to printer profile dialog that the nozzle offsets for multi extruder setups are only to be configured if they are not already set in the printer's firmware.
+ * [#2232](https://github.com/foosel/OctoPrint/issues/2232) - Disable movement distance buttons when not connected to the printer or when printing, since they don't have any use then.
+ * [#2239](https://github.com/foosel/OctoPrint/pull/2239) - Improved the check summing speed, thus improving the general achievable throughput on the comm layer.
+ * Allow cancelling of file transfers
+ * Made check of how old an unrendered timelapse is more lenient buy looking at both the creation and last modification date and using the younger one.
+ * Made notifications in general auto-close faster.
+ * Make the first profile saved for a slicer the default profile for that slicer.
+ * New command `server` for testing server connections on the [JS test API](http://docs.octoprint.org/en/maintenance/api/util.html#post--api-util-test).
+ * New hook [`octoprint.accesscontrol.keyvalidator`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-accesscontrol-keyvalidator) that allows plugins to validate their own customized API keys to be used to access OctoPrint.
+ * Updated `cookiecutter`, `requests` and `psutil` dependencies.
+ * Added safety warning to first run wizard.
+ * More error resilience against broken view models.
+ * New sub command `octoprint safemode`. Will set the `server.startOnceInSafeMode` setting in the config so that the next (re)start of the server after issuing this command will happen in safe mode.
+ * New sub command `octoprint config effective`. Will report the effective config.
+ * New centralized plugin blacklist (opt-in). Allows to prevent plugins/certain versions of plugins known to cause crippling issues with the normal operation of OctoPrint to be disabled from loading, if the user has opted to do so in the settings/wizard.
+ * Log how to enable `serial.log` to `serial.log` if it's disabled. That will hopefully put at least a small dent in the amount of "It's empty!" responses in tickets ;)
+ * Force new Pypi index URL in `requirements.txt` as an additional work around against old tooling.
+ * Prefer plain `pip` over `git` for updating OctoPrint.
+ * Added environment detection and logging on startup. That should give us more information about the environment to produce a reported bug in.
+ * Added OctoPi support plugin that provides information about the detected OctoPi version. Will only load if OctoPi is detected.
+ * More dynamic plugin mixin detection. Now using a base class instead of having to list all types manually. Should greatly reduce overhead of adding new mixin types.
+ * Support leaf merging for file extension tree, allowing to add new file extensions to types registered by default.
+ * Allow non GCODE SD file transfers if registered as `machinecode` through e.g. a plugin's file extension hook. Caution: This doesn't make streaming arbitrary files to the printer via serial work magically. It merely allows that, it's up to the firmware to actually be able to handle that. Also, the regular GCODE streaming protocol is used, so if the streamed file contains control characters from that (e.g. `M29` to signal the end of the streaming process), stuff will break!
+ * Added a test button for the online connectivity check.
+ * Announcements plugin: Added UTM Tags.
+ * Cura plugin: Less `not configured yet` logging.
+ * GCODE viewer: Added advanced options that allow configuring display of bounding boxes, sorting by layers and hiding of empty layers.
+ * GCODE viewer: Persist all options to local storage so they will be automatically set again the next time the GCODE viewer is used in the same browser.
+ * Software update: Auto-hide "Everything is up-to-date" notification.
+ * Easier copying of terminal contents thanks to dedicated copy button.
+ * Timelapse: [#2067](https://github.com/foosel/OctoPrint/issues/2067) - Added rate limiting to z-based timelapse capturing to prevent issues when accidentally leaving this mode on with vase mode prints.
+ * Timelapse: Refactored configuration form & added reset button to switch back to currently active settings.
+ * Timelapse: Sort timelapses by modification instead of creation time (creation time can be newer if a backup restore was done).
+ * Virtual printer: Support configurable ambient temperature for testing.
+ * Virtual printer: Support configurable reset lines.
+ * Virtual printer: Added new debug trigger `trigger_missing_lineno`.
+ * Virtual printer: Allow empty/`None` prepared oks, allowing to simulate lost acknowledgements right on start.
+ * Docs: [#2142](https://github.com/foosel/OctoPrint/pull/2142) - Added documentation for the bundled virtual printer plugin.
+ * Docs: [#2234](https://github.com/foosel/OctoPrint/pull/2234) - Added info on how to install under Suse Linux.
+ * Docs: Added example PyCharm run configuration that includes automatic dependency updates on start.
+ * Docs: Added information on how to run the test suite.
+ * Various refactorings
+ * Various documentation updates
+ * Fetch plugin blacklist (and also announcements, plugin notices and plugin repository) via https instead of http.
+
+### Bug fixes
+
+ * [#2044](https://github.com/foosel/OctoPrint/pull/2044) - Fix various typos in strings and comments
+ * [#2048](https://github.com/foosel/OctoPrint/pull/2048) & [#2176](https://github.com/foosel/OctoPrint/pull/2176) - Fixed various warnings during documentation generation.
+ * [#2077](https://github.com/foosel/OctoPrint/issues/2077) - Fix an issue with shared nozzles and the temperature graph, causing temperature to not be reported properly when another tool but the first one is selected. See also [#2077](https://github.com/foosel/OctoPrint/pull/2123)
+ * [#2108](https://github.com/foosel/OctoPrint/issues/2108) - Added no-op default action to login form so that username + password aren't sent as GET parameters if for some reason the user tries to log in before the view models are properly bound and thus the AJAX POST submission method is attached.
+ * [#2111](https://github.com/foosel/OctoPrint/issues/2111) - Prevent file list's scroll bar from fading out.
+ * [#2146](https://github.com/foosel/OctoPrint/issues/2147) - Fix initialization of temperature graph if it's not on the first tab due to tab reordering.
+ * [#2166](https://github.com/foosel/OctoPrint/issues/2166) - Workaround for a Firefox bug that causes the Drag-n-Drop overlay to never go away if the file is dragged outside of the browser window.
+ * [#2167](https://github.com/foosel/OctoPrint/issues/2167) - Fixed grammar of print time estimation tooltip
+ * [#2175](https://github.com/foosel/OctoPrint/issues/2175) - Cancel printing when an external reset of the printer is detected on the serial connection.
+ * [#2181](https://github.com/foosel/OctoPrint/issues/2181) - More resilience against non-standard `M115` responses.
+ * [#2182](https://github.com/foosel/OctoPrint/pull/2182) - Don't start tracking non existing or nonfunctional tools if encountering a temperature command referencing said tool. See also [kantlivelong/OctoPrint-PSUControl#68](https://github.com/kantlivelong/OctoPrint-PSUControl/issues/68).
+ * [#2196](https://github.com/foosel/OctoPrint/issues/2196) - Marked API key fields as `readonly` instead of `disabled` to allow their contents to be copied in Firefox (which wasn't possible before).
+ * [#2203](https://github.com/foosel/OctoPrint/issues/2203) - Reset temperature offsets to 0 when disconnected from the printer.
+ * [#2206](https://github.com/foosel/OctoPrint/issues/2206) - Disable pre-configured timelapse if snapshot URL of ffmpeg path are unset.
+ * [#2214](https://github.com/foosel/OctoPrint/issues/2214) - Fixed temperature fields not selecting in MS Edge on focus.
+ * [#2217](https://github.com/foosel/OctoPrint/pull/2217) - Fix an issue in `octoprint.util` causing a crash when running under PyPy instead of CPython.
+ * [#2226](https://github.com/foosel/OctoPrint/issues/2226) - Handle `No Line Number with checksum, Last Line: ...` errors from the firmware.
+ * [#2233](https://github.com/foosel/OctoPrint/pull/2233) - Respond with `411 Length Required` when content length is missing on file uploads.
+ * [#2242](https://github.com/foosel/OctoPrint/issues/2242) - Fixed an issue where print time left could show "1 days" instead of "1 day".
+ * [#2262](https://github.com/foosel/OctoPrint/issues/2262) (regression) - Fixed a bug causing `Error:checksum mismatch, Last Line: ...` errors from the firmware to be handled incorrectly.
+ * [#2267](https://github.com/foosel/OctoPrint/issues/2267) (regression) - Fixed a bug causing the GCODE viewer to not get properly initialized due to a JS error on load if "Also show next layer" was selected.
+ * [#2268](https://github.com/foosel/OctoPrint/issues/2268) (regression) - Fixed a bug causing a display error with the temperature offsets. If one offset was changed, all others seemed to revert back to 0.
+ * Fixed cleanup of unrendered timelapses with certain names.
+ * Fixed a caching issue with the file list API and the slicing API.
+ * Fixed initial sizing of the temperature graph.
+ * More resilience against corrupt `.metadata.yaml` files.
+ * More resilience against corrupt/invalid entries for system actions.
+ * More resilience against invalid JSON command requests.
+ * More resilience against broken packages in the python environment.
+ * Don't evaluate `onWebcamLoaded` more than once when switching to the webcam tab.
+ * Fixed `octoprint config` sub command.
+ * Fixed deactivated user accounts being able to login (albeit without a persistent session). Show fitting error instead.
+ * Fixed temperature auto report after an external reset.
+ * Don't log full request headers in Tornado on an error.
+ * Fix displayed notification message for synchronous system commands. Was accidentally swapped with the one for asynchronous system commands.
+ * GCODE viewer: Fix error on empty layers.
+ * Virtual printer: Fix resend simuation.
+ * Docs: Fixed CSS of line numbered listings.
+ * Docs: Updated mermaid to fix a deprecation warning.
+ * Fixed ordering of plugin assets, should be alphabetical based on the plugin identifier. (regression)
+ * Fixed an issue causing redundant software update configuration settings to be written to `config.yaml`, in turn causing issues when downgrading to <1.3.5. (regression)
+ * Fixed an issue detecting whether the installed version is a release version or a development version. (regression)
+
+### More Information
+
+ * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.5...1.3.6)
+ * Release Candidates:
+ * [1.3.6rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.6rc1)
+ * [1.3.6rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.6rc2)
+ * [1.3.6rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.6rc3)
+ * A special **Thank you!** to everyone who reported back on these release candidates this time: [andrivet](https://github.com/andrivet), [b-morgan](https://github.com/b-morgan), [bjarchi](https://github.com/bjarchi), [chippypilot](https://github.com/chippypilot), [ChrisHeerschap](https://github.com/ChrisHeerschap), [cosmith71](https://github.com/cosmith71), [Crowlord](https://github.com/Crowlord), [ctgreybeard](https://github.com/ctgreybeard), [fiveangle](https://github.com/fiveangle), [goeland86](https://github.com/goeland86), [jbjones27](https://github.com/jbjones27), [jneilliii](https://github.com/jneilliii), [JohnOCFII](https://github.com/JohnOCFII), [Kunsi](https://github.com/Kunsi), [Lordxv](https://github.com/Lordxv), [malnvenshorn](https://github.com/malnvenshorn), [mcp5500](https://github.com/mcp5500), [ntoff](https://github.com/ntoff), [ripp2003](https://github.com/ripp2003) and [schorsch3000](https://github.com/schorsch3000)
+
+## 1.3.5 (2017-10-16)
+
+### Improvements
+
+ * [#1162](https://github.com/foosel/OctoPrint/pull/1162) - Allow `octoprint.comm.protocol.gcode.queuing` hook to return a list of commands.
+ * [#1572](https://github.com/foosel/OctoPrint/issues/1572) & [#1881](https://github.com/foosel/OctoPrint/issues/1881) - Refactored web interface startup process to minimise risk of race conditions and speed improvements. Also added sequence diagram to the documentation showing the new processing order.
+ * [#1640](https://github.com/foosel/OctoPrint/issues/1640) - Mouse over temperature graph to get exact data for that time.
+ * [#1679](https://github.com/foosel/OctoPrint/issues/1679) - Support temperature autoreporting by the firmware instead of polling if the firmware reports to support it. For this to work with Marlin 1.1.0 to 1.1.3 you'll need to explicitly enable `EXTENDED_CAPABILITIES_REPORT` *and* `AUTO_REPORT_TEMPERATURES` in your firmware configuration, otherwise your firmware won't report that it actually supports this feature.
+ * [#1737](https://github.com/foosel/OctoPrint/issues/1737) - Auto-detect Anet A8 firmware and treat as Repetier Firmware (which it actually appears to be, just renamed - thanks Anet for making this even harder).
+ * [#1842](https://github.com/foosel/OctoPrint/issues/1842) - Update bundled FontAwesome to 4.7 (see also [#1915](https://github.com/foosel/OctoPrint/pull/1915)).
+ * [#1910](https://github.com/foosel/OctoPrint/issues/1910) - Make last/pause/cancel temperature available for GCODE scripts.
+ * [#1925](https://github.com/foosel/OctoPrint/issues/1925) - Include configured webcam stream URL in "Webcam stream not loaded" message for logged in users/admins. Slightly different wording for guests vs users vs admins.
+ * [#1941](https://github.com/foosel/OctoPrint/issues/1941) - Enable "block while dwelling" flag when Malyan firmware is detected since that firmware seems to handle `G4` identically to Repetier Firmware instead of Marlin (like it claims to). See also [#1762](https://github.com/foosel/OctoPrint/issues/1762).
+ * [#1946](https://github.com/foosel/OctoPrint/issues/1946) - Add option to disable position logging on cancel/pause. See "Log position on cancel" and "Log position on pause" under Settings > Serial > Advanced options.
+ * [#1971](https://github.com/foosel/OctoPrint/issues/1971) - Refactored temperature inputs. They now sport some fancy +/- buttons to increment/decrement the current temperature (which also auto submit after a couple of seconds) and easier editing by keyboard. The temperature offset was also slightly redesigned to make room for that.
+ * [#1975](https://github.com/foosel/OctoPrint/issues/1975) - Better error reporting when deleting timelapses.
+ * [#2010](https://github.com/foosel/OctoPrint/pull/2010) - Slight refactoring in the terminal tab: Full width input field, auto focus of input field when just clicking on terminal output.
+ * [#2011](https://github.com/foosel/OctoPrint/issues/2011) - Centralized online connectivity check (with opt-in of course). None of the bundled plugins will attempt to fetch data from the net when the connectivity check indicates that would fail anyhow. This should improve server startup times and various requests when running isolated.
+ * [#2025](https://github.com/foosel/OctoPrint/issues/2025) - More verbose logging of asynchronous system commands (e.g. restart/shutdown).
+ * Allow timelapse configuration through UI even when not connected to the printer (suggested in [#1918](https://github.com/foosel/OctoPrint/issues/1918))
+ * Disable "Upload to SD" UI elements while printing (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914))
+ * Update bundled SockJS to 1.1.2 incl. source maps
+ * Set `X-Robots` HTTP header and remove `Server` header from all responses, also set `robots` meta tag in page.
+ * Don't require to enter programmer mode for printer port autodetection when there's only one possible port candidate anyhow.
+ * More sensible sorting of baudrates (additionally configured, then 115200, then 250000, then everything else).
+ * Don't show "Unhandled communication error" on autodetection failure.
+ * Make timeout after which to unload the webcam stream after navigating away from it configurable (as suggested in [#1937](https://github.com/foosel/OctoPrint/issues/1937))
+ * Add `ToolChange` event and tool change GCODE scripts
+ * Support parsing GCODE subcodes.
+ * Add `octoprint.users.factory` hook, allowing plugins to extend/swap out the user manager OctoPrint uses.
+ * Corewizard: Disable view model and client code if it's not actually required.
+ * Corewizard: Disable injection of JS files into UI when it's not actually required.
+ * GCODE analysis: Moved into its own subprocess. That should improve performance on multi core systems.
+ * GCODE viewer: Ignore coordinates outside bed when zooming/centering on model. Those usually are nozzle priming routines.
+ * JS Client Lib: Add centralized browser detection as `OctoPrint.coreui.browser`. Available properties: `chrome`, `firefox`, `safari`, `ie`, `edge`, `opera` as well as `mobile` and `desktop`, all of which are boolean values.
+ * Plugin Manager plugin: Detect if a plugin requires a reconnect to the printer to become fully active/inactive.
+ * Software Update plugin: Force exact version when updating OctoPrint and tracking releases.
+ * Software Update plugin: "Devel RCs" release channel now also tracks maintenance RCs. That way people don't have to toggle between the two any more to get *all* RCs.
+ * Software Update plugin: `bitbucket_commit` check type now supports API credentials (see also [#1993](https://github.com/foosel/OctoPrint/pull/1993)).
+ * Wizard: Allow suppressing the "the settings got updated" dialog through subwizards, in case they need to update settings asynchronously as part of their workflow.
+ * More resilience against expected folders being files.
+ * More resilience against a wrong user manager class being configured.
+ * Some code refactoring & cleanup.
+ * Some HTML & CSS improvements.
+
+### Bug fixes
+
+ * [#1916](https://github.com/foosel/OctoPrint/issues/1916) - Fix webcam not loading if first/initial tab is "Control"
+ * [#1924](https://github.com/foosel/OctoPrint/issues/1924) - Filter out source map links from bundled JS webassets.
+ * [#1943](https://github.com/foosel/OctoPrint/issues/1943) - Fix issue causing unnecessary creation of default printer profile on startup
+ * [#1946](https://github.com/foosel/OctoPrint/issues/1946) - Decouple writing of print log from everything else. Fixes delay in cancel processing.
+ * [#1963](https://github.com/foosel/OctoPrint/issues/1963) & [#1974](https://github.com/foosel/OctoPrint/issues/1974) - Allow empty & custom size in print job events. Also fixes an issue with timelapses when printing from SD on printers that require the GPX plugin to work.
+ * [#1996](https://github.com/foosel/OctoPrint/issues/1996) - Support all line ending variantes in the GCODE viewer. Solves an issue with GCODE generated for Prusa's multi material extruder since that uses only `\r` for some reason.
+ * [#2007](https://github.com/foosel/OctoPrint/issues/2007) - Fix issue parsing temperature lines from the printer that contain negative values.
+ * [#2012](https://github.com/foosel/OctoPrint/issues/2012) - Fix command line interface of Software Update plugin.
+ * [#2017](https://github.com/foosel/OctoPrint/issues/2017) - Fix issue in GCODE viewer with files that contain a visit to the first layer twice (e.g. brim, then nose dive from higher z for actual model), causing all but the last layer segment to not be rendered.
+ * [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab: Fix for legend in graph not updating with current values on mouse over.
+ * [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab: Fix for new temperature inputs not fitting on one line in Firefox.
+ * [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab & GCODE viewer: Fix for available tools (and offsets) not properly updating on change of printer profile.
+ * [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Wizard: Fix sorting of required wizards not properly handling non-ASCII unicode.
+ * [#2035](https://github.com/foosel/OctoPrint/issues/2035) (regression) - Fix an issue of the server not starting up if there's a file in the analysis backlog. The reason for this is that spawning a new process while the intermediary server is active causes the server port to be blocked (this is due to how subprocessing works by default), in turn leading to an error on startup since the port cannot be bound by the actual server. Since the GCODE analysis takes now place in its own subprocess and hence triggers this problem, it had to be moved until after the actual server has already started up to avoid this problem.
+ * [#2059](https://github.com/foosel/OctoPrint/issues/2059) (regression) - Fix an issue causing the new temperature controls to wrap on touch enabled devices when the temperature dropdown is opened.
+ * [#2090](https://github.com/foosel/OctoPrint/issues/2090) (regression) - Fix an issue causing an aborted server startup under Windows if the timing is just right.
+ * [#2135](https://github.com/foosel/OctoPrint/issues/2135) (regression) - Fix an issue causing import errors inside the GCODE analysis tool in certain environments due to `sys.path` entries causing relative imports.
+ * [#2136](https://github.com/foosel/OctoPrint/issues/2136) (regression) - Fix wrong minimum version for `sockjs-tornado` dependency.
+ * [#2137](https://github.com/foosel/OctoPrint/issues/2137) (regression) - Fix issue with session cookies getting lost when running an OctoPrint instance on a subpath of another (e.g. `octopi.local/` and `octopi.local/octoprint2`).
+ * [#2140](https://github.com/foosel/OctoPrint/issues/2140) (regression) - Fix issue with locale dependent sorting of sub wizards during first time setup causing issues leading to the wizard not being able to complete.
+ * Fix various popup buttons allowing multiple clicks (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914))
+ * Software Update Plugin: Perform server restart asynchronously. Should reduce restart times on updates significantly.
+ * Don't hex-escape `\t`, `\r` or `\n` in terminal output
+ * Use client side default printer profile if the default profile could not be found on the server
+ * Use both "to" and "from" coordinates of a given move for min/max model coordinate calculation in GCODE analysis. Otherwise wrong values could be calculated under certain circumstances.
+ * Fix potential race condition in resend request handling.
+ * Fix potential race condition in web socket handling.
+ * Fix handling of tool offsets in GCODE analysis - diverted too far from firmware implementations, causing wrong calculations.
+ * Fix `FileAdded`, `FileRemoved`, `FolderAdded`, `FolderRemoved` events not being fired with the correct event name.
+ * Fix potential division by zero in progress reporting if the timing was just right.
+ * Fix sorting order for multiple tools in the "State" panel.
+ * Fix file position vs. line ending handling in GCODE viewer. Could lead to slightly off file position calculation and hence possibly to the wrong move being plotted when synchronizing with print progress.
+ * Wizard: Fix `onWizardPreventSettingsRefreshDialog` callback invocation. (regression)
+ * Corewizard plugin: Fix `firstrunonly` wizards (e.g. for printer profile configuration) being displayed again if _any_ of the sub wizards (e.g. for the online check opt-in and configuration) is active. (regression)
+ * Fix an issue causing rollover of `serial.log` to fail under Windows. (regression)
+
+### More Information
+
+ * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.4...1.3.5)
+ * Release Candidates:
+ * [1.3.5rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc1)
+ * [1.3.5rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc2)
+ * [1.3.5rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc3)
+ * [1.3.5rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc4)
+ * A special **Thank you!** to everyone who reported back on these release candidates this time: [alexxy](https://github.com/alexxy), [andrivet](https://github.com/andrivet), [b-morgan](https://github.com/b-morgan), [BillyBlaze](https://github.com/BillyBlaze), [CapnBry](https://github.com/CapnBry), [chippypilot](https://github.com/chippypilot), [ctgreybeard](https://github.com/ctgreybeard), [cxt666](https://github.com/cxt666), [DaSTIG](https://github.com/DaSTIG), [fhbmax](https://github.com/fhbmax), [fiveangle](https://github.com/fiveangle), [goeland86](https://github.com/goeland86), [JohnOCFII](https://github.com/JohnOCFII), [Kunsi](https://github.com/Kunsi), [mgrl](https://github.com/mgrl), [MoonshineSG](https://github.com/MoonshineSG), [nate-ubiquisoft](https://github.com/nate-ubiquisoft), [Neoolog](https://github.com/Neoolog), [ntoff](https://github.com/ntoff), [oferfrid](https://github.com/oferfrid), [roygilby](https://github.com/roygilby), [SAinc](https://github.com/SAinc), [sbts](https://github.com/sbts), [thess](https://github.com/thess), [tkurbad](https://github.com/tkurbad), [tsillini](https://github.com/tsillini) and [TylonHH](https://github.com/TylonHH).
+
## 1.3.4 (2017-06-01)
### Note for owners of Malyan M200/Monoprice Select Mini
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index b8ba81c03..861215f4d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -21,45 +21,41 @@ or **[creating pull requests](#pull-requests)**.
## Issues, Tickets, however you may call them
-Please read the following short instructions fully and follow them. You can
+Please read the following instructions fully and follow them. You can
help the project tremendously this way: not only do you help the maintainers
to **address problems in a timely manner** but also keep it possible for them
to **fix bugs, add new and improve on existing functionality** instead of doing
nothing but ticket management.
-
+
-- **[Read the FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)**
+- **[Read the FAQ](https://faq.octoprint.org)**
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
and *[use the provided template](#what-should-i-include-in-a-ticket)*.
You do not need to do anything else with your ticket.
- If you want to post a **feature request** or a **documentation request**, add `[Request]`
to your issue's title (e.g. `[Request] Awesome new feature`). A question on how to run/change/setup
something is **not** what qualifies as a request here, use the
- [Mailinglist](https://groups.google.com/group/octoprint) or the
- [Google+ Community](https://plus.google.com/communities/102771308349328485741) for
+ [community forum at discourse.octoprint.org](https://discourse.octoprint.org) for
such support issues.
- If you are a **developer** that wants to brainstorm a pull request or possible
changes to the plugin system, add [Brainstorming] to your issue's title (e.g.
`[Brainstorming] New plugin hook for doing some cool stuff`).
- If you need **support**, have a **question** or some **other reason** that
doesn't fit any of the above categories, the issue tracker is not the right place.
- Consult the [Mailinglist](https://groups.google.com/group/octoprint) or the
- [Google+ Community](https://plus.google.com/communities/102771308349328485741) instead.
+ Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org) instead.
No matter what kind of ticket you create, never mix two or more "ticket reasons"
into one ticket: One ticket per bug, request, brainstorming thread please.
-----
-
-**Note**: A bot is in place that monitors new tickets, automatically
-categorizes them and checks new bug reports for usage of the provided template.
-That bot will only bother you if you open a ticket that appears to be a bug (no
-`[Request]` or `[Brainstorming]` in the title) without the template, and it
-will do that only to ensure that all information needed to solve the issue is
-available for the maintainers to directly start tackling that problem.
-
-----
+> 👉 **Note**
+>
+> A bot is in place that monitors new tickets, automatically
+> categorizes them and checks new bug reports for usage of the provided template.
+> That bot will only bother you if you open a ticket that appears to be a bug (no
+> `[Request]` or `[Brainstorming]` in the title) without the complete template, and it
+> will do that only to ensure that all information needed to solve the issue is
+> available for the maintainers to directly start tackling that problem.
## How to file a bug report
@@ -72,22 +68,25 @@ following section *completely* and also follow the instructions in the
### What should I do before submitting a bug report?
-1. **Make sure you are at the right location**. This is the Github repository
+1. **Make sure you are at the right location**. This is the bug tracker
of the official version of OctoPrint, which is the 3D print server and
corresponding web interface itself.
-
- **This is not the Github respository of OctoPi**, which is the preconfigured
+
+ **OctoPrint doesn't manage your network connection or your webcam nor
+ can it fix your printer not getting detected as a serial interface** -
+ if you have any kinds of problems with that, get in touch on the
+ [community forum](https://discourse.octoprint.org).
+
+ **This is not the bug tracker of OctoPi**, which is the preconfigured
Raspberry Pi image including OctoPrint among other things - that one can be found
- [here](https://github.com/guysoft/OctoPi). Please note that while we do have
- some entries regarding OctoPi in the FAQ, any bugs should be reported in the
- [proper bug tracker](https://github.com/guysoft/OctoPi/issues) which - again -
- is not here.
+ [here](https://github.com/guysoft/OctoPi). If you have any kind of specific
+ issue with how the OctoPi system is setup, go there please.
- **This is also not the Github repository of any OctoPrint Plugins you
+ **This is also not the bug tracker of any OctoPrint Plugins you
might have installed**. Report any issues with those in their corresponding
bug tracker (probably linked to from the plugin's homepage).
- Finally, **this is also not the right issue tracker if you are running a
+ Finally, **this is also not the right bug tracker if you are running a
forked version of OctoPrint**. Seek help for such unofficial versions from
the people maintaining them instead.
@@ -101,7 +100,7 @@ following section *completely* and also follow the instructions in the
more about safe mode in the [docs](http://docs.octoprint.org/en/master/features/safemode.html).
You might also want to try the current development version of OctoPrint
- (if you aren't already). Refer to the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)
+ (if you aren't already). Refer to the [FAQ](https://faq.octoprint.org)
for information on how to do this.
3. The problem still exists? Then please **look through the
@@ -111,8 +110,8 @@ following section *completely* and also follow the instructions in the
Sorting through duplicates of the same issue sometimes causes more work than
fixing it. Take the time to filter through possible duplicates and be really
sure that your problem definitely is a new one. Try more than one search query
- (e.g. do not only search for "webcam" if you happen to run into an issue
- with your webcam, also search for "timelapse" etc). Do not only read the subject lines
+ (e.g. do not only search for "timelapse" if you happen to run into an issue
+ with your webcam, also search for "recording" etc). Do not only read the subject lines
of tickets that look like they might be related, but also read the ticket itself!
**Very important:** Please make absolutely sure that if you find a bug that looks like
@@ -126,84 +125,149 @@ following section *completely* and also follow the instructions in the
makes it more difficult due to on top of having to figure out the original problem
there's now also a [red herring](https://en.wikipedia.org/wiki/Red_herring) interfering - so please be
very diligent here!
-
+
+If in doubt about any of the above - get in touch on the [community forum](https://discourse.octoprint.org)
+instead of opening a ticket here. If you are actually running into a bug, we'll figure it out together
+there.
+
### What should I include in a bug report?
First of all make sure your use **a descriptive title**. "It doesn't work"
and similar unspecific complaints are NOT descriptive titles.
-**Always use the following template** (please remove what's within `[...]`, that's
-only provided here as some additional information for you), **even if only adding a
-"me too" to an existing ticket**:
+**Always use the following template, even if only adding a "me too" to an
+existing ticket**:
- #### What were you doing?
+```
+
- #### Branch & Commit or Version of OctoPrint
+#### What were you doing?
- [Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.]
+
- [OctoPi, Linux, Windows, MacOS, something else? With version please,
- OctoPi's version can be found in /etc/octopi_version]
+1. ...
+2. ...
+3. ...
- #### Printer model & used firmware incl. version
+
- [If applicable, always include if unsure.]
+#### What did you expect to happen?
- #### Browser and Version of Browser, Operating System running Browser
+#### What happened instead?
- [If applicable, always include if unsure.]
+#### Did the same happen when running OctoPrint in safe mode?
- #### Link to octoprint.log
+
- [On gist.github.com or pastebin.com. If applicable, always include if unsure or
- reporting communication issues. Never truncate.
+#### Version of OctoPrint
- serial.log is usually not written due to performance reasons and must be
- enabled explicitly. Provide at the very least the FULL contents of your
- terminal tab at the time of the bug occurrence, even if you do not have
- a serial.log.]
+
- #### Link to contents of Javascript console in the browser
+#### Operating System running OctoPrint
- [On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
- always include if unsure or reporting UI issues.
+
- The Contribution Guidelines tell you where to find that.]
+#### Printer model & used firmware incl. version
- #### Screenshot(s)/video(s) showing the problem:
+
- [If applicable. Always include if unsure or reporting UI issues.]
+#### Browser and version of browser, operating system running browser
- I have read the FAQ.
+
+
+#### Link to octoprint.log
+
+
+
+#### Link to contents of terminal tab or serial.log
+
+
+
+#### Link to contents of Javascript console in the browser
+
+
+
+#### Screenshot(s)/video(s) showing the problem:
+
+
+
+I have read the FAQ.
+```
Copy-paste this template **completely** (or use the version that gets pre-filled
into the "new issue" form). Do not skip any lines or the bot *will* complain! Provide
@@ -211,50 +275,11 @@ all requested information or your ticket will be closed.
### Where can I find which version and branch I'm on?
-You can find out all of them by taking a look into the lower left corner of the
-OctoPrint UI:
-
-
-
-If you don't have access to the UI you can find out that information via the
-command line as well. Either `octoprint --version` or `python setup.py version`
-in OctoPrint's folder will tell you the version of OctoPrint you are running
-(note: if it doesn't then you are running a version older than 1.1.0,
-*upgrade now*). A `git branch` in your OctoPrint installation folder will mark
-the branch you are on with a little *. `git rev-parse HEAD` will tell you the
-current commit.
+Please refer to [this FAQ entry](https://discourse.octoprint.org/t/how-can-i-find-out-the-version-of-octoprint-or-octopi-i-am-running/204/1).
### Where can I find those log files you keep talking about?
-OctoPrint by default provides two log outputs, a third one can be enabled if
-more information is needed.
-
-One is contained in the **"Terminal" tab** within OctoPrint's UI and is a log
-of the last 300 lines of communication with the printer. Please copy-paste
-this *completely* somewhere (disable auto scroll to make copying the contents easier) -
-e.g. http://pastebin.com or http://gist.github.com - and include a link in
-your bug report.
-
-There is also **OctoPrint's application log file** or in short `octoprint.log`,
-which is by default located at `~/.octoprint/logs/octoprint.log` on Linux,
-`%APPDATA%\OctoPrint\logs\octoprint.log` on Windows and
-`~/Library/Application Support/OctoPrint/logs/octoprint.log` on MacOS. You can
-also access it directly through OctoPrint via Settings > Logs. Please
-copy-paste this *completely* to pastebin or gist as well and include a link in your bug
-report.
-
-It might happen that you are asked to provide a more **thorough log of the
-communication with the printer** if you haven't already done so, the `serial.log`.
-This is not written by default due to performance reasons, but you can enable
-it in the settings dialog. After enabling that log, please reproduce the problem
-again (connect to the printer, do whatever triggers it), then copy-paste
-`~/.octoprint/logs/serial.log` (Windows: `%APPDATA%\OctoPrint\logs\serial.log`,
-MacOS: `~/Library/Application Support/OctoPrint/logs/serial.log`) to pastebin
-or gist and include the link in the bug report.
-
-You might also be asked to provide a log with an increased log level. You can
-find information on how to do just that in the
-[docs](http://docs.octoprint.org/en/master/configuration/logging_yaml.html).
+Please refer to [this FAQ entry](https://discourse.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299/1).
### Where can I find my browser's error console?
@@ -263,6 +288,8 @@ See [How to open the Javascript Console in different browsers](https://webmaster
## Setting up a development environment
See [the corresponding chapter in the documentation](http://docs.octoprint.org/en/master/development/index.html#setting-up-a-development-environment).
+This also includes information on how to run the test suite and how to build
+the documentation.
## Pull requests
@@ -303,7 +330,17 @@ See [the corresponding chapter in the documentation](http://docs.octoprint.org/e
* Make sure you do not add dead code (e.g. commented out left-overs
from experiments).
8. Ensure your changes **pass the existing unit tests**. PRs that break
- those cannot be accepted.
+ those cannot be accepted. You can run the unit tests locally (after
+ [initial development environment setup with "develop" dependencies](http://docs.octoprint.org/en/master/development/index.html#setting-up-a-development-environment))
+ by running
+
+ ```
+ nosetests --with-doctest
+ ```
+
+ in the OctoPrint checkout folder. A [travis build](https://travis-ci.org/foosel/OctoPrint)
+ is also setup so that if the tests should fail, your PR will be marked
+ accordingly.
9. **Test your changes thoroughly**. That also means testing with usage
scenarios you don't normally use, e.g. if you only use access control, test
without and vice versa. If you only test with your printer, test with the
@@ -432,6 +469,10 @@ the local version identifier to allow for an exact determination of the active c
* 2017-03-10: Reproduce bugs in safe mode to make sure they are really caused
by OctoPrint itself and not a misbehaving plugin.
* 2017-03-27: Added safe mode section to ticket template.
+ * 2017-11-22: Added note on how to run the unit tests
+ * 2018-03-15: Link to new community forum and some clarifications re bug
+ reporting
+ * 2018-03-29: "Where to find version numbers" is now located on the FAQ
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
diff --git a/LICENSE b/LICENSE.txt
similarity index 100%
rename from LICENSE
rename to LICENSE.txt
diff --git a/README.md b/README.md
index 817884a57..b44dfe19e 100644
--- a/README.md
+++ b/README.md
@@ -5,31 +5,35 @@
OctoPrint provides a snappy web interface for controlling consumer 3D printers. 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).
+Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme).
+
+The community forum is available at [discourse.octoprint.org](https://discourse.octoprint.org/?utm_source=github&utm_medium=readme).
+
+The FAQ can be accessed by following [faq.octoprint.org](https://faq.octoprint.org/?utm_source=github&utm_medium=readme).
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).
+The official plugin repository can be reached at [plugins.octoprint.org](https://plugins.octoprint.org/?utm_source=github&utm_medium=readme).
-OctoPrint's development wouldn't be possible without the [financial support by its community](http://octoprint.org/support-octoprint/).
-If you enjoy OctoPrint, please consider becoming a regular supporter!
+**OctoPrint's development wouldn't be possible without the [financial support by its community](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
+If you enjoy OctoPrint, please consider becoming a regular supporter!**

You are currently looking at the source code repository of OctoPrint. If you already installed it
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki)
-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
+might be of more interest for you. You might also want to subscribe to join
+[the community forum at discourse.octoprint.org](https://discourse.octoprint.org) where there are other active users who might be
able to help you with any questions you might have.
## Contributing
Contributions of all kinds are welcome, not only in the form of code but also with regards to the
-[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), 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) and also [financially](http://octoprint.org/support-octoprint/).
+[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), debugging help
+in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on
+[the community forum at discourse.octoprint.org](https://discourse.octoprint.org)
+and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
If you think something is bad 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
@@ -54,23 +58,20 @@ you already have Python 2.7, pip and virtualenv set up on your system:
1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git`
2. Change into the OctoPrint folder: `cd OctoPrint`
3. Create a user-owned virtual environment therein: `virtualenv venv`
-4. Install OctoPrint *into that virtual environment*: `./venv/bin/python setup.py install`
+4. Install OctoPrint *into that virtual environment*: `./venv/bin/pip 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.
+access control as necessary.
## Dependencies
OctoPrint depends on a few python modules to do its job. Those are automatically installed when installing
-OctoPrint via `setup.py`:
+OctoPrint via `pip`:
- python setup.py install
+ pip install .
You should do this every time after pulling from the repository, since the dependencies may have changed.
@@ -78,9 +79,9 @@ OctoPrint currently only supports Python 2.7.
## Usage
-Running the `setup.py` script via
+Running the pip install via
- python setup.py install
+ pip 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 in your `PATH` or not). The
diff --git a/SUPPORTERS.md b/SUPPORTERS.md
index 2909b8101..6159d8f79 100644
--- a/SUPPORTERS.md
+++ b/SUPPORTERS.md
@@ -6,63 +6,53 @@ thanks to everyone who contributed!
## Patreon Patrons
- * 3D Moniak
- * Aleph Objects, Inc.
* Andrew Moorby
* Arnljot Arntsen
- * BEEVERYCREATIVE
* Boris Hussein
* Brad Jackson
* Brian E. Tyler
- * Chris Day
* Christian Petropolis
- * CreativeTools
+ * COLLE+McVOY
* D Brian Kimmel
* DeltaMaker 3D Printers
- * Doug Johnson
* E3D BigBox
* Ernesto Martinez
- * Exovite
* F. Kunsmann
* Frank Sander
* Gary Deen
- * Gary N McKinney
- * George Robles
* günter weber
- * Ivan Krasin
* James Seigel
- * Jamie R McGuigan
* Jeff Moe
+ * Jeff Renfer
+ * Jefferson Hunt
+ * Jeremiah Avery
* Josh Daniels
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
- * Lamin Kivelä
+ * Kodama Inc.
+ * LulzBot®
* Makespace Madrid
- * Marcus Ackermann
- * Mark Qvist
* Mark Walker
- * Masayoshi Mitsui
+ * Martin Beattie
* Michael Aumock
* Miles Flavel
+ * mitchell hirsch
* Mohammed khorakiwala
* Noe Ruiz
* Patrick McGinnis
- * Peter Grace
* Peter Schmehl
- * PRINT3Dforum.com
+ * Randy C. Will
* Robert Gusek
* Roger Strolz
* Roy Cortes
* Samer Najia
- * SD3D
- * SeeMeCNC
* Simon Hallam
* Stefan Krister
* Stephane Schittly
* Sven Mueller
+ * Symbiotic Devices
* Thomas Hatley
- * Timeshell.ca
* Trent Shumay
-and 1098 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
\ No newline at end of file
+and 1233 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
\ No newline at end of file
diff --git a/THIRDPARTYLICENSES.md b/THIRDPARTYLICENSES.md
index 30cc98a82..6cc67867c 100644
--- a/THIRDPARTYLICENSES.md
+++ b/THIRDPARTYLICENSES.md
@@ -6,7 +6,7 @@
* [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 Knockout Binding](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
@@ -36,6 +36,8 @@
* [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3
* [chainmap](https://bitbucket.org/jeunice/chainmap): Python
* [Click](http://click.pocoo.org/): BSD
+ * [dateutil](https://dateutil.readthedocs.io/): BSD
+ * [emoji](https://github.com/carpedm20/emoji/): BSD
* [feedparser](https://github.com/kurtmckee/feedparser): BSD
* [Flask](http://flask.pocoo.org/): BSD
* [Flask-Assets](http://github.com/miracle2k/flask-assets): BSD
@@ -44,6 +46,8 @@
* [Flask-Markdown](http://github.com/dcolish/flask-markdown): BSD
* [Flask-Principal](http://packages.python.org/Flask-Principal/): MIT
* [future](https://python-future.org/): MIT
+ * [futures](https://github.com/agronholm/pythonfutures): Python
+ * [monotonic](https://github.com/atdt/monotonic): Apache License 2.0
* [netaddr](https://github.com/drkjam/netaddr/): BSD
* [netifaces](https://bitbucket.org/al45tair/netifaces): MIT
* [pkginfo](http://pypi.python.org/pypi/pkginfo/): Python
@@ -60,13 +64,14 @@
* [Tornado](http://www.tornadoweb.org/): Apache License 2.0
* [watchdog](http://github.com/gorakhargosh/watchdog): Apache License 2.0
* [websocket-client](https://github.com/liris/websocket-client): LGPLv3
+ * [wrapt](http://wrapt.readthedocs.org/): BSD
## Development (testing, documentation generation, etc)
* [ddt](https://github.com/txels/ddt): MIT
* [mock](https://github.com/testing-cabal/mock): BSD
* [nose](http://pythonhosted.org/nose/): LGPL
- * [pypandoc](https://github.com/bebraw/pypandoc): MIT
* [Sphinx](http://sphinx-doc.org/): BSD
* [sphinxcontrib-httpdomain](https://bitbucket.org/birkenfeld/sphinx-contrib/src/default/httpdomain/): BSD
+ * [sphinxcontrib-mermad](https://github.com/mgaitan/sphinxcontrib-mermaid): BSD
* [sphinx_rtd_theme](https://github.com/snide/sphinx_rtd_theme/): BSD
diff --git a/docs/_static/theme_overrides.css b/docs/_static/theme_overrides.css
index 864a02766..cce327b20 100644
--- a/docs/_static/theme_overrides.css
+++ b/docs/_static/theme_overrides.css
@@ -37,6 +37,11 @@
vertical-align: 10%;
}
+.rst-content .highlight>pre,
+.rst-content .linenodiv>pre {
+ line-height: 1.5;
+}
+
/* make code tags non-red again */
code,
.rst-content tt {
@@ -52,3 +57,4 @@ a:visited code,
.rst-content a:visited tt {
color: #9B59B6 !important;
}
+
diff --git a/docs/api/connection.rst b/docs/api/connection.rst
index c0bc75377..721e92cac 100644
--- a/docs/api/connection.rst
+++ b/docs/api/connection.rst
@@ -39,7 +39,7 @@ Get connection settings
"options": {
"ports": ["/dev/ttyACM0", "VIRTUAL"],
"baudrates": [250000, 230400, 115200, 57600, 38400, 19200, 9600],
- "printerProfiles": [{"name": "Default", id: "_default"}],
+ "printerProfiles": [{"name": "Default", "id": "_default"}],
"portPreference": "/dev/ttyACM0",
"baudratePreference": 250000,
"printerProfilePreference": "_default",
diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst
index 768e420b0..a55554e9e 100644
--- a/docs/api/datamodel.rst
+++ b/docs/api/datamodel.rst
@@ -44,6 +44,14 @@ Printer State
- 1
- Boolean
- ``true`` if the printer is currently printing, ``false`` otherwise
+ * - ``flags.pausing``
+ - 1
+ - Boolean
+ - ``true`` if the printer is currently printing and in the process of pausing, ``false`` otherwise
+ * - ``flags.cancelling``
+ - 1
+ - Boolean
+ - ``true`` if the printer is currently printing and in the process of pausing, ``false`` otherwise
* - ``flags.sdReady``
- 1
- Boolean
@@ -232,12 +240,18 @@ File information
* - ``name``
- 1
- String
- - The name of the file without path. E.g. "file.gco" for a file "file.gco" located anywhere in the file system.
+ - The name of the file without path. E.g. "file.gco" for a file "file.gco" located anywhere in the file system. Currently
+ this will always fit into ASCII.
+ * - ``display``
+ - 1
+ - String
+ - The name of the file without the path, this time potentially with non-ASCII unicode characters.
+ E.g. "a turtle 🐢.gco" for a file "a_turtle_turtle.gco" located anywhere in the file system.
* - ``path``
- 1
- String
- The path to the file within the location. E.g. "folder/subfolder/file.gco" for a file "file.gco" located within
- "folder" and "subfolder" relative to the root of the location.
+ "folder" and "subfolder" relative to the root of the location. Currently this will always fit into ASCII.
* - ``type``
- 1
- String
@@ -249,8 +263,11 @@ File information
- Path to type of file in extension tree. E.g. ``["model", "stl"]`` for ``.stl`` files, or ``["machinecode", "gcode"]``
for ``.gcode`` files. ``["folder"]`` for folders.
-Additional properties depend on ``type``. For a ``type`` value of ``folder``, see "Folders". For any other value
-see "Files".
+Additional properties depend on ``type``.
+For a ``type`` value of ``folder``, see :ref:`Folders `.
+For any other value see :ref:`Files `.
+
+.. _sec-api-datamodel-files-folders:
Folders
'''''''
@@ -266,13 +283,14 @@ Folders
* - ``children``
- 0..*
- Array of :ref:`File information items `
- - Contained children for entries of type ``folder``. Will only include children in subfolders in recursive
- listings. Not present in non recursive listings, this might be revisited in the future.
+ - Contained children for entries of type ``folder``. On non recursive listings only present on first level
+ sub folders!
* - ``size``
- 0..1
- Number
- - The size of all files contained in the folder and its subfolders. Not present in non recursive listings, this might
- be revisited in the future.
+ - The size of all files contained in the folder and its subfolders. Not present in non recursive listings!
+
+.. _sec-api-datamodel-files-files:
Files
'''''
@@ -329,11 +347,17 @@ Abridged file or folder information
- 1
- String
- The name of the file or folder without path. E.g. "file.gco" for a file "file.gco" located anywhere in the file system.
+ Currently this will always fit into ASCII.
+ * - ``display``
+ - 1
+ - String
+ - The name of the file without the path, this potentially with non-ASCII unicode characters.
+ E.g. "a turtle 🐢.gco" for a file "a_turtle_turtle.gco" located anywhere in the file system.
* - ``path``
- 1
- String
- The path to the file or folder within the location. E.g. "folder/subfolder/file.gco" for a file "file.gco" located within
- "folder" and "subfolder" relative to the root of the location.
+ "folder" and "subfolder" relative to the root of the location. Currently this will always fit into ASCII.
* - ``origin``
- 1
- String, either ``local`` or ``sdcard``
@@ -365,14 +389,58 @@ GCODE analysis information
- 0..1
- Object
- The estimated usage of filament
- * - ``filament.length``
+ * - ``filament.tool{n}.length``
- 0..1
- Integer
- The length of filament used, in mm
- * - ``filament.volume``
+ * - ``filament.tool{n}.volume``
- 0..1
- Float
- The volume of filament used, in cm³
+ * - ``dimensions``
+ - 0..1
+ - Object
+ - Information regarding the size of the printed model
+ * - ``dimensions.depth``
+ - 0..1
+ - Float
+ - The depth of the printed model, in mm
+ * - ``dimensions.height``
+ - 0..1
+ - Float
+ - The height of the printed model, in mm
+ * - ``dimensions.width``
+ - 0..1
+ - Float
+ - The width of the printed model, in mm
+ * - ``printingArea``
+ - 0..1
+ - Object
+ - Information regarding the size of the printing area
+ * - ``printingArea.maxX``
+ - 0..1
+ - Float
+ - The maximum X coordinate of the printed model, in mm
+ * - ``printingArea.maxY``
+ - 0..1
+ - Float
+ - The maximum Y coordinate of the printed model, in mm
+ * - ``printingArea.maxZ``
+ - 0..1
+ - Float
+ - The maximum Z coordinate of the printed model, in mm
+ * - ``printingArea.minX``
+ - 0..1
+ - Float
+ - The minimum X coordinate of the printed model, in mm
+ * - ``printingArea.minY``
+ - 0..1
+ - Float
+ - The minimum Y coordinate of the printed model, in mm
+ * - ``printingArea.minZ``
+ - 0..1
+ - Float
+ - The minimum Z coordinate of the printed model, in mm
.. _sec-api-datamodel-files-ref:
@@ -401,4 +469,3 @@ References
- URL
- The model from which this file was generated (e.g. an STL, currently not used). Never present for
folders.
-
diff --git a/docs/api/files.rst b/docs/api/files.rst
index 76b80132e..23583d59c 100644
--- a/docs/api/files.rst
+++ b/docs/api/files.rst
@@ -82,8 +82,37 @@ Retrieve all files
"path": "folderA",
"type": "folder",
"typePath": ["folder"],
- "children": [],
- "size": 1334
+ "children": [
+ {
+ "name": "whistle_v2_copy.gcode",
+ "path": "whistle_v2_copy.gcode",
+ "type": "machinecode",
+ "typePath": ["machinecode", "gcode"],
+ "hash": "...",
+ "size": 1468987,
+ "date": 1378847754,
+ "origin": "local",
+ "refs": {
+ "resource": "http://example.com/api/files/local/folderA/whistle_v2_copy.gcode",
+ "download": "http://example.com/downloads/files/local/folderA/whistle_v2_copy.gcode"
+ },
+ "gcodeAnalysis": {
+ "estimatedPrintTime": 1188,
+ "filament": {
+ "length": 810,
+ "volume": 5.36
+ }
+ },
+ "print": {
+ "failure": 4,
+ "success": 23,
+ "last": {
+ "date": 1387144346,
+ "success": true
+ }
+ }
+ }
+ ]
}
],
"free": "3.2GB"
@@ -192,6 +221,7 @@ Retrieve all files
"refs": {
"resource": "http://example.com/api/files/local/folderA/subfolder",
}
+ }
],
"size": 1334,
"refs": {
@@ -442,7 +472,7 @@ Upload file or create folder
:form select: Whether to select the file directly after upload (``true``) or not (``false``). Optional, defaults
to ``false``. Ignored when creating a folder.
:form print: Whether to start printing the file directly after upload (``true``) or not (``false``). If set, ``select``
- is implicitely ``true`` as well. Optional, defaults to ``false``. Ignored when creating a folder.
+ is implicitly ``true`` as well. Optional, defaults to ``false``. Ignored when creating a folder.
:form userdata: [Optional] An optional string that if specified will be interpreted as JSON and then saved along
with the file as metadata (metadata key ``userdata``). Ignored when creating a folder.
:form foldername: The name of the folder to create. Ignored when uploading a file.
diff --git a/docs/api/general.rst b/docs/api/general.rst
index 91e673571..4232a96c9 100644
--- a/docs/api/general.rst
+++ b/docs/api/general.rst
@@ -12,7 +12,7 @@ Authorization
=============
OctoPrint's API expects an API key to be supplied with each request. This API key can be either the globally
-configured one, a user specific one if "Access Control" is enabled or an ref:`App Session Key `.
+configured one, a user specific one if "Access Control" is enabled or an :ref:`App Session Key `.
Users are able to generate and revoke their custom API key via the "Change password" dialog.
The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
@@ -65,7 +65,7 @@ Please be advised that clients should use the header field variant if at all pos
Content Type
============
-If not otherwise stated OctoPrint's API expects request bodies and issues response bodies as ``Content-Type: application/json``.
+If not otherwise stated, OctoPrint's API expects request bodies and issues response bodies as ``Content-Type: application/json``.
.. _sec-api-general-encoding:
diff --git a/docs/api/job.rst b/docs/api/job.rst
index 5d727228e..338a10ea7 100644
--- a/docs/api/job.rst
+++ b/docs/api/job.rst
@@ -4,6 +4,9 @@
Job operations
**************
+Use these operations to query the currently selected file and start/cancel/restart/pause the
+actual print job.
+
.. contents::
.. _sec-api-jobs-command:
diff --git a/docs/api/languages.rst b/docs/api/languages.rst
index ac7b988f2..ecb83102a 100644
--- a/docs/api/languages.rst
+++ b/docs/api/languages.rst
@@ -39,9 +39,7 @@ Retrieve installed language packs
"_core": {
"identifier": "_core",
"name": "Core",
- "languages": [
- ...
- ]
+ "languages": []
},
"some_plugin": {
"identifier": "some_plugin",
@@ -61,7 +59,6 @@ Retrieve installed language packs
"last_update": 1470859680,
"author": "The italian Transifex Team"
}
- ...
]
}
}
@@ -124,9 +121,7 @@ Delete a language pack
"_core": {
"identifier": "_core",
"name": "Core",
- "languages": [
- ...
- ]
+ "languages": []
},
"some_plugin": {
"identifier": "some_plugin",
@@ -138,8 +133,7 @@ Delete a language pack
"locale_english": "German",
"last_update": 1474574597,
"author": "Gina Häußge"
- },
- ...
+ }
]
}
}
diff --git a/docs/api/logs.rst b/docs/api/logs.rst
index ee1c19561..f357494df 100644
--- a/docs/api/logs.rst
+++ b/docs/api/logs.rst
@@ -4,172 +4,9 @@
Log file management
*******************
-.. note::
+Log file management (and logging configuration) was moved into a bundled plugin in OctoPrint 1.3.7. Refer to
+:ref:`the Logging's plugins API ` for the API documentation.
- All log file management operations require admin rights.
-
-.. contents::
-
-.. _sec-api-logs-list:
-
-Retrieve a list of available log files
-======================================
-
-.. 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.
-
- Returns a :ref:`Logfile Retrieve response `.
-
- **Example**
-
- .. sourcecode:: http
-
- GET /api/logs HTTP/1.1
- Host: example.com
- X-Api-Key: abcdef...
-
- .. sourcecode:: http
-
- HTTP/1.1 200 OK
- Content-Type: application/json
-
- {
- "files" : [
- {
- "date" : 1393158814,
- "name" : "octoprint.log",
- "size" : 43712,
- "refs": {
- "resource": "http://example.com/api/logs/octoprint.log",
- "download": "http://example.com/downloads/logs/octoprint.log"
- }
- },
- {
- "date" : 1392628936,
- "name" : "octoprint.log.2014-02-17",
- "size" : 13205,
- "refs": {
- "resource": "http://example.com/api/logs/octoprint.log.2014-02-17",
- "download": "http://example.com/downloads/logs/octoprint.log.2014-02-17"
- }
- },
- {
- "date" : 1393158814,
- "name" : "serial.log",
- "size" : 1798419,
- "refs": {
- "resource": "http://example.com/api/logs/serial.log",
- "download": "http://example.com/downloads/logs/serial.log"
- }
- }
- ],
- "free": 12237201408
- }
-
- :statuscode 200: No error
- :statuscode 403: If the given API token did not have admin rights associated with it
-
-.. _sec-api-logs-delete:
-
-Delete a specific logfile
-=========================
-
-.. http:delete:: /api/logs/(path:filename)
-
- Delete the selected log file with name `filename`.
-
- Returns a :http:statuscode:`204` after successful deletion.
-
- **Example Request**
-
- .. sourcecode:: http
-
- DELETE /api/logs/octoprint.log.2014-02-17 HTTP/1.1
- Host: example.com
- X-Api-Key: abcdef...
-
- :param filename: The filename of the log file to delete
- :statuscode 204: No error
- :statuscode 403: If the given API token did not have admin rights associated with it
- :statuscode 404: If the file was not found
-
-.. _sec-api-logs-datamodel:
-
-Data model
-==========
-
-.. _sec-api-logs-datamodel-retrieveresponse:
-
-Logfile Retrieve Response
--------------------------
-
-.. list-table::
- :widths: 15 5 10 30
- :header-rows: 1
-
- * - Name
- - Multiplicity
- - Type
- - Description
- * - ``files``
- - 0..*
- - Array of :ref:`File information items `
- - The list of requested files. Might be an empty list if no files are available
- * - ``free``
- - 1
- - String
- - The amount of disk space in bytes available in the local disk space (refers to OctoPrint's ``logs`` folder).
-
-.. _sec-api-logs-datamodel-fileinfo:
-
-File information
-----------------
-
-.. list-table::
- :widths: 15 5 10 30
- :header-rows: 1
-
- * - Name
- - Multiplicity
- - Type
- - Description
- * - ``name``
- - 1
- - String
- - The name of the file
- * - ``size``
- - 1
- - Number
- - The size of the file in bytes.
- * - ``date``
- - 1
- - Unix timestamp
- - The timestamp when this file was last modified.
- * - ``refs``
- - 1
- - :ref:`sec-api-logs-datamodel-ref`
- - References relevant to this file
-
-.. _sec-api-logs-datamodel-ref:
-
-References
-----------
-
-.. list-table::
- :widths: 15 5 10 30
- :header-rows: 1
-
- * - Name
- - Multiplicity
- - Type
- - Description
- * - ``resource``
- - 1
- - URL
- - The resource that represents the file (e.g. for deleting)
- * - ``download``
- - 1
- - URL
- - The download URL for the file
+The former endpoints ``/api/logs`` and ``api/logs/`` are marked as deprecated but still work for now. New
+client implementations should directly use the new endpoints provided by the bundled plugin. Existing implementations
+should adapt their endpoints as soon as possible.
diff --git a/docs/api/printer.rst b/docs/api/printer.rst
index 200f42108..5d7c8ebde 100644
--- a/docs/api/printer.rst
+++ b/docs/api/printer.rst
@@ -37,7 +37,7 @@ Besides that, OctoPrint also provides a :ref:`full state report of the printer <
OctoPrint's internal webserver is single threaded and can only handle one request at a time. This is
not a problem generally since asynchronous programming allows to just have one request which is waiting for
data from a long running backend operation to sleep while handling other requests. The internal framework
- used for providing the REST API though, Flask, is based on WSGI, which is synchrounous in nature. This means
+ used for providing the REST API though, Flask, is based on WSGI, which is synchronous in nature. This means
that it is impossible to wait in a non blocking wait while handling a request on the REST API. So in order to
return the response of a command sent to the printer, the single thread of the webserver would have to be blocked
by the API while the response wasn't available yet. Which in turn would mean that the whole web server would
@@ -149,6 +149,8 @@ Retrieve the current printer state
"operational": true,
"paused": false,
"printing": false,
+ "cancelling": false,
+ "pausing": false,
"sdReady": true,
"error": false,
"ready": true,
@@ -179,6 +181,8 @@ Retrieve the current printer state
"operational": true,
"paused": false,
"printing": false,
+ "cancelling": false,
+ "pausing": false,
"sdReady": true,
"error": false,
"ready": true,
@@ -213,7 +217,7 @@ Issue a print head command
* ``z``: Optional. Amount/coordinate to jog print head on z axis, must be a valid number corresponding to the distance to travel in mm.
* ``absolute``: Optional. Boolean value specifying whether to move relative to current position (provided
axes values are relative amounts) or to absolute position (provided axes values are coordinates)
- * ``speed``: Optiona. Speed at which to move. If not provided, minimum speed for all selected axes from printer
+ * ``speed``: Optional. Speed at which to move. If not provided, minimum speed for all selected axes from printer
profile will be used. If provided but ``false``, no speed parameter will be appended to the command. Otherwise
interpreted as an integer signifying the speed in mm/s, to append to the command.
@@ -223,7 +227,7 @@ Issue a print head command
* ``axes``: A list of axes which to home, valid values are one or more of ``x``, ``y``, ``z``.
feedrate
- Changes the feedrate factor to apply to the movement's of the axes.
+ Changes the feedrate factor to apply to the movements of the axes.
* ``factor``: The new factor, percentage as integer or float (percentage divided by 100) between 50 and 200%.
diff --git a/docs/api/printerprofiles.rst b/docs/api/printerprofiles.rst
index 835399d5c..8db1b51ae 100644
--- a/docs/api/printerprofiles.rst
+++ b/docs/api/printerprofiles.rst
@@ -581,7 +581,7 @@ Profile
* - ``axes``
- 0..1
- Object
- - Description of the printer's axes properties, one entry each for ``x``, ``y``, ``z`` and ``e`` holding maxium speed
+ - Description of the printer's axes properties, one entry each for ``x``, ``y``, ``z`` and ``e`` holding maximum speed
and whether this axis is inverted or not.
* - ``axes.{axis}.speed``
- 0..1
diff --git a/docs/api/settings.rst b/docs/api/settings.rst
index acc797220..c5947c4b5 100644
--- a/docs/api/settings.rst
+++ b/docs/api/settings.rst
@@ -62,10 +62,11 @@ Save settings
{
"api": {
- "enabled": true,
- // ...
+ "enabled": true
},
- // ...
+ "appearance": {
+ "color": "black"
+ }
}
.. _sec-api-settings-generateapikey:
@@ -105,7 +106,7 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
* - ``api.key``
- Only maps to ``api.key`` in ``config.yaml`` if request is sent with admin rights, set to ``n/a`` otherwise.
Starting with OctoPrint 1.3.3 setting this field via :ref:`the API ` is not possible,
- only :ref:`regenerting it ` is supported. Setting a custom value is only
+ only :ref:`regenerating it ` is supported. Setting a custom value is only
possible through `config.yaml`.
* - ``api.allowCrossOrigin``
-
diff --git a/docs/api/slicing.rst b/docs/api/slicing.rst
index 010f1af74..129653171 100644
--- a/docs/api/slicing.rst
+++ b/docs/api/slicing.rst
@@ -58,11 +58,9 @@ List All Slicers and Slicing Profiles
"displayName": "Medium Quality",
"default": true,
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
- },
- ...
+ }
}
- },
- ...
+ }
}
:statuscode 200: No error
@@ -104,8 +102,7 @@ List Slicing Profiles of a Specific Slicer
"displayName": "Medium Quality",
"default": true,
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
- },
- ...
+ }
}
:param slicer: The identifying key of the slicer for which to list the available profiles.
@@ -147,8 +144,7 @@ Retrieve Specific Profile
"brim_line_count": 20,
"cool_head_lift": false,
"cool_min_feedrate": 10.0,
- "cool_min_layer_time": 5.0,
- ...
+ "cool_min_layer_time": 5.0
}
}
diff --git a/docs/api/system.rst b/docs/api/system.rst
index 78ea128ff..b39e0a1ad 100644
--- a/docs/api/system.rst
+++ b/docs/api/system.rst
@@ -39,7 +39,7 @@ List all registered system commands
"action": "shutdown",
"name": "Shutdown",
"command": "sudo shutdown -h now",
- "confirm": "You are about to shutdown the system.",
+ "confirm": "You are about to shutdown the system.
This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"source": "core",
@@ -49,7 +49,7 @@ List all registered system commands
"action": "reboot",
"name": "Reboot",
"command": "sudo reboot",
- "confirm": "You are about to reboot the system.",
+ "confirm": "You are about to reboot the system.
This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"source": "core",
@@ -59,7 +59,7 @@ List all registered system commands
"action": "restart",
"name": "Restart OctoPrint",
"command": "sudo service octoprint restart",
- "confirm": "You are about to restart the OctoPrint server.",
+ "confirm": "You are about to restart the OctoPrint server.
This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"source": "core",
@@ -100,7 +100,7 @@ List all registered system commands for a source
"action": "shutdown",
"name": "Shutdown",
"command": "sudo shutdown -h now",
- "confirm": "You are about to shutdown the system.",
+ "confirm": "You are about to shutdown the system.
This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"source": "core",
@@ -110,7 +110,7 @@ List all registered system commands for a source
"action": "reboot",
"name": "Reboot",
"command": "sudo reboot",
- "confirm": "You are about to reboot the system.",
+ "confirm": "You are about to reboot the system.
This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"source": "core",
@@ -120,7 +120,7 @@ List all registered system commands for a source
"action": "restart",
"name": "Restart OctoPrint",
"command": "sudo service octoprint restart",
- "confirm": "You are about to restart the OctoPrint server.",
+ "confirm": "You are about to restart the OctoPrint server.
This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"source": "core",
@@ -139,7 +139,7 @@ Execute a registered system command
.. http:post:: /api/system/commands/(string:source)/(string:action)
- Execute the system command ``action`` on defined in ``source``.
+ Execute the system command ``action`` defined in ``source``.
**Example**
@@ -154,7 +154,7 @@ Execute a registered system command
.. sourcecode:: http
- 204 No Content
+ HTTP/1.1 204 No Content
:param source: The source for which to list commands, currently either ``core`` or ``custom``
:param action: The identifier of the command, ``action`` from its definition
diff --git a/docs/api/timelapse.rst b/docs/api/timelapse.rst
index 914e43490..54b3668ec 100644
--- a/docs/api/timelapse.rst
+++ b/docs/api/timelapse.rst
@@ -128,7 +128,7 @@ Rendered timelapse
* - ``date``
- 1
- string
- - Formatted timestamp of the the timelapse creation date
+ - Formatted timestamp of the timelapse creation date
* - ``url``
- 1
- string
@@ -162,7 +162,7 @@ Unrendered timelapse
* - ``date``
- 1
- string
- - Formatted timestamp of the the timelapse job creation date
+ - Formatted timestamp of the timelapse job creation date
* - ``recording``
- 1
- bool
diff --git a/docs/api/util.rst b/docs/api/util.rst
index eb50df4b8..dde6d5100 100644
--- a/docs/api/util.rst
+++ b/docs/api/util.rst
@@ -38,13 +38,15 @@ Test paths or URLs
.. _sec-api-util-test-url:
url
- Tests whether a provided url responds. Request method and expected status codes can
+ Tests whether a provided URL responds. Request method and expected status codes can
optionally be specified as well. Supported parameters are:
- * ``url``: The url to test. Mandatory.
+ * ``url``: The URL to test. Mandatory.
* ``method``: The request method to use for the test. Optional, defaults to ``HEAD``.
* ``timeout``: A timeout for the request, in seconds. If no reply from the tested URL has been
received within this time frame, the check will be considered a failure. Optional, defaults to 3 seconds.
+ * ``validSsl``: Whether to validate the SSL connection if the ``url`` happens to be an HTTPS URL or not. Optional,
+ defaults to ``True``.
* ``status``: The status code(s) or named status range(s) to test for. Can be either a single
value or a list of either HTTP status codes or any of the following named status ranges:
@@ -63,11 +65,32 @@ Test paths or URLs
from the URL check will be returned as part of the check result as well. ``json`` will attempt
to parse the response as json and return the parsed result. ``true`` or ``bytes`` will base64 encode the body
and return that.
+ * ``content_type_whitelist``: Optional array of supported content types. If set and the URL returns a content
+ type not included in this list, the test will fail. E.g. ``["image/*", "text/plain"]``.
+ * ``content_type_blacklist``: Optional array of unsupported content types. If set and the URL returns a content
+ type included in this list, the test wil fail. E.g. ``["video/*"]``. Can be used together with ``content_type_whitelist``
+ to further limit broader content type definition, e.g. by putting ``image/*`` into the whitelist, but disallowing
+ PNG by including ``image/png`` on the blacklist.
The ``url`` command returns :http:statuscode:`200` with a :ref:`URL test result `
when the test could be performed. The status code of the response does NOT reflect the
test result!
+ .. _sec-api-util-test-server:
+
+ server
+ Tests whether a provided server identified by host and port can be reached. Protocol can optionally be specified
+ as well. Supported parameters are:
+
+ * ``host``: The host to test. IP or host name. Mandatory.
+ * ``port``: The port to test. Integer. Mandatory.
+ * ``protocol``: The protocol to test with. ``tcp`` or ``udp``. Optional, defaults to ``tcp``.
+ * ``timeout``: A timeout for the test, in seconds. If no successful connection to the server could be established
+ within this time frame, the check will be considered a failure. Optional, defaults to 3.05 seconds.
+
+ The ``server`` command returns :http:statuscode:`200` with a :ref:`Server test result `
+ when the test could be performed. The status code of the response does NOT reflect the test result!
+
Requires admin rights.
**Example 1**
@@ -226,6 +249,35 @@ Test paths or URLs
}
}
+ **Example 6**
+
+ Test whether a server is reachable on a given port via TCP.
+
+ .. sourcecode:: http
+
+ POST /api/util/test HTTP/1.1
+ Host: example.com
+ X-Api-Key: abcdef...
+ Content-Type: application/json
+
+ {
+ "command": "server",
+ "host": "8.8.8.8",
+ "port": 53
+ }
+
+ .. sourcecode:: http
+
+ HTTP/1.1 200 OK
+ Content-Type: application/json
+
+ {
+ "host": "8.8.8.8",
+ "port": 53,
+ "protocol": "tcp",
+ "result": true
+ }
+
:json command: The command to execute, currently either ``path`` or ``url``
:json path: ``path`` command only: the path to test
:json check_type: ``path`` command only: the type of path to test for, either ``file`` or ``dir``
@@ -233,8 +285,11 @@ Test paths or URLs
:json url: ``url`` command only: the URL to test
:json status: ``url`` command only: one or more expected status codes
:json method: ``url`` command only: the HTTP method to use for the check
- :json timeout: ``url`` command only: the timeout for the HTTP request
+ :json timeout: ``url`` and ``server`` commands only: the timeout for the test request
:json response: ``url`` command only: whether to include response data and if so in what form
+ :json host: ``server`` command only: the server to test
+ :json port: ``server`` command only: the port to test
+ :json protocol: ``server`` command only: the protocol to test
:statuscode 200: No error occurred
.. _sec-api-util-datamodel:
@@ -244,6 +299,9 @@ Data model
.. _sec-api-util-datamodel-pathtestresult:
+Path test result
+----------------
+
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
@@ -275,6 +333,9 @@ Data model
.. _sec-api-util-datamodel-urltestresult:
+URL test result
+---------------
+
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
@@ -306,3 +367,33 @@ Data model
- object
- A dictionary with all headers of the checked URL's response. Only present if ``response`` in the
request was set.
+
+.. _sec-api-util-datamodel-servertestresult:
+
+Server test result
+------------------
+
+.. list-table::
+ :widths: 15 5 10 30
+ :header-rows: 1
+
+ * - Name
+ - Multiplicity
+ - Type
+ - Description
+ * - ``host``
+ - 1
+ - string
+ - The host that was tested.
+ * - ``port``
+ - 1
+ - int
+ - The port that was tested
+ * - ``protocol``
+ - 1
+ - string
+ - The protocol that was tested, ``tcp`` or ``udp``
+ * - ``result``
+ - 1
+ - bool
+ - ``true`` if the check passed.
diff --git a/docs/bundledplugins/cura.rst b/docs/bundledplugins/cura.rst
index 30370e5be..d365e9ac3 100644
--- a/docs/bundledplugins/cura.rst
+++ b/docs/bundledplugins/cura.rst
@@ -1,4 +1,4 @@
-.. _sec-bundledplugins_cura:
+.. _sec-bundledplugins-cura:
Cura
====
@@ -45,7 +45,7 @@ Installing CuraEngine
You'll need a build of ``legacy`` branch of `CuraEngine `_
in order to be able to use the Cura OctoPrint plugin. You can find the ``legacy`` branch
-`here `_.
+`here `__.
If you previously used the `old variant of the Cura integration `_,
you probably still have a fully functional binary lying around in the
@@ -60,7 +60,7 @@ Compiling for Raspbian
.. note::
A binary of CuraEngine 15.04.06 precompiled on Raspbian Jessie Lite 2016-03-18 is available
- `here `_. Don't forget to make it
+ `here `__. Don't forget to make it
executable after copying it to your preferred destination on your Pi
(suggestion: ``/usr/local/bin``) with ``chmod +x cura_engine``. Use at your
own risk.
diff --git a/docs/bundledplugins/index.rst b/docs/bundledplugins/index.rst
index d5935a96a..bd862b005 100644
--- a/docs/bundledplugins/index.rst
+++ b/docs/bundledplugins/index.rst
@@ -9,5 +9,7 @@ Bundled Plugins
cura.rst
discovery.rst
+ logging.rst
pluginmanager.rst
+ printer_safety_check.rst
softwareupdate.rst
diff --git a/docs/bundledplugins/logging.rst b/docs/bundledplugins/logging.rst
new file mode 100644
index 000000000..d06d7915c
--- /dev/null
+++ b/docs/bundledplugins/logging.rst
@@ -0,0 +1,238 @@
+.. _sec-bundledplugins-logging:
+
+Logging
+=======
+
+The OctoPrint Logging plugin comes bundled with OctoPrint starting with version 1.3.7.
+
+It implements the log management functionality that was formerly part of the core application and adds features to
+configure logging levels for sub modules through the included settings dialog.
+
+.. _fig-bundledplugins-logging-settings:
+.. figure:: ../images/bundledplugins-logging-settings.png
+ :align: center
+ :alt: Logging plugin
+
+ The settings dialog of the Logging plugin
+
+.. _sec-bundledplugins-logging-api:
+
+API
+---
+
+.. note::
+
+ All log file management operations require admin rights.
+
+.. _sec-bundledplugins-logging-api-list_logs:
+
+Retrieve a list of available log files
+++++++++++++++++++++++++++++++++++++++
+
+.. http:get:: /plugin/logging/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.
+
+ Returns a :ref:`Logfile Retrieve response `.
+
+ **Example**
+
+ .. sourcecode:: http
+
+ GET /plugin/logging/logs HTTP/1.1
+ Host: example.com
+ X-Api-Key: abcdef...
+
+ .. sourcecode:: http
+
+ HTTP/1.1 200 OK
+ Content-Type: application/json
+
+ {
+ "files" : [
+ {
+ "date" : 1393158814,
+ "name" : "octoprint.log",
+ "size" : 43712,
+ "refs": {
+ "resource": "http://example.com/plugin/logging/logs/octoprint.log",
+ "download": "http://example.com/downloads/logs/octoprint.log"
+ }
+ },
+ {
+ "date" : 1392628936,
+ "name" : "octoprint.log.2014-02-17",
+ "size" : 13205,
+ "refs": {
+ "resource": "http://example.com/plugin/logging/logs/octoprint.log.2014-02-17",
+ "download": "http://example.com/downloads/logs/octoprint.log.2014-02-17"
+ }
+ },
+ {
+ "date" : 1393158814,
+ "name" : "serial.log",
+ "size" : 1798419,
+ "refs": {
+ "resource": "http://example.com/plugin/logging/logs/serial.log",
+ "download": "http://example.com/downloads/logs/serial.log"
+ }
+ }
+ ],
+ "free": 12237201408
+ }
+
+ :statuscode 200: No error
+ :statuscode 403: If the given API token did not have admin rights associated with it
+
+.. _sec-bundledplugins-logging-api-delete_logs:
+
+Delete a specific logfile
++++++++++++++++++++++++++
+
+.. http:delete:: /plugin/logging/logs/(path:filename)
+
+ Delete the selected log file with name `filename`.
+
+ Returns a :http:statuscode:`204` after successful deletion.
+
+ **Example Request**
+
+ .. sourcecode:: http
+
+ DELETE /plugin/logging/logs/octoprint.log.2014-02-17 HTTP/1.1
+ Host: example.com
+ X-Api-Key: abcdef...
+
+ :param filename: The filename of the log file to delete
+ :statuscode 204: No error
+ :statuscode 403: If the given API token did not have admin rights associated with it
+ :statuscode 404: If the file was not found
+
+.. _sec-bundledplugins-logging-api-datamodel:
+
+Data model
+++++++++++
+
+.. _sec-bundledplugins-logging-api-datamodel-retrieveresponse:
+
+Logfile Retrieve Response
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. list-table::
+ :widths: 15 5 10 30
+ :header-rows: 1
+
+ * - Name
+ - Multiplicity
+ - Type
+ - Description
+ * - ``files``
+ - 0..*
+ - Array of :ref:`File information items `
+ - The list of requested files. Might be an empty list if no files are available
+ * - ``free``
+ - 1
+ - String
+ - The amount of disk space in bytes available in the local disk space (refers to OctoPrint's ``logs`` folder).
+
+.. _sec-bundledplugins-logging-api-datamodel-fileinfo:
+
+File information
+~~~~~~~~~~~~~~~~
+
+.. list-table::
+ :widths: 15 5 10 30
+ :header-rows: 1
+
+ * - Name
+ - Multiplicity
+ - Type
+ - Description
+ * - ``name``
+ - 1
+ - String
+ - The name of the file
+ * - ``size``
+ - 1
+ - Number
+ - The size of the file in bytes.
+ * - ``date``
+ - 1
+ - Unix timestamp
+ - The timestamp when this file was last modified.
+ * - ``refs``
+ - 1
+ - :ref:`References `
+ - References relevant to this file
+
+.. _sec-bundledplugins-logging-api-datamodel-ref:
+
+References
+~~~~~~~~~~
+
+.. list-table::
+ :widths: 15 5 10 30
+ :header-rows: 1
+
+ * - Name
+ - Multiplicity
+ - Type
+ - Description
+ * - ``resource``
+ - 1
+ - URL
+ - The resource that represents the file (e.g. for deleting)
+ * - ``download``
+ - 1
+ - URL
+ - The download URL for the file
+
+.. _sec-bundledplugins-logging-jsclientlib:
+
+JS Client Library
+-----------------
+
+:mod:`OctoPrintClient.plugins.logging`
+--------------------------------------
+
+.. note::
+
+ All methods here require that the used API token or the existing browser session
+ has admin rights.
+
+.. js:function:: OctoPrintClient.plugins.logging.listLogs(opts)
+
+ Retrieves a list of log files.
+
+ See :ref:`Retrieve a list of available log files ` for details.
+
+ :param object opts: Additional options for the request
+ :returns Promise: A `jQuery Promise `_ for the request's response
+
+.. js:function:: OctoPrintClient.plugins.logging.deleteLog(path, opts)
+
+ Deletes the specified log ``path``.
+
+ See :ref:`Delete a specific log file ` for details.
+
+ :param string path: The path to the log file to delete
+ :param object opts: Additional options for the request
+ :returns Promise: A `jQuery Promise `_ for the request's response
+
+.. js:function:: OctoPrintClient.plugins.logging.downloadLog(path, opts)
+
+ Downloads the specified log ``file``.
+
+ See :js:func:`OctoPrint.download` for more details on the underlying library download mechanism.
+
+ :param string path: The path to the log file to download
+ :param object opts: Additional options for the request
+ :returns Promise: A `jQuery Promise `_ for the request's response
+
+.. _sec-bundledplugins-logging-sourcecode:
+
+Source Code
+-----------
+
+The source of the Logging plugin is bundled with OctoPrint and can be found in its source repository under ``src/octoprint/plugins/logging``.
diff --git a/docs/bundledplugins/pluginmanager.rst b/docs/bundledplugins/pluginmanager.rst
index e8c3675eb..dacb3f8ca 100644
--- a/docs/bundledplugins/pluginmanager.rst
+++ b/docs/bundledplugins/pluginmanager.rst
@@ -54,6 +54,12 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
# Time to live for the repository cache
repository_ttl: 1440
+ # The URL of the plugin notices feed to use
+ notices: http://plugins.octoprint.org/notices.json
+
+ # Time to live for the notices feed cache
+ notices_ttl: 360
+
# Additional arguments to use with pip. Defaults to unset,
# you normally shouldn't need to modify this
pip_args: --some --additional --pip --arguments
@@ -76,6 +82,36 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
- hidden
- plugins
+.. _sec-bundledplugins-pluginmanager-hooks:
+
+Hooks
+-----
+
+.. _sec-bundledplugins-pluginmanager-hooks-reconnect_hooks:
+
+octoprint.plugin.pluginmanager.reconnect_hooks
+++++++++++++++++++++++++++++++++++++++++++++++
+
+.. py:function:: reconnect_hooks_hook(*args, **kwargs)
+
+ Returns additional hooks defined by the plugin for which the plugin manager
+ should display the "You should reconnect to your printer" message on plugin
+ install/uninstall/enabling/disabling.
+
+ Handlers should return a Python list containing the affected hook names.
+
+ **Example**
+
+ .. code-block:: python
+
+ def reconnect_hooks_hook(*args, **kwargs):
+ return ["octoprint.plugin.exampleplugin.some_custom_hook",
+ "octoprint.plugin.exampleplugin.some_other_custom_hook"]
+
+ __plugin_hooks__ = {
+ "octoprint.plugin.pluginmanager.reconnect_hooks": reconnect_hooks_hook
+ }
+
.. _sec-bundledplugins-pluginmanager-sourcecode:
Source Code
diff --git a/docs/bundledplugins/printer_safety_check.rst b/docs/bundledplugins/printer_safety_check.rst
new file mode 100644
index 000000000..89974de48
--- /dev/null
+++ b/docs/bundledplugins/printer_safety_check.rst
@@ -0,0 +1,43 @@
+.. _sec-bundledplugins-printer_safety_check:
+
+Printer Safety Check
+====================
+
+The Printer Safety Check plugin comes bundled with OctoPrint starting with version 1.3.7.
+
+It tries to identify printers or rather printer firmwares with known safety issues, such as
+disabled thermal runaway protection, and displays a warning box to logged in users on
+such identification.
+
+.. _fig-bundledplugins-printer_safety_check-example:
+.. figure:: ../images/bundledplugins-printer_safety_check-example.png
+ :align: center
+ :alt: Printer Safety Check warning example
+
+ An example of a warning generated by the Printer Safety Check
+
+Currently the following firmwares produce this warning:
+
+ * Anet A8 stock firmware
+
+If you know of further printers/printer firmwares that need to be added here, please
+`get in touch on the forum and provide their response to an M115 `_.
+
+.. seealso::
+
+ `Entry on the "unsafe firmware" warning in OctoPrint's FAQ `_
+
+.. note::
+
+ Feel free to disable the plugin in OctoPrint's Plugin Manager if you feel like it is unnecessary. Be advised though
+ that even if your printer might be running totally fine with a known unsafe configuration, that might change
+ unexpectedly and with `catastrophic `_
+ `results `_.
+
+.. _sec-bundledplugins-printer_safety_check-source:
+
+Source Code
+-----------
+
+The source of the Printer Safety Check plugin is bundled with OctoPrint and can be
+found in its source repository under ``src/octoprint/plugins/printer_safety_check``.
diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst
index 17efc535c..de4896b6d 100644
--- a/docs/bundledplugins/softwareupdate.rst
+++ b/docs/bundledplugins/softwareupdate.rst
@@ -14,14 +14,14 @@ First Steps
Out of the box the Software Update Plugin will be able to notify you of any
updates that might be available for your OctoPrint installation or any plugins
-that registered themselves with it. In order to also be able to update
-your OctoPrint installation, you'll need to configure
-at least OctoPrint's checkout folder, and you also should
-configure the restart commands for OctoPrint and the whole server.
+that registered themselves with it. In order for automatic restarts after updates
+to work, you should configure the restart commands for OctoPrint and the whole server.
-For configuring the plugin you'll need to go into OctoPrint's Settings Dialog, navigate to the
-Software Upda.. _section therein and once you are there click on the little wrench icon in the
-upper right corner.
+Out of the box the plugin should already be ready to update your OctoPrint installation to current
+stable release versions, but you can also switch to one of the available release candidate channels
+or outright git commit tracking via the plugin's configuration dialog. To open this dialog, fire up OctoPrint's
+Settings Dialog, navigate to the Software Update section therein and once you are there click on the little
+wrench icon in the upper right corner.
.. _fig-bundledplugins-softwareupdate-plugin-configuration:
.. figure:: ../images/bundledplugins-softwareupdate-plugin-configuration.png
@@ -32,36 +32,21 @@ upper right corner.
There you can adjust the following settings:
- * **OctoPrint checkout folder**: This should be the path to OctoPrint's git checkout folder (``/home/pi/OctoPrint``
- for OctoPi or `manual installs following the Raspberry Pi setup guide `_).
- This must be set to allow updating from within OctoPrint
-
- .. note::
-
- OctoPi releases 0.12.0 and later ship with this already setup for you.
-
- .. note::
-
- **OctoPi 0.11.0 users**: Please also take a look at
- `the note at the very end of this FAQ entry `_.
- Due to a little issue in that OctoPi release 0.11.0 you might have to fix
- the URL your OctoPrint checkout is using for updating. This can easily be
- done by SSHing into your OctoPi instance and doing this::
-
- cd ~/OctoPrint
- git remote set-url origin https://github.com/foosel/OctoPrint.git
-
* **OctoPrint version tracking**: Whether you want to track OctoPrint *releases* or every *commit*. Usually you want to
select "Release" here which is also the default, unless you are a developer.
- * **OctoPrint Release Channel**: The release channel of OctoPrint to track for updates. If you only want stable versions,
+ * **OctoPrint Release Channel** (if tracking releases): The release channel of OctoPrint to track for updates. If you only want stable versions,
select "Stable" here which is also the default. "Maintenance RCs" will also allow you to update to maintenance release
candidates, "Devel RCs" will also allow you to update to development release candidates. If in doubt, leave it at
"Stable". `Read more about Release Channels here `_.
+ * **OctoPrint checkout folder** (if tracking git commits): This must be the path to OctoPrint's git checkout folder
+ (``/home/pi/OctoPrint`` for OctoPi or `manual installs following the Raspberry Pi setup guide `_).
+ Note that since OctoPrint 1.3.6 you will no longer need to set this to be able to update to releases, only if you
+ want to be able to update against some bleeding edge git branch.
* **Version cache TTL**: The "time to live" of the cache OctoPrint will use to temporarily persist the version information
for the various components registered with the plugin, so that they don't have to be queried from the internet every time
you load the page. Defaults to 24h, you usually shouldn't need to change that value.
-More settings are available by :ref:`editing the correspondi.. _section in config.yaml `.
+More settings are available by :ref:`editing the corresponding section in config.yaml `.
That restart commands for OctoPrint and the whole server can be configured under Settings > Server.
@@ -71,9 +56,9 @@ Command line usage
------------------
The functionality of the Software Update Plugin is also available on OctoPrint's command line interface under the
-``plugins`` sub command. It's is possible to check for updates via ``octoprint plugins softwareupdate:check``
-and to apply available updates via ``octoprint plugins softwareupdate:update``. Please the corresponding
-``--help`` pages on details:
+``plugins`` sub command. It's possible to check for updates via ``octoprint plugins softwareupdate:check``
+and to apply available updates via ``octoprint plugins softwareupdate:update``. Please see the corresponding
+``--help`` pages for details:
.. code-block:: none
@@ -132,30 +117,29 @@ Configuring the Plugin
.. code-block:: yaml
- plugins:
- softwareupdate:
- # the time-to-live of the version cache, in minutes
- cache_ttl: 60
+ plugins:
+ softwareupdate:
+ # the time-to-live of the version cache, in minutes
+ cache_ttl: 60
- # configured version check and update methods
- checks:
- # "octoprint" is reserved for OctoPrint
- octoprint:
- # this defines an version check that will check against releases
- # published on OctoPrint's Github repository and an update method
- # utilizing an (included) update script that will be run on
- # OctoPrint's checkout folder
- type: github_release
- user: foosel
- repo: OctoPrint
- update_script: '{python} "/path/to/octoprint-update.py" --python="{python}" "{folder}" "{target}"'
- update_folder: /path/to/octoprint/checkout/folder
+ # configured version check and update methods
+ checks:
+ # "octoprint" is reserved for OctoPrint
+ octoprint:
+ # this defines a version check that will check against releases
+ # published on OctoPrint's Github repository and pip as update method
+ # against the release archives on Github - this is the default
+ type: github_release
+ user: foosel
+ repo: OctoPrint
+ method: pip
+ pip: 'https://github.com/foosel/OctoPrint/archive/{target_version}.zip'
- # further checks may be define here
+ # further checks may be defined here
- # pip command, if another one than the automatically detected one should be
- # used - should normally NOT be necessary and hence set
- pip_command: /path/to/pip
+ # pip command, if another one than the automatically detected one should be
+ # used - should normally NOT be necessary and hence set
+ pip_command: /path/to/pip
.. _sec-bundledplugins-softwareupdate-configuration-versionchecks:
@@ -198,6 +182,13 @@ Version checks
* ``branch``: Branch of the Bitbucket repository to check, defaults to
``master`` if not set.
* ``current``: Current commit hash. Will be updated automatically.
+ * ``api_user``: (mandatory only for private repositories) Bitbucket user name (not email address).
+ Requires ``api_password`` to be set. Hint: This is used for the check only. For the actual
+ download you might register your public SSH key as access key for the according repo and
+ configure this as pip URL in ``config.yaml``: ``git+ssh://git@bitbucket.org/my_user/my_repo.git@{target_version}``
+ * ``api_password``: (mandatory only for private repositories) App password. Requires
+ ``api_user`` to be set. **Important**: Never use your actual Bitbucket login password. Generate
+ a new app password. App passwords are user specific on Bitbucket.
* ``git_commit``: Checks a local git repository for new commits on its
configured remote. Additional config parameters:
@@ -218,10 +209,21 @@ Version checks
:ref:`hook `. Additional config
parameters:
- * ``python_checker``: (mandatory) A python callable which returns version
+ * ``python_checker``: (mandatory) A Python callable which returns version
information and whether the current version is up-to-date or not, see
below for details.
+ * ``always_current``: Always reports that no update is necessary. Useful for debugging
+ software update mechanisms during development. Additional config parameters:
+
+ * ``current_version``: Version to report for both local and remote version.
+
+ * ``never_current``: Always reports that an update is necessary. Useful for debugging
+ software update mechanisms during development. Additional config parameters:
+
+ * ``local_version``: Current local version. Defaults to ``1.0.0``.
+ * ``remote_version``: Remote version to offer update to. Defaults to ``1.0.1``.
+
.. _sec-bundledplugins-softwareupdate-configuration-updatemethods:
Update methods
@@ -239,8 +241,37 @@ Update methods
``update_folder`` setting or if the ``git_commit`` check is used its
``checkout_folder`` setting.
* ``python_updater``: Can only be specified by plugins through the
- :ref:`hook `. A python callable
+ :ref:`hook `. A Python callable
which performs the update, see below for details.
+ * ``sleep_a_bit``: Does nothing but block for a configurable ``duration`` and log
+ a countdown in the meantime. Useful for debugging software update mechanisms
+ during development.
+
+.. note::
+
+ To allow default configurations for multiple update methods, if more than one of
+ the above update method specific settings is set the one to use can be selected
+ by setting the property ``method`` to the method specific setting in question.
+
+ **Example**
+
+ The following example defines both ``pip`` and ``update_script``. By setting to
+ ``method`` to ``pip``, the Software Update plugin is instructed to use that as
+ update method.
+
+ .. code-block:: yaml
+
+ plugins:
+ softwareupdate:
+ checks:
+ octoprint:
+ type: github_release
+ user: foosel
+ repo: OctoPrint
+ method: pip
+ pip: 'https://github.com/foosel/OctoPrint/archive/{target_version}.zip'
+ update_script: '{python} "/path/to/octoprint-update.py" --python="{python}" "{folder}" "{target}"'
+ checkout_folder: /path/to/octoprint/checkout/folder
.. _sec-bundledplugins-softwareupdate-configuration-patterns:
@@ -261,6 +292,7 @@ plugin itself):
user: foosel
repo: OctoPrint
branch: devel
+ method: update_script
update_folder: /home/pi/OctoPrint
Plugin installed via pip and hosted on Github under
diff --git a/docs/conf.py b/docs/conf.py
index 74799d526..3827b54fa 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -33,7 +33,7 @@ needs_sphinx = '1.3'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain',
- 'sphinx.ext.napoleon']
+ 'sphinx.ext.napoleon', 'sphinxcontrib.mermaid']
todo_include_todos = True
# Add any paths that contain templates here, relative to this directory.
diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst
index debb35d16..79795f021 100644
--- a/docs/configuration/config_yaml.rst
+++ b/docs/configuration/config_yaml.rst
@@ -36,7 +36,7 @@ Use the following settings to enable access control:
# If set to true, will automatically log on clients originating from any of the networks defined in
# "localNetworks" as the user defined in "autologinAs". Defaults to false.
- autologinLocal: true
+ autologinLocal: false
# The name of the user to automatically log on clients originating from "localNetworks" as. Must
# be the name of one of your configured users.
@@ -51,6 +51,17 @@ Use the following settings to enable access control:
- 127.0.0.0/8
- 192.168.1.0/24
+ # Whether to trust Basic Authentication headers. If you have setup Basic Authentication in front of
+ # OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will
+ # be logged into OctoPrint as the user user during Basic Authentication. Your should ONLY ENABLE THIS if your
+ # OctoPrint instance is only accessible through a connection locked down through Basic Authentication!
+ trustBasicAuthentication: false
+
+ # Whether to also check the password provided through Basic Authentication if the Basic Authentication
+ # header is to be trusted. Disabling this will only match the user name in the Basic Authentication
+ # header and login the user without further checks. Use with caution.
+ checkBasicAuthenticationPassword: true
+
.. _sec-configuration-config_yaml-api:
API
@@ -140,7 +151,7 @@ appearance or to modify the order and presence of the various UI components:
# order of settings, if settings plugins are registered gets extended internally by
# section_plugins and all settings plugins
- settings
+ settings:
- section_printer
- serial
- printerprofiles
@@ -285,9 +296,13 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# to false.
okWithLinenumber: false
- # Number of extruders to simulate on the virtual printer.
+ # Number of extruders to simulate on the virtual printer. Map from tool id (0, 1, ...) to temperature
+ # in °C
numExtruders: 1
+ # Allows pinning certain hotends to a fixed temperature
+ pinnedExtruders: null
+
# Whether to include the current tool temperature in the M105 output as separate T segment or not.
#
# True: > M105
@@ -304,13 +319,6 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# > File opened
includeFilenameInOpened: true
- # The maximum movement speeds of the simulated printer's axes, in mm/s
- movementSpeed:
- x: 6000
- y: 6000
- z: 200
- e: 300
-
# Whether the simulated printer should also simulate a heated bed or not
hasBed: true
@@ -331,6 +339,18 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# to make sure nothing gets lost on the line
repetierStyleResends: false
+ # If enabled, ok will be sent before a commands output, otherwise after or inline (M105)
+ #
+ # True: > M20
+ # < ok
+ # < Begin file list
+ # < End file list
+ # False: > M20
+ # < Begin file list
+ # < End file list
+ # < ok
+ okBeforeCommandOutput: false
+
# If enabled, reports the first extruder in M105 responses as T instead of T0
#
# True: > M105
@@ -358,7 +378,8 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# side will block
rxBuffer: 64
- # Size of simulated command buffer
+ # Size of simulated command buffer, number of commands. If full, buffered commands will block
+ # until a slot frees up
commandBuffer: 4
# Whether to support the M112 command with simulated kill
@@ -370,6 +391,58 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# Whether to simulate broken M29 behaviour (missing ok after response)
brokenM29: true
+ # Whether F is supported as individual command
+ supportF: false
+
+ # Firmware name to report (useful for testing firmware detection)
+ firmwareName: Virtual Marlin 1.0
+
+ # Simulate a shared nozzle
+ sharedNozzle: false
+
+ # Send "busy" messages if busy processing something
+ sendBusy: false
+
+ # Simulate a reset on connect
+ simulateReset: true
+
+ # Lines to send on simulated reset
+ resetLines:
+ - start
+ - Marlin: Virtual Marlin!
+ - "\x80"
+ - "SD card ok"
+
+ # Initial set of prepared oks to use instead of regular ok (e.g. to simulate
+ # mis-sent oks). Can also be filled at runtime via the debug command prepare_ok
+ preparedOks: []
+
+ # Format string for ok response.
+ #
+ # Placeholders:
+ # - lastN: last acknowledged line number
+ # - buffer: empty slots in internal command buffer
+ #
+ # Example format string for "extended" ok format:
+ # ok N{lastN} P{buffer}
+ okFormatString: ok
+
+ # Format string for M115 output.
+ #
+ # Placeholders:
+ # - firmare_name: The firmware name as defined in firmwareName
+ m115FormatString: "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0"
+
+ # Whether to include capability report in M115 output
+ m115ReportCapabilites: false
+
+ # Capabilities to report if capability report is enabled
+ capabilities:
+ AUTOREPORT_TEMP: true
+
+ # Simulated ambient temperature in °C
+ ambientTemperature: 21.3
+
.. _sec-configuration-config_yaml-estimation:
Estimation
@@ -381,7 +454,7 @@ the estimation of the left print time during an active job utilizes this section
.. code-block:: yaml
estimation:
- # Parameters for the print time estmation during an ongoing print job
+ # Parameters for the print time estimation during an ongoing print job
printTime:
# Until which percentage to do a weighted mixture of statistical duration (analysis or
# past prints) with the result from the calculated estimate if that's already available.
@@ -460,52 +533,16 @@ Use the following settings to enable or disable OctoPrint features:
.. code-block:: yaml
feature:
+
# Whether to enable the gcode viewer in the UI or not
gCodeVisualizer: true
# Whether to enable the temperature graph in the UI or not
temperatureGraph: true
- # Specifies whether OctoPrint should wait for the start response from the printer before trying to send commands
- # during connect.
- waitForStartOnConnect: false
-
- # Specifies whether OctoPrint should send linenumber + checksum with every printer command. Needed for
- # successful communication with Repetier firmware
- alwaysSendChecksum: false
-
- # Specifies whether OctoPrint should also send linenumber + checksum with commands that are *not*
- # detected as valid GCODE (as in, they do not match the regular expression "^\s*([GM]\d+|T)").
- sendChecksumWithUnknownCommands: false
-
- # Specifies whether OctoPrint should also use up acknowledgments ("ok") for commands that are *not*
- # detected as valid GCODE (as in, they do not match the regular expression "^\s*([GM]\d+|T)").
- unknownCommandsNeedAck: false
-
- # Whether to ignore the first ok after a resend response. Needed for successful communication with
- # Repetier firmware
- swallowOkAfterResend: false
-
# Specifies whether support for SD printing and file management should be enabled
sdSupport: true
- # Specifies whether firmware expects relative paths for selecting SD files
- sdRelativePath: false
-
- # Whether to always assume that an SD card is present in the printer.
- # Needed by some firmwares which don't report the SD card status properly.
- sdAlwaysAvailable: false
-
- # Whether the printer sends repetier style target temperatures in the format
- # TargetExtr0:
- # instead of attaching that information to the regular M105 responses
- repetierTargetTemp: false
-
- # Whether to enable external heatup detection (to detect heatup triggered e.g. through the printer's LCD panel or
- # while printing from SD) or not. Causes issues with Repetier's "first ok then response" approach to
- # communication, so disable for printers running Repetier firmware.
- externalHeatupDetection: true
-
# Whether to enable the keyboard control feature in the control tab
keyboardControl: true
@@ -513,28 +550,16 @@ Use the following settings to enable or disable OctoPrint features:
# notifications instead (false)
pollWatched: false
- # Whether to ignore identical resends from the printer (true, repetier) or not (false)
- ignoreIdenticalResends: false
-
- # If ignoredIdenticalResends is true, how many consecutive identical resends to ignore
- identicalResendsCount: 7
-
- # Whether to support F on its own as a valid GCODE command (true) or not (false)
- supportFAsCommand: false
-
# Whether to enable model size detection and warning (true) or not (false)
modelSizeDetection: true
- # Whether to attempt to auto detect the firmware of the printer and adjust settings
- # accordingly (true) or not and rely on manual configuration (false)
- firmwareDetection: true
-
# Whether to show a confirmation on print cancelling (true) or not (false)
printCancelConfirmation: true
- # Whether to block all sending to the printer while a G4 (dwell) command is active (true, repetier)
- # or not (false)
- blockWhileDwelling: false
+ # Commands that should never be auto-uppercased when sent to the printer through the Terminal tab.
+ # Defaults to only M117.
+ autoUppercaseBlacklist:
+ - M117
.. _sec-configuration-config_yaml-folder:
@@ -738,6 +763,10 @@ Use the following settings to configure the serial connection to the printer:
# Defaults to 30 sec
communication: 30
+ # Timeout during serial communication when busy protocol support is detected, in seconds.
+ # Defaults to 3 sec
+ communicationBusy: 3
+
# Timeout after which to query temperature when no target is set
temperature: 5
@@ -762,7 +791,7 @@ Use the following settings to configure the serial connection to the printer:
# Maximum number of write attempts to serial during which nothing can be written before the communication
# with the printer is considered dead and OctoPrint will disconnect with an error
- maxWritePasses:
+ maxWritePasses: 5
# Use this to define additional patterns to consider for serial port listing. Must be a valid
# "glob" pattern (see http://docs.python.org/2/library/glob.html). Defaults to not set.
@@ -793,7 +822,8 @@ Use the following settings to configure the serial connection to the printer:
# 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
+ helloCommand:
+ - M110 N0
# Whether to disconnect on errors or not
disconnectOnErrors: true
@@ -805,13 +835,75 @@ Use the following settings to configure the serial connection to the printer:
# impact, leave on if possible please
logResends: true
+ # Specifies whether OctoPrint should wait for the start response from the printer before trying to send commands
+ # during connect.
+ waitForStartOnConnect: false
+
+ # Specifies whether OctoPrint should send linenumber + checksum with every printer command. Needed for
+ # successful communication with Repetier firmware
+ alwaysSendChecksum: false
+
+ # Specifies whether OctoPrint should also send linenumber + checksum with commands that are *not*
+ # detected as valid GCODE (as in, they do not match the regular expression "^\s*([GM]\d+|T)").
+ sendChecksumWithUnknownCommands: false
+
+ # Specifies whether OctoPrint should also use up acknowledgments ("ok") for commands that are *not*
+ # detected as valid GCODE (as in, they do not match the regular expression "^\s*([GM]\d+|T)").
+ unknownCommandsNeedAck: false
+
+ # Whether to ignore the first ok after a resend response. Needed for successful communication with
+ # Repetier firmware
+ swallowOkAfterResend: false
+
+ # Specifies whether firmware expects relative paths for selecting SD files
+ sdRelativePath: false
+
+ # Whether to always assume that an SD card is present in the printer.
+ # Needed by some firmwares which don't report the SD card status properly.
+ sdAlwaysAvailable: false
+
+ # Whether the printer sends repetier style target temperatures in the format
+ # TargetExtr0:
+ # instead of attaching that information to the regular M105 responses
+ repetierTargetTemp: false
+
+ # Whether to enable external heatup detection (to detect heatup triggered e.g. through the printer's LCD panel or
+ # while printing from SD) or not. Causes issues with Repetier's "first ok then response" approach to
+ # communication, so disable for printers running Repetier firmware.
+ externalHeatupDetection: true
+
+ # Whether to ignore identical resends from the printer (true, repetier) or not (false)
+ ignoreIdenticalResends: false
+
+ # If ignoredIdenticalResends is true, how many consecutive identical resends to ignore
+ identicalResendsCount: 7
+
+ # Whether to support F on its own as a valid GCODE command (true) or not (false)
+ supportFAsCommand: false
+
+ # Whether to attempt to auto detect the firmware of the printer and adjust settings
+ # accordingly (true) or not and rely on manual configuration (false)
+ firmwareDetection: true
+
+ # Whether to block all sending to the printer while a G4 (dwell) command is active (true, repetier)
+ # or not (false)
+ blockWhileDwelling: false
+
# Whether to support resends without follow-up ok or not
supportResendsWithoutOk: false
# Whether to "manually" trigger an ok for M29 (a lot of versions of this command are buggy and
- # the responds skips on the ok)
+ # the response skips on the ok)
triggerOkForM29: true
+ capabilities:
+
+ # Whether to enable temperature autoreport in the firmware if its support is detected
+ autoreport_temp: true
+
+ # Whether to shorten the communication timeout if the firmware seems to support the busy protocol
+ busy_protocol: true
+
.. _sec-configuration-config_yaml-server:
Server
@@ -842,7 +934,7 @@ Use the following settings to configure the server:
# Settings if OctoPrint is running behind a reverse proxy (haproxy, nginx, apache, ...).
# These are necessary in order to make OctoPrint generate correct external URLs so
- # that AJAX requests and download URLs work.
+ # that AJAX requests and download URLs work, and so that client IPs are read correctly.
reverseProxy:
# The request header from which to determine the URL prefix under which OctoPrint
@@ -876,6 +968,14 @@ Use the following settings to configure the server:
# (X-Forwarded-Host by default, see above) with forwarded requests.
hostFallback:
+ # List of trusted downstream servers for which to ignore the IP address when trying to determine
+ # the connecting client's IP address. If you have OctoPrint behind more than one reverse proxy
+ # you should add their IPs here so that they won't be interpreted as the client's IP. One reverse
+ # proxy will be handled correctly by default.
+ trustedDownstream:
+ - 192.168.1.254
+ - 192.168.23.42
+
# Settings for file uploads to OctoPrint, such as maximum allowed file size and
# header suffixes to use for streaming uploads. OctoPrint does some nifty things internally in
# order to allow streaming of large file uploads to the application rather than just storing
@@ -909,6 +1009,31 @@ Use the following settings to configure the server:
# Command to shut down the system OctoPrint is running on, defaults to being unset
systemShutdownCommand: sudo shutdown -h now
+ # Configuration of the regular online connectivity check
+ onlineCheck:
+ # whether the online check is enabled, defaults to false due to valid privacy concerns
+ enabled: false
+
+ # interval in which to check for online connectivity (in seconds)
+ interval: 300
+
+ # DNS host against which to check (default: 8.8.8.8 aka Google's DNS)
+ host: 8.8.8.8
+
+ # DNS port against which to check (default: 53 - the default DNS port)
+ port: 53
+
+ # Configuration of the plugin blacklist
+ pluginBlacklist:
+ # whether use of the blacklist is enabled, defaults to false
+ enabled: false
+
+ # the URL from which to fetch the blacklist
+ url: http://plugins.octoprint.org/blacklist.json
+
+ # time to live of the cached blacklist, in seconds (default: 15 minutes)
+ ttl: 15 * 60
+
# Settings of when to display what disk space warning
diskspace:
@@ -975,7 +1100,12 @@ System
Use the following settings to add custom system commands to the "System" dropdown within OctoPrint's top bar.
-Commands consist of a name, an action identifier, the commandline to execute and an optional confirmation message to
+Commands consist of a ``name`` shown to the user, an ``action`` identifier used by the code and the actual
+``command`` including any argument needed for its execution.
+By default OctoPrint blocks until the command has returned so that the exit code can be used to show a success
+or failure message; use the flag ``async: true`` for commands that don't return.
+
+Optionally you can add a confirmation message to
display before actually executing the command (should be set to False if a confirmation dialog is not desired).
The following example defines a command for shutting down the system under Linux. It assumes that the user under which
@@ -990,7 +1120,7 @@ OctoPrint is running is allowed to do this without password entry:
command: sudo shutdown -h now
confirm: You are about to shutdown the system.
-You can also add an divider by setting action to divider like this:
+You can also add a divider by setting action to divider like this:
.. code-block:: yaml
diff --git a/docs/development/environment.rst b/docs/development/environment.rst
new file mode 100644
index 000000000..8308712b7
--- /dev/null
+++ b/docs/development/environment.rst
@@ -0,0 +1,218 @@
+.. _sec-development-environment:
+
+Setting up a Development environment
+====================================
+
+.. _sec-development-environment-source:
+
+Obtaining, building and running the source
+------------------------------------------
+
+This describes the general steps in obtaining, building and running. OS specific instructions can be found
+below.
+
+ * Prerequisites:
+
+ * `Python 2.7 `_ including ``pip``, ``setuptools`` and ``virtualenv``
+ * `Git `_
+
+ * Checkout the OctoPrint sources from their Git repository: ``git clone https://github.com/foosel/OctoPrint.git``
+ * Enter the checked out source folder: ``cd OctoPrint``
+ * Create a virtual environment in the checked out source folder to use for installing and running OctoPrint and its
+ dependencies (this avoids potential versioning issues for the dependencies with system wide installed
+ instances): ``virtualenv venv``
+ * Activate the virtual environment: ``source venv/bin/activate`` (Linux, MacOS) or
+ ``source venv/Scripts/activate`` (Git Bash under Windows, see below)
+ * Update ``pip`` in the virtual environment: ``pip install --upgrade pip``
+ * Install OctoPrint in `"editable" mode `_,
+ including its regular *and* development and plugin development dependencies: ``pip install -e .[develop,plugins]``
+
+When the virtual environment is activated you can then:
+
+ * run the OctoPrint server via ``octoprint serve``
+ * run the test suite from the checked out source folder via ``nosetests --with-doctest``
+ * build the documentation from the ``docs`` sub folder of the checked out sources via ``sphinx-build -b html . _build``
+
+.. _sec-development-environment-source-linux:
+
+Linux
+.....
+
+This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
+location, please substitute accordingly.
+
+First make sure you have python including its header files, pip, setuptools, virtualenv, git and some build requirements
+installed:
+
+ * On apt based distributions (e.g. Debian, Ubuntu, ...):
+
+ .. code-block:: none
+
+ sudo apt-get install python python-pip python-dev python-setuptools python-virtualenv git libyaml-dev build-essential
+
+ * On zypper based distributions (example below for SLES 12 SP2):
+
+ .. code-block:: none
+
+ sudo zypper ar https://download.opensuse.org/repositories/devel:/languages:/python/SLE_12_SP2/ python_devel
+ sudo zypper ref
+ sudo zypper in python python-pip python-devel python-setuptools python-virtualenv git libyaml-devel
+ sudo zypper in -t pattern Basis-Devel
+
+.. todo::
+
+ Using a Linux distribution that doesn't use ``apt`` or ``zypper``? Please send a
+ `Pull Request `_ to get the necessary
+ steps into this guide!
+
+Then:
+
+.. code-block:: none
+
+ cd ~/devel
+ git clone https://github.com/foosel/OctoPrint.git
+ cd OctoPrint
+ virtualenv venv
+ source ./venv/bin/activate
+ pip install --upgrade pip
+ pip install -e .[develop,plugins]
+
+You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
+environment.
+
+.. _sec-development-environment-windows:
+
+Windows
+.......
+
+This assumes you'll host your OctoPrint development checkout at ``C:\Devel\OctoPrint``. If you want to use a different
+location, please substitute accordingly.
+
+First download & install:
+
+ * `Python 2.7.12 Windows x86 MSI installer `_
+
+ * make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too
+
+ * `Microsoft Visual C++ Compiler for Python 2.7 `_
+ * `Git for Windows `_
+
+Open the Git Bash you just installed and in that:
+
+.. code-block:: none
+
+ pip install virtualenv
+ cd /c/Devel
+ git clone https://github.com/foosel/OctoPrint.git
+ cd OctoPrint
+ virtualenv venv
+ source ./venv/Scripts/activate
+ pip install --upgrade pip
+ pip install -e .[develop,plugins]
+
+.. _sec-development-environment-mac:
+
+Mac OS X
+........
+
+.. note::
+
+ This guide is based on the `Setup Guide for Mac OS X on OctoPrint's wiki `_.
+ Please report back if it works for you, due to lack of access to a Mac I cannot test it myself. Thanks.
+
+This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
+location, please substitute accordingly.
+
+You'll need a user account with administrator privileges.
+
+ * Install the latest version of Xcode suitable for your OS. For example, OS X 10.11 (El Capitan) requires Xcode 7.
+ * Install Xcode's command line tools:
+
+ * ``xcode-select --install``
+ * ``sudo xcodebuild`` (ensure the license was accepted)
+ * If you have more than one Xcode installed: ``sudo xcode-select -s /Applications/Xcode.app/Contents/Developer``
+
+ * Install Homebrew and use that to install Python:
+
+ * ``ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"``
+ * ``brew install python``
+
+ * Install `virtualenv `_
+
+ * ``pip install virtualenv``
+
+ * Install OctoPrint
+
+ .. code-block:: none
+
+ cd ~/devel
+ git clone https://github.com/foosel/OctoPrint.git
+ cd OctoPrint
+ virtualenv venv
+ source venv/bin/activate
+ pip install --upgrade pip
+ pip install -e .[develop,plugins]
+
+.. _sec-development-environment-ides:
+
+IDE Setup
+---------
+
+.. todo::
+
+ Using another IDE than the ones below? Please send a
+ `Pull Request `_ to get the necessary
+ steps into this guide!
+
+.. _sec-development-environment-ides-pycharm:
+
+PyCharm
+.......
+
+ - "File" > "Open ...", select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
+ - "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
+ folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``)
+ - Right click "src" in project tree, mark as source folder
+ - Add Run/Debug Configuration, select "Python":
+
+ * Name: OctoPrint server
+ * Script: path to ``run`` in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/run`` or ``C:\Devel\OctoPrint\run``)
+ * Script parameters: ``serve --debug``
+ * Project: ``OctoPrint``
+ * Python interpreter: the ``venv`` local virtual environment
+ * Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
+ * If you want dependencies to auto-update on run if necessary: "Before Launch" > "+" > "Run external tool" > "+"
+
+ * Name: Update OctoPrint dependencies
+ * Program: ``$PyInterpreterDirectory$/pip`` (or ``$PyInterpreterDirectory$/pip.exe`` on Windows)
+ * Parameters: ``install -e .[develop,plugins]``
+ * Working directory: ``$ProjectFileDir$``
+
+ - Add Run/Debug Configuration, select "Python tests" and therein "Nosetests":
+
+ * Name: OctoPrint nosetests
+ * Target: Path, ``.``
+ * Project: ``OctoPrint``
+ * Python interpreter: the ``venv`` local virtual environment
+ * Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
+ * Just like with the run configuration for the server you can also have the dependencies auto-update on run of
+ the tests, see above on how to set this up.
+
+ - Add Run/Debug Configuration, select "Python docs" and therein "Sphinx task"
+
+ * Name: OctoPrint docs
+ * Command: ``html``
+ * Input: the ``docs`` folder in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/docs`` or
+ ``C:\Devel\OctoPrint\docs``)
+ * Output: the ``docs/_build`` folder in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/docs/_build`` or
+ ``C:\Devel\OctoPrint\docs\_build``)
+ * Project: ``OctoPrint``
+ * Python interpreter: the ``venv`` local virtual environment
+ * Just like with the run configuration for the server you can also have the dependencies auto-update when building
+ the documentation, see above on how to set this up.
+
+.. note::
+
+ Make sure you are running a PyCharm version of 2016.1 or later, or manually fix
+ `a debugger bug contained in earlier versions `_ or plugin management
+ will not work in your developer install when running OctoPrint from PyCharm in debug mode.
diff --git a/docs/development/index.rst b/docs/development/index.rst
index 7d24a843e..8b3038592 100644
--- a/docs/development/index.rst
+++ b/docs/development/index.rst
@@ -4,183 +4,8 @@
Development
###########
-.. contents::
- :local:
+.. toctree::
+ :maxdepth: 3
-.. _sec-development-environment:
-
-Setting up a Development environment
-====================================
-
-.. _sec-development-environment-source:
-
-Obtaining, building and running the source
-------------------------------------------
-
-This describes the general steps in obtaining, building and running. OS specific instructions can be found
-below.
-
- * Prerequisites:
-
- * `Python 2.7 `_ including ``pip``, ``setuptools`` and ``virtualenv``
- * `Git `_
-
- * Checkout the OctoPrint sources from their Git repository: ``git clone https://github.com/foosel/OctoPrint.git``
- * Create a virtual environment in the checkout folder to use for installing and running OctoPrint and its
- dependencies (this avoids potential versioning issues for the dependencies with system wide installed
- instances): ``virtualenv venv``
- * Activate the virtual environment: ``source venv/bin/activate`` (might differ per your platform/OS)
- * Update ``pip`` in the virtual environment: ``pip install --upgrade pip``
- * Install OctoPrint in `"editable" mode `_,
- including its regular *and* development dependencies: ``pip install -e .[develop]``
-
-.. _sec-development-environment-source-linux:
-
-Linux
-.....
-
-This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
-location, please substitute accordingly.
-
-First make sure you have python including its header files, pip, setuptools, virtualenv, git and some build requirements
-installed:
-
- * On apt based distributions (e.g. Debian, Ubuntu, ...):
-
- .. code-block:: none
-
- sudo apt-get install python python-pip python-dev python-setuptools python-virtualenv git libyaml-dev build-essential
-
-.. todo::
-
- Using a Linux distribution that doesn't use ``apt``? Please send a
- `Pull Request `_ to get the necessary
- steps into this guide!
-
-Then:
-
-.. code-block:: none
-
- cd ~/devel
- git clone https://github.com/foosel/OctoPrint.git
- cd OctoPrint
- virtualenv venv
- source ./venv/bin/activate
- pip install --upgrade pip
- pip install -e .[develop]
-
-You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
-environment.
-
-.. _sec-development-environment-windows:
-
-Windows
-.......
-
-This assumes you'll host your OctoPrint development checkout at ``C:\Devel\OctoPrint``. If you want to use a different
-location, please substitute accordingly.
-
-First download & install:
-
- * `Python 2.7.12 Windows x86 MSI installer `_
-
- * make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too
-
- * `Microsoft Visual C++ Compiler for Python 2.7 `_
- * `Git for Windows `_
-
-Open the Git Bash you just installed and in that:
-
-.. code-block:: none
-
- pip install virtualenv
- cd /c/Devel
- git clone https://github.com/foosel/OctoPrint.git
- cd OctoPrint
- virtualenv venv
- source ./venv/bin/activate
- pip install --upgrade pip
- pip install -e .[develop]
-
-You can then start OctoPrint via ``/c/Devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
-environment.
-
-.. _sec-development-environment-mac:
-
-Mac OS X
-........
-
-.. note::
-
- This guide is based on the `Setup Guide for Mac OS X on OctoPrint's wiki `_.
- Please report back if it works for you, due to lack of access to a Mac I cannot test it myself. Thanks.
-
-This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
-location, please substitute accordingly.
-
-You'll need a user account with administrator privileges.
-
- * Install the latest version of Xcode suitable for your OS. For example, OS X 10.11 (El Capitan) requires Xcode 7.
- * Install Xcode's command line tools:
-
- * ``xcode-select --install``
- * ``sudo xcodebuild`` (ensure the license was accepted)
- * If you have more than one Xcode installed: ``sudo xcode-select -s /Applications/Xcode.app/Contents/Developer``
-
- * Install Homebrew and use that to install Python:
-
- * ``ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"``
- * ``brew install python``
-
- * Install `virtualenv `_
-
- * ``pip install virtualenv``
-
- * Install OctoPrint
-
- .. code-block:: none
-
- cd ~/devel
- git clone https://github.com/foosel/OctoPrint.git
- cd OctoPrint
- virtualenv venv
- source venv/bin/activate
- pip install -e .[develop]
-
-You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
-environment.
-
-.. _sec-development-environment-ides:
-
-IDE Setup
----------
-
-.. todo::
-
- Using another IDE than the ones below? Please send a
- `Pull Request `_ to get the necessary
- steps into this guide!
-
-.. _sec-development-environment-ides-pycharm:
-
-PyCharm
-.......
-
- - "File" > "Open ...", select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
- - "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
- folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``)
- - Right click "src" in project tree, mark as source folder
- - Add Run/Debug Configuration, select "Python":
-
- * Name: OctoPrint server
- * Script: path to ``run`` in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/run`` or ``C:\Devel\OctoPrint\run``)
- * Script parameters: ``--debug``
- * Project: ``OctoPrint``
- * Python interpreter: the ``venv`` local virtual environment
- * Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
-
-.. note::
-
- Make sure you are running a PyCharm version of 2016.1 or later, or manually fix
- `a debugger bug contained in earlier versions `_ or plugin management
- will not work in your developer install when running OctoPrint from PyCharm in debug mode.
+ environment.rst
+ virtual_printer.rst
diff --git a/docs/development/virtual_printer.rst b/docs/development/virtual_printer.rst
new file mode 100644
index 000000000..479cdc198
--- /dev/null
+++ b/docs/development/virtual_printer.rst
@@ -0,0 +1,116 @@
+.. _sec-development-virtual-printer:
+
+Setting up the virtual printer for debugging
+============================================
+
+OctoPrint includes, by default, a virtual printer plugin. This plugin allows you to debug OctoPrint's serial
+communication without connecting to an actual printer. Furthermore, it is possible to create certain edge conditions
+that may be hard to reproduce with a real printer.
+
+.. _sec-development-virtual-printer-enable:
+
+Enabling the virtual printer
+----------------------------
+
+The virtual printer is enabled by editing OctoPrint's config.yaml file. Details on the configuration file can
+be found in the full :ref:`config.yaml documentation `.
+
+The steps to take are as follows:
+
+* Find config.yaml in the OctoPrint settings folder. Usually in ``~/.octoprint`` on Linux, in ``%APPDATA%/OctoPrint`` on Windows and in ``~/Library/Application Support/OctoPrint`` on MacOS.
+* Add or extend the ``devel`` section with:
+
+.. code-block:: yaml
+
+ devel:
+ virtualPrinter:
+ enabled: true
+
+* Restart OctoPrint.
+* In the connection panel, a new option will appear in the Serial Port dropdown labeled ``VIRTUAL``.
+* Select this option and click ``connect``.
+* The virtual printer is now active.
+
+.. _sec-development-virtual-printer-config:
+
+Virtual printer configuration options
+-------------------------------------
+
+The config.yaml file has many configuration options for the virtual printer that allow you to fine-tune its behavior.
+
+Please see the relevant :ref:`config.yaml section ` for the full details.
+
+.. _sec-development-virtual-printer-log:
+
+Log file
+--------
+
+Once activated, the virtual printer will log all serial communication in the ``plugin_virtual_printer_serial.log`` file
+that can be found in the OctoPrint settings folder.
+
+.. _sec-development-virtual-printer-debug:
+
+Debug commands
+--------------
+
+You can simulate certain conditions and communications through the terminal tab in OctoPrint's interface.
+
+All commands start with ``!!DEBUG:`` and are followed by the command you want to execute. For instance, sending
+``!!DEBUG:action_disconnect`` will disconnect the printer. Sending ``!!DEBUG`` without command will show a help
+message with all the available commands.
+
+Action Triggers
+...............
+
+``action_pause``
+Sends a "// action:pause" action trigger to the host.
+
+``action_resume``
+Sends a "// action:resume" action trigger to the host.
+
+``action_disconnect``
+Sends a "// action:disconnect" action trigger to the host.
+
+``action_custom [ ]``
+Sends a custom "// action:" action trigger to the host.
+
+Communication Errors
+....................
+
+``dont_answer``
+Will not acknowledge the next command.
+
+``go_awol``
+Will completely stop replying.
+
+``trigger_resend_lineno``
+Triggers a resend error with a line number mismatch
+
+``trigger_resend_checksum``
+Triggers a resend error with a checksum mismatch
+
+``drop_connection``
+Drops the serial connection
+
+``prepare_ok ``
+Will cause to be enqueued for use, will be used instead of actual "ok"
+
+Reply Timing / Sleeping
+.......................
+``sleep ``
+Sleep s
+
+``sleep_after ``
+Sleeps s after each execution of
+
+``sleep_after_next ``
+Sleeps s after execution of next
+
+Misc
+....
+
+``help``
+Show the available commands.
+
+``send ``
+Sends back
diff --git a/docs/events/index.rst b/docs/events/index.rst
index b471193f5..a97e7e385 100644
--- a/docs/events/index.rst
+++ b/docs/events/index.rst
@@ -110,6 +110,14 @@ ClientClosed
* ``remoteAddress``: the remote address (IP) of the client that disconnected
+ConnectivityChanged
+ The server's internet connectivity changed
+
+ Payload:
+
+ * ``old``: Old connectivity value (true for online, false for offline)
+ * ``new``: New connectivity value (true for online, false for offline)
+
Printer communication
---------------------
@@ -199,8 +207,8 @@ FolderAdded
Payload:
* ``storage``: the storage's identifier
- * ``path``: the folders's path within its storage location
- * ``name``: the folders's name
+ * ``path``: the folder's path within its storage location
+ * ``name``: the folder's name
.. note::
@@ -212,8 +220,8 @@ FolderRemoved
Payload:
* ``storage``: the storage's identifier
- * ``path``: the folders's path within its storage location
- * ``name``: the folders's name
+ * ``path``: the folder's path within its storage location
+ * ``name``: the folder's name
.. note::
@@ -229,7 +237,7 @@ UpdatedFiles
.. deprecated:: 1.2.0
- The ``gcode`` modification type has been superceeded by ``printables``. It is currently still available for
+ The ``gcode`` modification type has been superseded by ``printables``. It is currently still available for
reasons of backwards compatibility and will also be sent on modification of ``printables``. It will however
be removed with 1.4.0.
@@ -257,7 +265,7 @@ MetadataAnalysisFinished
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the file's origin storage location
- * ``result``: the analysis result -- this is a python object currently only available for internal use
+ * ``result``: the analysis result -- this is a Python object currently only available for internal use
.. deprecated:: 1.3.0
@@ -355,8 +363,18 @@ PrintDone
Still available for reasons of backwards compatibility. Will be removed with 1.4.0.
+PrintCancelling
+ The print is about to be cancelled.
+
+ Payload:
+
+ * ``name``: the file's name
+ * ``path``: the file's path within its storage location
+ * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
+ * ``firmwareError``: the firmware error that caused cancelling the print job, if any
+
PrintCancelled
- The print has been cancelled via the cancel button.
+ The print has been cancelled.
Payload:
@@ -477,6 +495,15 @@ PositionUpdate
* ``t``: last tool selected *through OctoPrint*
* ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint*
+ToolChange
+ A tool change command was sent to the printer. The payload contains the former current tool index and the
+ new current tool index.
+
+ Payload:
+
+ * ``old``: old tool index
+ * ``new``: new tool index
+
Timelapses
----------
diff --git a/docs/features/accesscontrol.rst b/docs/features/accesscontrol.rst
index dd59bd6b8..3207b1c42 100644
--- a/docs/features/accesscontrol.rst
+++ b/docs/features/accesscontrol.rst
@@ -39,7 +39,7 @@ Rerunning the wizard
--------------------
In case Access Control was disabled in the configuration wizard, it is
-possibly to re-run it by editing ``config.yaml`` [#f1]_ and setting ``firstRun``
+possible to re-run it by editing ``config.yaml`` [#f1]_ and setting ``firstRun``
in the ``server`` section and ``enabled`` in the ``accessControl`` section to
``true``:
diff --git a/docs/features/action_commands.rst b/docs/features/action_commands.rst
index 82591cf9e..502f068b8 100644
--- a/docs/features/action_commands.rst
+++ b/docs/features/action_commands.rst
@@ -21,16 +21,20 @@ Action commands are a feature defined for the GCODE based RepRap communication p
OctoPrint out of the box supports handling of the above mentioned commands:
+cancel
+ When this command is received from the printer, OctoPrint will cancel a current print job like if the
+ "Cancel" button had been clicked.
+
pause
- When this command is received from the printer, OctoPrint will pause streaming of a current print job just like if the
+ When this command is received from the printer, OctoPrint will pause a current print job just like if the
"Pause" button had been clicked.
resume
- When this command is received from the printer, OctoPrint will resume streaming of a current print job just like if
+ When this command is received from the printer, OctoPrint will resume a current print job just like if
the "Resume" button had been clicked.
disconnect
- When this command is Received from the printer, OctoPrint will immediately disconnect from it.
+ When this command is received from the printer, OctoPrint will immediately disconnect from it.
Support for additional commands may be added by plugins by implementing a handler for the
:ref:`octoprint.comm.protocol.action ` hook.
diff --git a/docs/features/atcommands.rst b/docs/features/atcommands.rst
new file mode 100644
index 000000000..a8ead05d2
--- /dev/null
+++ b/docs/features/atcommands.rst
@@ -0,0 +1,30 @@
+.. _sec-features-atcommands:
+
+@ Commands
+==========
+
+@ commands (also known as host commands elsewhere) are special commands you may include in GCODE files streamed
+through OctoPrint to your printer or send as part of GCODE scripts, through the Terminal Tab, the API or plugins.
+Contrary to other commands they will never be sent to the printer but instead trigger functions inside OctoPrint.
+
+They are always of the form ``@[ ]``, e.g. ``@pause`` or ``@custom_command with some parameters``.
+
+Out of the box OctoPrint supports handling of these commands starting with version 1.3.7:
+
+@cancel
+ OctoPrint will cancel the current print job like if the "Cancel" button had been clicked. This command doesn't
+ take any parameters.
+
+@abort
+ Same as ``cancel``.
+
+@pause
+ OctoPrint will pause the current print job just like if the "Pause" button had been clicked. This command doesn't
+ take any parameters.
+
+@resume
+ OctoPrint will resume the current print job just like if the "Resume" button had been clicked. This command doesn't
+ take any parameters.
+
+Support for additional commands may be added by plugins by implementing a handler for one of the
+:ref:`octoprint.comm.protocol.atcommand ` hooks.
diff --git a/docs/features/custom_controls.rst b/docs/features/custom_controls.rst
index a953617e9..f130596c1 100644
--- a/docs/features/custom_controls.rst
+++ b/docs/features/custom_controls.rst
@@ -166,6 +166,10 @@ Controls
clicked. This allows to override the direct sending of the command or commands to the printer with more
sophisticated behaviour. The JavaScript snippet is ``eval``'d and processed in a context where the control
it is part of is provided as local variable ``data`` and the ``ControlViewModel`` is available as ``self``.
+ * - ``additionalClasses``
+ - (Optional) Additional classes to apply to the button of a ``command``, ``commands``, ``script`` or ``javascript``
+ control, other than the default ``btn``. Can be used to visually style the button, e.g. set to ``btn-danger`` to
+ turn the button red.
* - ``enabled``
- (Optional) A JavaScript snippet returning either ``true`` or ``false`` determining whether the control
should be enabled or not. This allow to override the default logic for this (disabled if printer is offline
diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst
index ee3136da8..4fb891eb4 100644
--- a/docs/features/gcode_scripts.rst
+++ b/docs/features/gcode_scripts.rst
@@ -66,27 +66,44 @@ Context
All GCODE scripts have access to the following template variables through the template context:
- * ``printer_profile``: The currently selected Printer Profile, including
+ * ``printer_profile``: The currently selected :ref:`Printer Profile `, including
information such as the extruder count, the build volume size, the filament diameter etc.
- * ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!)
+ * ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!).
+ Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
+ current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no
+ position could be retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)!
+ * ``last_temperature``: Last actual and target temperature reported for all available tools and if available the
+ heated bed. This is a dictionary of key-value pairs. The keys are the indices of the available tools (``0``, ``1``,
+ ...) and ``b`` for the heated bed. The values are a dictionary consisting of ``actual`` and ``target`` keys mapped
+ to the corresponding temperature in degrees Celsius. Note that not all tools your printer has must necessarily be
+ present here, neither must the heated bed - it depends on whether OctoPrint has values for a tool or the bed. Also
+ note that ``actual`` and ``target`` might be ``None``.
* ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type``
and ``script.name`` respectively.
+ * ``plugins``: An object containing variables provided by plugins (e.g ``plugins.myplugin.myvariable``)
There are a few additional template variables available for the following specific scripts:
* ``afterPrintPaused`` and ``beforePrintResumed``
- * ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists
- of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool
- ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no position could be
- retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)!
+ * ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. See
+ ``last_position`` above for the structure to expect here.
+
+ **Please note:** This will not be available if you disable
+ "Log position on pause" under Settings > Serial > Advanced options!
+ * ``pause_temperature``: Last known temperature values when the print was paused. See ``last_temperature`` above
+ for the structure to expect here.
* ``afterPrintCancelled``
* ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled.
- Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
- current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no
- position could be retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)!
+ See ``last_position`` above for the structure to expect here.
+
+ **Please note:** This will not be available if you disable
+ "Log position on cancel" under Settings > Serial > Advanced options!
+ * ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above
+ for the structure to expect here.
+
.. warning::
@@ -130,7 +147,7 @@ Out of the box, OctoPrint defaults to the following script setup for ``afterPrin
;disable all heaters
{% snippet 'disable_hotends' %}
- [% snippet 'disable_bed' %}
+ {% snippet 'disable_bed' %}
;disable fan
M106 S0
@@ -158,6 +175,75 @@ As you can see, the ``disable_hotends`` and ``disable_bed`` snippets utilize the
extruders and set their temperature to 0, and to also set the bed temperature
to 0 if a heated bed is configured.
+.. _sec-features-gcode_scripts-examples:
+
+Examples
+--------
+
+.. _sec-features-gcode_scripts-examples-more_nifty_pause_and_resume:
+
+More nifty pause and resume
+...........................
+
+If you do not have a multi-extruder setup, aren't printing from SD and have "Log position on pause" enabled under
+Settings > Serial > Advanced options, the following ``afterPrintPaused`` and
+``beforePrintResumed`` scripts might be interesting for you. With something like them in place, OctoPrint will move your print head
+out of the way to a safe rest position (here ``G1 X0 Y0``, you might want to adjust that) on pause and move it back
+to the persisted pause position on resume, making sure to also reset the extruder and feedrate.
+
+.. code-block:: jinja
+ :caption: ``afterPrintPaused`` script
+
+ {% if pause_position.x is not none %}
+ ; relative XYZE
+ G91
+ M83
+
+ ; retract filament, move Z slightly upwards
+ G1 Z+5 E-5 F4500
+
+ ; absolute XYZE
+ M82
+ G90
+
+ ; move to a safe rest position, adjust as necessary
+ G1 X0 Y0
+ {% endif %}
+
+.. code-block:: jinja
+ :caption: ``beforePrintResumed`` script
+
+ {% if pause_position.x is not none %}
+ ; relative extruder
+ M83
+
+ ; prime nozzle
+ G1 E-5 F4500
+ G1 E5 F4500
+ G1 E5 F4500
+
+ ; absolute E
+ M82
+
+ ; absolute XYZ
+ G90
+
+ ; reset E
+ G92 E{{ pause_position.e }}
+
+ ; move back to pause position XYZ
+ G1 X{{ pause_position.x }} Y{{ pause_position.y }} Z{{ pause_position.z }} F4500
+
+ ; reset to feed rate before pause if available
+ {% if pause_position.f is not none %}G1 F{{ pause_position.f }}{% endif %}
+ {% endif %}
+
+.. warning::
+
+ As mentioned in the warning above and the description of the example itself, this will *only* work if you are
+ not printing from SD and not using multiple extruders since OctoPrint will only then be able to track the
+ necessary position data and print parameters due to firmware limitations.
+
.. seealso::
`Jinja Template Designer Documentation `_
diff --git a/docs/features/index.rst b/docs/features/index.rst
index ebbf48821..37c056f2f 100644
--- a/docs/features/index.rst
+++ b/docs/features/index.rst
@@ -15,5 +15,6 @@ Features
custom_controls.rst
gcode_scripts.rst
action_commands.rst
+ atcommands.rst
plugins.rst
safemode.rst
diff --git a/docs/features/plugins.rst b/docs/features/plugins.rst
index 2530f7817..450074713 100644
--- a/docs/features/plugins.rst
+++ b/docs/features/plugins.rst
@@ -46,7 +46,7 @@ Manual Installation
If you don't want or can't use the Plugin Manager, plugins may also be installed manually either by copying and
unpacking them into one of the configured plugin folders (regularly those are ``/plugins`` and
-``/plugins`` [#f1]_ or by installing them as regular python modules via ``pip`` [#f2]_.
+``/plugins`` [#f1]_ or by installing them as regular Python modules via ``pip`` [#f2]_.
For a plugin available on the Python Package Index (PyPi), the process is as simple as issuing a
diff --git a/docs/features/safemode.rst b/docs/features/safemode.rst
index a99cbf973..c90d30d60 100644
--- a/docs/features/safemode.rst
+++ b/docs/features/safemode.rst
@@ -16,6 +16,9 @@ Additionally, OctoPrint allows uninstalling plugins in this mode, allowing recov
a third party plugin causes the server to not start up or the web interface to not render or function
correctly anymore.
+Whenever reporting an issue with OctoPrint, please always attempt to reproduce it in safe mode as well to
+ensure it really is an issue in OctoPrint itself and now caused by one of your installed third party plugins.
+
.. _sec-features-safemode-how:
How to start OctoPrint in safe mode
@@ -23,15 +26,37 @@ How to start OctoPrint in safe mode
There exist three ways to start OctoPrint in safe mode:
- * since OctoPrint 1.3.2: by selecting "Restart OctoPrint in safe mode" from the "System" menu,
- if the "Restart OctoPrint" server command has been correctly configured (see :numref:`fig-features-safemode-systemmenu`).
- * by starting OctoPrint with the command line parameter ``--safe``, e.g. ``octoprint serve --safe``
- * by setting the option ``server.startOnceInSafeMode`` in :ref:`config.yaml `
- to ``true`` and restarting
+ * by selecting "Restart OctoPrint in safe mode" from the "System" menu,
+ if the "Restart OctoPrint" server command has been correctly configured (since OctoPrint 1.3.2,
+ see :numref:`fig-features-safemode-systemmenu`)
+ * by setting the flag ``server.startOnceInSafeMode`` in :ref:`config.yaml `
+ to ``true`` and restarting. To set this flag you have the following options:
+
+ * from command line run ``octoprint safemode`` (since OctoPrint 1.3.6)
+ * from command line run ``octoprint config set --bool server.startOnceInSafeMode true`` (fixed in OctoPrint 1.3.6)
+ * use the `Yamlpatcher Plugin `_ and enter & apply the patch
+ ``[["set", "server.startOnceInSafeMode", true]]``
+ * edit ``config.yaml`` manually with a text editor, locate the ``server`` block if it already exists or create it
+ if it doesn't and add ``startOnceInSafeMode: true`` to it:
+
+ .. code-block:: yaml
+
+ # ...
+ server:
+ startOnceInSafeMode: true
+ # ...
+
+ Please also refer to the :ref:`YAML primer `.
+ * by starting OctoPrint with the command line parameter ``--safe``, e.g. ``octoprint serve --safe`` (don't forget to
+ shutdown OctoPrint first before doing this)
The last two options will have OctoPrint enable safe mode only for the next server start - once you
restart OctoPrint again, safe mode will be disabled again.
+.. note::
+
+ **OctoPi users**: For you that's ``~/oprint/bin/octoprint`` wherever it says just ``octoprint``.
+
.. _fig-features-safemode-systemmenu:
.. figure:: ../images/features-safemode-systemmenu.png
:align: center
diff --git a/docs/images/bundledplugins-logging-settings.png b/docs/images/bundledplugins-logging-settings.png
new file mode 100644
index 000000000..c5b761246
Binary files /dev/null and b/docs/images/bundledplugins-logging-settings.png differ
diff --git a/docs/images/bundledplugins-printer_safety_check-example.png b/docs/images/bundledplugins-printer_safety_check-example.png
new file mode 100644
index 000000000..c6bac3a8e
Binary files /dev/null and b/docs/images/bundledplugins-printer_safety_check-example.png differ
diff --git a/docs/images/bundledplugins-softwareupdate-plugin-configuration.png b/docs/images/bundledplugins-softwareupdate-plugin-configuration.png
index 7d5a672cb..ba13a9973 100644
Binary files a/docs/images/bundledplugins-softwareupdate-plugin-configuration.png and b/docs/images/bundledplugins-softwareupdate-plugin-configuration.png differ
diff --git a/docs/index.rst b/docs/index.rst
index 4af930621..ac0ed3ec5 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -6,9 +6,24 @@ Welcome to OctoPrint's documentation!
:alt: The OctoPrint Logo
:align: right
-This documentation is still in the process of being migrated from
-`OctoPrint's wiki `_, so also take
-a look there!
+OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software
+and released under the `GNU Affero General Public License V3 `_.
+
+Its website can be found at `octoprint.org `_.
+
+The community forum is available at `discourse.octoprint.org `_.
+
+The FAQ can be accessed by following `faq.octoprint.org `_.
+
+The official plugin repository can be reached at `plugins.octoprint.org `_.
+
+OctoPrint's development wouldn't be possible without the `financial support by its community `_.
+If you enjoy OctoPrint, please consider becoming a regular supporter!
+
+.. note::
+
+ This documentation currently focuses primarily on developers and less on end users. If you are interested in
+ helping to change this, please get in touch `on the forum `_!
Contents
========
diff --git a/docs/jsclientlib/base.rst b/docs/jsclientlib/base.rst
index d393f27e2..63833f0dc 100644
--- a/docs/jsclientlib/base.rst
+++ b/docs/jsclientlib/base.rst
@@ -119,7 +119,7 @@
:param string method: The HTTP method to use for the request (optional)
:param string url: The URL to perform the request against (optional)
:param object data: The data to send in the request body (optional)
- :param object opts: Additonal options to use for the request (optional)
+ :param object opts: Additional options to use for the request (optional)
:returns Promise: A `jQuery Promise `_ for the request's response
.. js:function:: OctoPrintClient.get(url, opts)
@@ -417,7 +417,7 @@
Creates a custom exception class. ``name`` may be either a function in which case it will be used
as constructor for the new exception class, or a string, in which case a constructor with proper
- ``name``, ``message`` and ``stack`` attributes will be created. The class hierarchy will be propery
+ ``name``, ``message`` and ``stack`` attributes will be created. The class hierarchy will be properly
setup to subclass ``Error``.
**Example:**
diff --git a/docs/jsclientlib/files.rst b/docs/jsclientlib/files.rst
index 9c4d8233a..5ecf5ea38 100644
--- a/docs/jsclientlib/files.rst
+++ b/docs/jsclientlib/files.rst
@@ -189,7 +189,7 @@
A boolean value, specifies whether to immediately start printing the file after the upload
completes (true) or not (false, default)
userdata
- An optional object or a serialized JSON string of additional user supplised data to associate with
+ An optional object or a serialized JSON string of additional user supplied data to associate with
the uploaded file.
See :ref:`Upload file or create folder ` for more details on the file upload API and
diff --git a/docs/jsclientlib/index.rst b/docs/jsclientlib/index.rst
index d97da3bf4..cf4f20376 100644
--- a/docs/jsclientlib/index.rst
+++ b/docs/jsclientlib/index.rst
@@ -14,7 +14,7 @@ If you are using it from a web page hosted on OctoPrint as a Jinja2 template, yo
methods to embed it instead of manually entering the URL, in order to have OctoPrint take care of setting the
correct URL prefix:
-.. code-block:: html
+.. code-block:: html+jinja
-Regardless of which way you use to include the library, you'll also need to make sure you included JQuery and lodash,
+Regardless of which way you use to include the library, you'll also need to make sure you included jQuery and lodash,
because the library depends on those to be available (as ``$`` and ``_``). You can embed those like this:
-.. code-block:: html
+.. code-block:: html+jinja
@@ -45,7 +45,7 @@ number of components, make sure to at the very least include that one to be able
When you import the client library as described above, a global variable ``OctoPrint`` will become available, which is
a prepared instance of the ``OctoPrintClient`` class the library assembles from registered components. You can directly
-used that singular ``OctoPrint`` instance if you only need to talk to one OctoPrint server:
+use that singular ``OctoPrint`` instance if you only need to talk to one OctoPrint server:
.. code-block:: javascript
diff --git a/docs/jsclientlib/job.rst b/docs/jsclientlib/job.rst
index eed5ac808..834b67f70 100644
--- a/docs/jsclientlib/job.rst
+++ b/docs/jsclientlib/job.rst
@@ -64,7 +64,7 @@
.. js:function:: OctoPrintClient.job.resume(opts)
- Resumes the current job if it's currently pause, does nothing if it's running.
+ Resumes the current job if it's currently paused, does nothing if it's running.
See :ref:`Issue a job command ` for details.
diff --git a/docs/jsclientlib/languages.rst b/docs/jsclientlib/languages.rst
index 5e187525f..f13b6430b 100644
--- a/docs/jsclientlib/languages.rst
+++ b/docs/jsclientlib/languages.rst
@@ -5,7 +5,7 @@
.. note::
- All methods here require that the used API token or a the existing browser session
+ All methods here require that the used API token or the existing browser session
has admin rights.
.. js:function:: OctoPrintClient.languages.list(opts)
diff --git a/docs/jsclientlib/logs.rst b/docs/jsclientlib/logs.rst
index 41d928661..fae86fb55 100644
--- a/docs/jsclientlib/logs.rst
+++ b/docs/jsclientlib/logs.rst
@@ -3,37 +3,9 @@
:mod:`OctoPrintClient.logs`
---------------------------
-.. note::
-
- All methods here require that the used API token or a the existing browser session
- has admin rights.
-
-.. js:function:: OctoPrintClient.logs.list(opts)
-
- Retrieves a list of log files.
-
- See :ref:`Retrieve a list of available log files ` for details.
-
- :param object opts: Additional options for the request
- :returns Promise: A `jQuery Promise `_ for the request's response
-
-.. js:function:: OctoPrintClient.logs.delete(path, opts)
-
- Deletes the specified log ``path``.
-
- See :ref:`Delete a specific log file ` for details.
-
- :param string path: The path to the log file to delete
- :param object opts: Additional options for the request
- :returns Promise: A `jQuery Promise `_ for the request's response
-
-.. js:function:: OctoPrintClient.logs.download(path, opts)
-
- Downloads the specified log ``file``.
-
- See :js:func:`OctoPrint.download` for more details on the underlying library download mechanism.
-
- :param string path: The path to the log file to download
- :param object opts: Additional options for the request
- :returns Promise: A `jQuery Promise `_ for the request's response
+Log file management (and logging configuration) was moved into a bundled plugin in OctoPrint 1.3.7. Refer to
+:ref:`the Logging's plugins JS Client Library ` for the JS Client documentation.
+The former module ``OctoPrintClient.logs`` and its methods are marked as deprecated but still work for now. New
+client implementations should directly use the new module provided by the bundled plugin. Existing implementations
+should adapt their used module as soon as possible.
diff --git a/docs/jsclientlib/printer.rst b/docs/jsclientlib/printer.rst
index b4e107d45..14df29834 100644
--- a/docs/jsclientlib/printer.rst
+++ b/docs/jsclientlib/printer.rst
@@ -174,7 +174,7 @@
Sets the given temperature on the printer's heated bed (if available).
- ``target`` is expected to be a the target temperature as a float value.
+ ``target`` is expected to be the target temperature as a float value.
**Example:**
diff --git a/docs/jsclientlib/socket.rst b/docs/jsclientlib/socket.rst
index 844b845a5..6da88a1ee 100644
--- a/docs/jsclientlib/socket.rst
+++ b/docs/jsclientlib/socket.rst
@@ -85,7 +85,7 @@
.. js:function:: OctoPrintClient.socket.onRateTooHigh(measured, maximum)
Called by the socket client when the last measured round trip time was higher than the
- current upper procesisng limit, indicating that the messages are now processed slower than
+ current upper processing limit, indicating that the messages are now processed slower than
the current rate requires and a slower rate might be necessary.
Can be overwritten with custom handler methods. The default implementation will call
diff --git a/docs/jsclientlib/system.rst b/docs/jsclientlib/system.rst
index 709977141..a82b89f29 100644
--- a/docs/jsclientlib/system.rst
+++ b/docs/jsclientlib/system.rst
@@ -5,7 +5,7 @@
.. note::
- All methods here require that the used API token or a the existing browser session
+ All methods here require that the used API token or the existing browser session
has admin rights.
.. js:function:: OctoPrintClient.system.getCommands(opts)
@@ -35,4 +35,4 @@
.. seealso::
:ref:`System API `
- Documentation of the underlying system API
+ Documentation of the underlying system API.
diff --git a/docs/jsclientlib/timelapse.rst b/docs/jsclientlib/timelapse.rst
index a16b8ec9a..351483ceb 100644
--- a/docs/jsclientlib/timelapse.rst
+++ b/docs/jsclientlib/timelapse.rst
@@ -15,7 +15,7 @@
.. js:function:: OctoPrintClient.timelapse.list(opts)
- Get the lists of rendered and unrendered timelapses. The returned promis
+ Get the lists of rendered and unrendered timelapses. The returned promise
will be resolved with an object containing the properties ``rendered``
which will have the list of rendered timelapses, and ``unrendered`` which
will have the list of unrendered timelapses.
diff --git a/docs/jsclientlib/users.rst b/docs/jsclientlib/users.rst
index a07ac7cf9..dd11adb19 100644
--- a/docs/jsclientlib/users.rst
+++ b/docs/jsclientlib/users.rst
@@ -5,7 +5,7 @@
.. note::
- Most methods here require that the used API token or a the existing browser session
+ Most methods here require that the used API token or the existing browser session
has admin rights *or* corresponds to the user to be modified. Some methods
definitely require admin rights.
diff --git a/docs/jsclientlib/util.rst b/docs/jsclientlib/util.rst
index 6168e1af5..f88062ee7 100644
--- a/docs/jsclientlib/util.rst
+++ b/docs/jsclientlib/util.rst
@@ -5,7 +5,7 @@
.. note::
- All methods here require that the used API token or a the existing browser session
+ All methods here require that the used API token or the existing browser session
has admin rights.
.. js:function:: OctoPrintClient.util.test(command, parameters, opts)
@@ -21,7 +21,7 @@
.. js:function:: OctoPrintClient.util.testPath(path, additional, opts)
- Test the provided ``path`` for existance. More test criteria supported by the :ref:`path test command `
+ Test the provided ``path`` for existence. More test criteria supported by the :ref:`path test command `
can be provided via the ``additional`` object.
**Example 1**
@@ -126,8 +126,16 @@
.done(function(response) {
if (response.result) {
// check passed
+ var content = response.response.content;
+ var mimeType = "image/jpeg";
+
+ var headers = response.response.headers;
+ if (headers && headers["content-type"]) {
+ mimeType = headers["content-type"].split(";")[0];
+ }
+
var image = $("#someimage");
- image.
+ image.src = "data:" + mimeType + ";base64," + content;
} else {
// check failed
}
@@ -153,7 +161,49 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise `_ for the request's response
+.. js:function:: OctoPrintClient.util.testServer(host, port, additional, opts)
+
+ Test if a server is reachable. More options supported by the :ref:`server test command `
+ can be provided via the ``additional`` object.
+
+ **Example 1**
+
+ Test if ``8.8.8.8`` is reachable on port 53 within the default timeout.
+
+ .. code-block:: javascript
+
+ OctoPrint.util.testServer("8.8.8.8", 53)
+ .done(function(response) {
+ if (response.result) {
+ // check passed
+ } else {
+ // check failed
+ }
+ });
+
+ **Example 2**
+
+ Test if ``127.0.0.1`` is reachable on port 1234 and UDP.
+
+ .. code-block:: javascript
+
+ OctoPrint.util.testUrl("127.0.0.1", 1234, {"protocol": "udp"})
+ .done(function(response) {
+ if (response.result) {
+ // check passed
+ } else {
+ // check failed
+ }
+ });
+
+
+ :param string url: Host to test
+ :param int port: Port to test
+ :param object additional: Additional parameters for the test command
+ :param object opts: Additional options for the request
+ :returns Promise: A `jQuery Promise `_ for the request's response
+
.. seealso::
:ref:`Util API `
- Documentation of the underlying util API
+ Documentation of the underlying util API.
diff --git a/docs/jsclientlib/wizard.rst b/docs/jsclientlib/wizard.rst
index 12a0cad25..90de044d0 100644
--- a/docs/jsclientlib/wizard.rst
+++ b/docs/jsclientlib/wizard.rst
@@ -5,7 +5,7 @@
.. note::
- All methods here require that the used API token or a the existing browser session
+ All methods here require that the used API token or the existing browser session
has admin rights.
.. js:function:: OctoPrintClient.wizard.get(opts)
diff --git a/docs/modules/index.rst b/docs/modules/index.rst
index 1cdb36a0a..0f67513b7 100644
--- a/docs/modules/index.rst
+++ b/docs/modules/index.rst
@@ -14,4 +14,5 @@ Internal Modules
server.rst
settings.rst
slicing.rst
+ users.rst
util.rst
diff --git a/docs/modules/printer.rst b/docs/modules/printer.rst
index ce752f431..5fcd54ae4 100644
--- a/docs/modules/printer.rst
+++ b/docs/modules/printer.rst
@@ -4,3 +4,10 @@ octoprint.printer
-----------------
.. automodule:: octoprint.printer
+
+.. _sec-modules-printer-profile:
+
+octoprint.printer.profile
+-------------------------
+
+.. automodule:: octoprint.printer.profile
diff --git a/docs/modules/users.rst b/docs/modules/users.rst
new file mode 100644
index 000000000..f147a46a3
--- /dev/null
+++ b/docs/modules/users.rst
@@ -0,0 +1,9 @@
+.. _sec-modules-users:
+
+octoprint.users
+---------------
+
+.. automodule:: octoprint.users
+ :members:
+
+
diff --git a/docs/plugins/concepts.rst b/docs/plugins/concepts.rst
index ceaf3acaa..5e1c624cf 100644
--- a/docs/plugins/concepts.rst
+++ b/docs/plugins/concepts.rst
@@ -23,9 +23,9 @@ Lifecycle
There are three sources of installed plugins that OctoPrint will check during start up:
- * it's own ``octoprint/plugins`` folder (this is where the bundled plugins reside),
+ * its own ``octoprint/plugins`` folder (this is where the bundled plugins reside),
* the ``plugins`` folder in its configuration directory (e.g. ``~/.octoprint/plugins`` on Linux),
- * any python packages registered for the entry point ``octoprint.plugin``.
+ * any Python packages registered for the entry point ``octoprint.plugin``.
Each plugin that OctoPrint finds it will first load, then enable. On enabling a plugin, OctoPrint will
register its declared :ref:`hook handlers ` and :ref:`helpers `, apply
@@ -36,7 +36,7 @@ any :ref:`settings overlays .py
``~/.octoprint/plugins`` folder. You already know how that works. But let's say you have more than just a simple plugin
that can be done in one file. Distributing multiple files and getting your users to install them in the right way
so that OctoPrint will be able to actually find and load them is certainly not impossible, but we want to do it in the
-best way possible, meaning we want to make our plugin a fully installable python module that your users will be able to
+best way possible, meaning we want to make our plugin a fully installable Python module that your users will be able to
install directly via `OctoPrint's built-in Plugin Manager `_
or alternatively manually utilizing Python's standard package manager ``pip`` directly.
-So let's begin. We'll use the `cookiecutter `_ template for OctoPrint plugins here,
-so we'll first need to install that::
+So let's begin. We'll use the `cookiecutter `_ template for OctoPrint plugins
+here. This should already be installed if you used the ``plugins`` extra while installing OctoPrint. However,
+you may install it with::
- (venv) $ pip install cookiecutter
+ (venv) $ pip install "cookiecutter>=1.4,<1.7"
Then we can use the ``octoprint dev plugin:new`` command [#f1]_ to generate a new OctoPrint plugin skeleton for us::
@@ -281,7 +282,7 @@ of information now defined twice:
plugin_version = "1.0.0"
plugin_description = "A quick \"Hello World\" example plugin for OctoPrint"
-The nice thing about our plugin now being a proper python package is that OctoPrint can and will access the metadata defined
+The nice thing about our plugin now being a proper Python package is that OctoPrint can and will access the metadata defined
within ``setup.py``! So, we don't really need to define all this data twice. Remove ``__plugin_name__``, ``__plugin_version__``
and ``__plugin_description__`` from ``__init__.py``:
@@ -409,8 +410,8 @@ Now look at that!
Settings Galore: How to make parts of your plugin user adjustable
-----------------------------------------------------------------
-Remember that Wikipedia link we added to our little link in the navigation bar? It links to the english Wikipedia. But
-what if we want to allow our users to adjust that according to their wishes, e.g. to link to the german language node
+Remember that Wikipedia link we added to our little link in the navigation bar? It links to the English Wikipedia. But
+what if we want to allow our users to adjust that according to their wishes, e.g. to link to the German language node
about "Hello World" programs instead?
To allow your users to customized the behaviour of your plugin you'll need to implement the :class:`~octoprint.plugin.SettingsPlugin`
@@ -508,7 +509,7 @@ section doesn't yet exist in the file, create it):
# [...]
Restart OctoPrint. Not only should the URL displayed in the log file have changed, but also the link should now (after
-a proper shift-reload) point to the german Wikipedia node about "Hello World" programs::
+a proper shift-reload) point to the German Wikipedia node about "Hello World" programs::
2015-01-30 11:47:18,634 - octoprint.plugins.helloworld - INFO - Hello World! (more: https://de.wikipedia.org/wiki/Hallo-Welt-Programm)
@@ -819,12 +820,10 @@ Put something like the following into ``helloworld.css``:
.. code-block:: css
:linenos:
- #tab_plugin_helloworld {
- iframe {
- width: 100%;
- height: 600px;
- border: 1px solid #808080;
- }
+ #tab_plugin_helloworld iframe {
+ width: 100%;
+ height: 600px;
+ border: 1px solid #808080;
}
Don't forget to remove the ``style`` attribute from the ``iframe`` tag in ``helloworld_tab.jinja2``:
diff --git a/docs/plugins/helpers.rst b/docs/plugins/helpers.rst
index 17cd18289..c411d3776 100644
--- a/docs/plugins/helpers.rst
+++ b/docs/plugins/helpers.rst
@@ -8,7 +8,7 @@ system. They are registered with the OctoPrint plugin system through the use of
An example for providing some helper functions to the system can be found in the
`Discovery Plugin `_,
-which provides it's SSDP browsing and Zeroconf browsing and publishing functions as helper methods.
+which provides its SSDP browsing and Zeroconf browsing and publishing functions as helper methods.
.. code-block:: python
:linenos:
diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst
index 93bd3f108..7126bf60a 100644
--- a/docs/plugins/hooks.rst
+++ b/docs/plugins/hooks.rst
@@ -66,7 +66,7 @@ the general type of script for which to look for additions ("gcode") and the scr
return a 2-tuple of prefix and postfix if has something for either of those, otherwise ``None``. OctoPrint will then take
care to add prefix and suffix as necessary after a small round of preprocessing.
-Plugins can easily add their own hooks too. For example, the `Software Update Plugin `_
+Plugins can easily add their own hooks too. For example, the `Software Update Plugin `_
declares a custom hook "octoprint.plugin.softwareupdate.check_config" which other plugins can add handlers for in order
to register themselves with the Software Update Plugin by returning their own update check configuration.
@@ -79,7 +79,7 @@ property instead, manually instantiate your implementation instance and then add
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_action_command.py
:linenos:
:tab-width: 4
- :caption: `custom_action_command.py `_
+ :caption: `custom_action_command.py `__
:name: sec-plugin-concepts-hooks-example
.. _sec-plugins-hooks-ordering:
@@ -226,6 +226,37 @@ octoprint.accesscontrol.appkey
:return: A list of 3-tuples as described above
:rtype: list
+.. _sec-plugins-hook-accesscontrol-keyvalidator:
+
+octoprint.accesscontrol.keyvalidator
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. py:function:: acl_keyvalidator_hook(apikey, *args, **kwargs)
+
+ Via this hook plugins may validate their own customized API keys to be used to access OctoPrint's API.
+
+ ``apikey`` will be the API key as read from the request headers.
+
+ Hook handlers are expected to return a :class:`~octoprint.users.User` instance here that will then be considered that
+ user making the request. By returning ``None`` or nothing at all, hook handlers signal that they do not handle the
+ provided key.
+
+ **Example:**
+
+ Allows using a user's id as their API key (for obvious reasons this is NOT recommended in production environments
+ and merely provided for educational purposes):
+
+ .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_keyvalidator.py
+ :linenos:
+ :tab-width: 4
+ :caption: `custom_keyvalidator.py `_
+
+ .. versionadded:: 1.3.6
+
+ :param str apikey: The API key to validate
+ :return: The user in whose name the request will be processed further
+ :rtype: :class:`~octoprint.users.User`
+
.. _sec-plugins-hook-cli-commands:
octoprint.cli.commands
@@ -370,13 +401,52 @@ octoprint.comm.protocol.action
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_action_command.py
:linenos:
:tab-width: 4
- :caption: `custom_action_command.py `_
+ :caption: `custom_action_command.py `__
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
:param str line: The complete line as received from the printer, format ``// action:``
:param str action: The parsed out action command, so for a ``line`` like ``// action:some_command`` this will be
``some_command``
+.. _sec-plugins-hook-comm-protocol-atcommand-phase:
+
+octoprint.comm.protocol.atcommand.
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+This describes actually two hooks:
+
+ * ``octoprint.comm.protocol.atcommand.queuing``
+ * ``octoprint.comm.protocol.atcommand.sending``
+
+.. py:function:: protocol_atcommandphase_hook(comm_instance, phase, command, parameters, tags=None, *args, **kwargs)
+
+ Trigger on :ref:`@ commands ` as they progress through the ``queuing`` and ``sending``
+ phases of the comm layer. See :ref:`the gcode phase hook ` for a
+ detailed description of each of these phases.
+
+ Hook handlers may use this to react to arbitrary :ref:`@ commands ` included in GCODE files
+ streamed to the printer or sent as part of GCODE scripts, through the API or plugins.
+
+ Please note that these hooks do not allow to rewrite, suppress or expand @ commands, they are merely callbacks to
+ trigger the *actual execution* of whatever functionality lies behind a given @ command, similar to
+ :ref:`the action command hook `.
+
+ **Example**
+
+ Pause the print on ``@wait`` (this mirrors the implementation of the built-in ``@pause`` command, just with a
+ different name).
+
+ .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_atcommand.py
+ :linenos:
+ :tab-width: 4
+ :caption: `custom_action_command.py `__
+
+ :param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
+ :param str phase: The current phase in the command progression, either ``queuing`` or ``sending``. Will always
+ match the ```` of the hook.
+ :param str cmd: The @ command without the leading @
+ :param str parameters: Any parameters provided to the @ command. If none were provided this will be an empty string.
+
.. _sec-plugins-hook-comm-protocol-gcode-phase:
octoprint.comm.protocol.gcode.
@@ -389,7 +459,7 @@ This describes actually four hooks:
* ``octoprint.comm.protocol.gcode.sending``
* ``octoprint.comm.protocol.gcode.sent``
-.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs)
+.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs)
Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases
are the following:
@@ -412,7 +482,39 @@ This describes actually four hooks:
the communication layer or before they are actually sent over the serial port, or to react to the queuing or sending
of commands after the fact. The hook handler will be called with the processing ``phase``, the ``cmd`` to be sent to
the printer as well as the ``cmd_type`` parameter used for enqueuing (OctoPrint will make sure that the send queue
- will never contain more than one line with the same ``cmd_type``) and the detected gcode command (if it is one).
+ will never contain more than one line with the same ``cmd_type``) and the detected ``gcode`` command (if it is one)
+ as well as its ``subcode`` (if it has one). OctoPrint will also provide any ``tags`` attached to the command throughout
+ its lifecycle.
+
+ Tags are arbitrary strings that can be attached to a command as it moves through the various phases and can be used to e.g.
+ distinguish between commands that originated in a printed file (``source:file``) vs. a configured GCODE script
+ (``source:script``) vs. an API call (``source:api``) vs. a plugin (``source:plugin`` or ``source:rewrite`` and
+ ``plugin:``). If during development you want to get an idea of the various possible tags, set
+ the logger ``octoprint.util.comm.command_phases`` to ``DEBUG``, connect to a printer (real or virtual) and take a
+ look at your ``octoprint.log`` during serial traffic:
+
+ .. code-block:: none
+
+ 2018-02-16 18:20:31,213 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ]
+ 2018-02-16 18:20:31,216 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: M117 Before T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
+ 2018-02-16 18:20:31,217 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: M117 Before T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
+ 2018-02-16 18:20:31,217 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ]
+ 2018-02-16 18:20:31,219 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: M117 After T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
+ 2018-02-16 18:20:31,220 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: M117 Before T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
+ 2018-02-16 18:20:31,230 - tornado.access - INFO - 204 POST /api/printer/command (127.0.0.1) 23.00ms
+ 2018-02-16 18:20:31,232 - tornado.access - INFO - 200 POST /api/printer/command (127.0.0.1) 25.00ms
+ 2018-02-16 18:20:31,232 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ]
+ 2018-02-16 18:20:31,234 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ]
+ 2018-02-16 18:20:31,242 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: M117 After T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
+ 2018-02-16 18:20:31,243 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: M117 After T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ]
+ 2018-02-16 18:20:38,552 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
+ 2018-02-16 18:20:38,552 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
+ 2018-02-16 18:20:38,553 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
+ 2018-02-16 18:20:38,553 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: G1 X10 F6000 | gcode: G1 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
+ 2018-02-16 18:20:38,555 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: G1 X10 F6000 | gcode: G1 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
+ 2018-02-16 18:20:38,556 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
+ 2018-02-16 18:20:38,556 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: G90 | gcode: G90 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
+ 2018-02-16 18:20:38,558 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: G90 | gcode: G90 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ]
Defining a ``cmd_type`` other than None will make sure OctoPrint takes care of only having one command of that type
in its sending queue. Predefined types are ``temperature_poll`` for temperature polling via ``M105`` and
@@ -426,7 +528,7 @@ This describes actually four hooks:
* ``None``: Don't change anything. Note that Python functions will also automatically return ``None`` if
an empty ``return`` statement is used or just nothing is returned explicitly from the handler. Hence, the following
- examples are all falling into this category:
+ examples are all falling into this category and equivalent:
.. code-block:: python
@@ -451,18 +553,26 @@ This describes actually four hooks:
should use this option.
* A 2-tuple consisting of a rewritten version of the ``cmd`` and the ``cmd_type``, e.g. ``return "M105", "temperature_poll"``.
Handlers which wish to rewrite both the command and the command type should use this option.
- * **``queuing`` phase only**: A list of any of the above to allow for expanding one command into
+ * A 3-tuple consisting of a rewritten version of the ``cmd``, the ``cmd_type`` and any additional ``tags`` you might
+ want to attach to the lifecycle of the command in a set, e.g. ``return "M105", "temperature_poll", {"my_custom_tag"}``
+ * **"queuing" phase only**: A list of any of the above to allow for expanding one command into
many. The following example shows how any queued command could be turned into a sequence of a temperature query,
line number reset, display of the ``gcode`` on the printer's display and finally the actual command (this example
- does not make a lot of sense to be quiet honest):
+ does not make a lot of sense to be quite honest):
.. code-block:: python
- def multi_expansion(*args, **kwargs):
- return [("M105", "temperature_poll"),
- ("M110",),
- "M117 GCODE: {}".format(gcode),
- (command, command_type)]
+ def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None *args, **kwargs):
+ if gcode or not cmd.startswith("@foo"):
+ return
+
+ return [("M105", "temperature_poll"), # 2-tuple, command & command type
+ ("M110",), # 1-tuple, just the command
+ "M117 echo foo: {}".format(cmd)] # string, just the command
+
+ __plugin_hooks__ = {
+ "octoprint.comm.protocol.gcode.queuing": rewrite_foo
+ }
Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type``
to one already in the queue will give an error.
@@ -485,6 +595,9 @@ This describes actually four hooks:
:param str cmd_type: Type of command, e.g. ``temperature_poll`` for temperature polling or ``sd_status_poll`` for SD
printing status polling.
:param str gcode: Parsed GCODE command, e.g. ``G0`` or ``M110``, may also be None if no known command could be parsed
+ :param str subcode: Parsed subcode of the GCODE command, e.g. ``1`` for ``M80.1``. Will be None if no subcode was provided
+ or no command could be parsed.
+ :param tags: Tags attached to the command
:return: None, 1-tuple, 2-tuple or string, see the description above for details.
.. _sec-plugins-hook-comm-protocol-gcode-received:
@@ -495,7 +608,7 @@ octoprint.comm.protocol.gcode.received
.. py:function:: gcode_received_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
+ version of it. If 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 explicitly from the handler.
@@ -513,6 +626,36 @@ octoprint.comm.protocol.gcode.received
:return: The received line or in any case, a modified version of it.
:rtype: str
+.. _sec-plugins-hook-comm-protocol-gcode-error:
+
+octoprint.comm.protocol.gcode.error
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. py:function:: gcode_error_hook(comm_instance, error_message, *args, **kwargs)
+
+ Get the messages of any errors messages sent by the printer, with the leading ``Error:`` or ``!!`` already
+ stripped. Handlers should return True if they handled that error internally and it should not be processed by
+ the system further. Normal processing of these kinds of errors - depending on the configuration of error
+ handling - involves canceling the ongoing print and possibly also disconnecting.
+
+ Plugins might utilize this hook to handle errors generated by the printer that are recoverable in one way or
+ the other and should not trigger the normal handling that assumes the worst.
+
+ **Example:**
+
+ Looks for error messages containing "fan error" or "bed missing" (ignoring case) and marks them as handled by the
+ plugin.
+
+ .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/comm_error_handler_test.py
+ :linenos:
+ :tab-width: 4
+ :caption: `comm_error_handler_test.py `_
+
+ :param MachineCom comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
+ :param str error_message: The error message received from the printer.
+ :return: True if the error was handled in the plugin and should not be processed further, False (or None) otherwise.
+ :rtype: bool
+
.. _sec-plugins-hook-comm-protocol-scripts:
octoprint.comm.protocol.scripts
@@ -520,19 +663,19 @@ octoprint.comm.protocol.scripts
.. py:function:: protocol_scripts_hook(comm_instance, script_type, script_name, *args, **kwargs)
- Return a prefix to prepend and a postfix to append to the script ``script_name`` of type ``type``. Handlers should
+ Return a prefix to prepend, postfix to append, and optionally a dictionary of variables to provide to the script ``script_name`` of type ``type``. Handlers should
make sure to only proceed with returning additional scripts if the ``script_type`` and ``script_name`` match
handled scripts. If not, None should be returned directly.
- If the hook handler has something to add to the specified script, it may return a 2-tuple, with the first entry
- defining the prefix (what to *prepend* to the script in question) and the last entry defining the postfix (what to
- *append* to the script in question). Both prefix and postfix can be None to signify that nothing should be prepended
+ If the hook handler has something to add to the specified script, it may return a 2-tuple or a 3-tuple with the first entry
+ defining the prefix (what to *prepend* to the script in question), the second entry defining the postfix (what to
+ *append* to the script in question), and finally if desired a dictionary of variables to be made available to the script. Both prefix and postfix can be None to signify that nothing should be prepended
respectively appended.
- The returned entries may be either iterables of script lines or a string including newlines of the script lines (which
+ The returned prefix and postfix entries may be either iterables of script lines or a string including newlines of the script lines (which
will be split by the caller if necessary).
- **Example:**
+ **Example 1:**
Appends an ``M117 OctoPrint connected`` to the configured ``afterPrinterConnected`` GCODE script.
@@ -541,12 +684,47 @@ octoprint.comm.protocol.scripts
:tab-width: 4
:caption: `message_on_connect.py `_
+ **Example 2:**
+
+ Provides the variable ``myvariable`` to the configured ``beforePrintStarted`` GCODE script.
+
+ .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/gcode_script_variables.py
+ :linenos:
+ :tab-width: 4
+ :caption: `gcode_script_variables.py `_
+
:param MachineCom comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
:param str script_type: The type of the script for which the hook was called, currently only "gcode" is supported here.
:param str script_name: The name of the script for which the hook was called.
- :return: A 2-tuple in the form ``(prefix, postfix)`` or None
+ :return: A 2-tuple in the form ``(prefix, postfix)``, 3-tuple in the form ``(prefix, postfix, variables)``, or None
:rtype: tuple or None
+.. _sec-plugins-hook-comm-protocol-temperatures-received:
+
+octoprint.comm.protocol.temperatures.received
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. py:function:: protocol_temperatures_received_hook(comm_instance, parsed_temperatures, *args, **kwargs)
+
+ Get the parsed temperatures returned by the printer, allowing handlers to modify them prior to handing them off
+ to the system. Handlers are expected to either return ``parsed_temperatures`` as-is or a modified copy thereof.
+
+ ``parsed_temperatures`` is a dictionary mapping from tool/bed identifier (``B``, ``T0``, ``T1``) to a 2-tuple of
+ actual and target temperature, e.g. ``{'B': (45.2, 50.0), 'T0': (178.9, 210.0), 'T1': (21.3, 0.0)}``.
+
+ This hook can be useful in cases where a printer e.g. is prone to returning garbage data from time to time, allowing
+ additional sanity checking to be applied and invalid values to be filtered out. If a handler returns an empty
+ dictionary or ``None``, no further processing will take place.
+
+ **Example**
+
+ The following example shows how to filter out actual temperatures that are outside a sane range of 1°C to 300°C.
+
+ .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/sanitize_temperatures.py
+ :linenos:
+ :tab-width: 4
+ :caption: `sanitize_temperatures.py `_
+
.. _sec-plugins-hook-comm-transport-serial-factory:
octoprint.comm.transport.serial.factory
@@ -673,7 +851,7 @@ octoprint.filemanager.preprocessor
``file_object`` will be a subclass of :class:`~octoprint.filemanager.util.AbstractFileWrapper`. Handlers may
access the raw data of the file via :func:`~octoprint.filemanager.util.AbstractFileWrapper.stream`, e.g.
- to wrap it further. Handlers which do not wish to handle the `file_object`
+ to wrap it further. Handlers which do not wish to handle the `file_object` should just return it untouched.
**Example**
@@ -718,7 +896,7 @@ octoprint.printer.factory
If the factory returns anything but ``None``, it will be assigned to the global ``printer`` instance.
- If no of the registered factories return a printer instance, the default :class:`~octoprint.printer.standard.Printer`
+ If none of the registered factories return a printer instance, the default :class:`~octoprint.printer.standard.Printer`
class will be instantiated.
:param dict components: System components to use for printer instance initialization
@@ -820,7 +998,7 @@ octoprint.server.http.routes
that allows delivery of the requested resource as attachment and access validation through an optional callback.
:class:`~octoprint.server.util.tornado.UrlForwardHandler`
`tornado.web.RequestHandler `_ that proxies
- requests to a preconfigured url and returns the response.
+ requests to a preconfigured URL and returns the response.
:param list server_routes: read-only list of the currently configured server routes
:return: a list of 3-tuples with additional routes as defined above
@@ -939,6 +1117,41 @@ octoprint.ui.web.templatetypes
:return: a list of 3-tuples (template type, rule, sorting spec)
:rtype: list
+.. _sec-plugins-hook-users-factory:
+
+octoprint.users.factory
+~~~~~~~~~~~~~~~~~~~~~~~
+
+.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs)
+
+ Return a :class:`~octoprint.users.UserManager` instance to use as global user manager object. This will
+ be called only once during initial server startup.
+
+ The provided ``components`` is a dictionary containing the already initialized system components:
+
+ * ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager`
+ * ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager`
+ * ``event_bus``: The :class:`~octoprint.events.EventManager`
+ * ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue`
+ * ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager`
+ * ``file_manager``: The :class:`~octoprint.filemanager.FileManager`
+ * ``app_session_manager``: The :class:`~octoprint.server.util.flask.AppSessionManager`
+ * ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager`
+ * ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache`
+
+ If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance.
+
+ If none of the registered factories return a user manager instance, the class referenced by the ``config.yaml``
+ entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock
+ :class:`~octoprint.users.FilebasedUserManager` will be instantiated, linked to the default user storage
+ file ``~/.octoprint/users.yaml``.
+
+ :param dict components: System components to use for user manager instance initialization
+ :param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary
+ :return: The ``userManager`` instance to use globally.
+ :rtype: UserManager subclass or None
+
+
.. _sec-plugins-hook-timelapse-capture-pre:
octoprint.timelapse.capture.pre
@@ -969,4 +1182,4 @@ octoprint.timelapse.capture.post
:param str filename: The path of the frame that should have been saved.
:param boolean success: Indicates whether the capture was successful or not.
:return: None
- :rtype: None
\ No newline at end of file
+ :rtype: None
diff --git a/docs/plugins/injectedproperties.rst b/docs/plugins/injectedproperties.rst
index 4fbf2a3bc..7b4bf311a 100644
--- a/docs/plugins/injectedproperties.rst
+++ b/docs/plugins/injectedproperties.rst
@@ -45,11 +45,13 @@ An overview of these properties follows.
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`.
+``self._connectivity_checker``
+ OctoPrint's connectivity checker, an instance of :class:`octoprint.util.ConnectivityChecker`.
.. seealso::
:class:`~octoprint.plugin.core.Plugin` and :class:`~octoprint.plugin.types.OctoPrintPlugin`
- Class documentation also containing the properties shared among all mixing implementations.
+ Class documentation also containing the properties shared among all mixin implementations.
:ref:`Available Mixins `
Some mixin types trigger the injection of additional properties.
diff --git a/docs/plugins/mixins.rst b/docs/plugins/mixins.rst
index 95bf3e5cf..fa73c1757 100644
--- a/docs/plugins/mixins.rst
+++ b/docs/plugins/mixins.rst
@@ -153,7 +153,7 @@ An overview of these properties can be found in the section :ref:`Injected Prope
.. seealso::
:class:`~octoprint.plugin.core.Plugin` and :class:`~octoprint.plugin.types.OctoPrintPlugin`
- Class documentation also containing the properties shared among all mixing implementations.
+ Class documentation also containing the properties shared among all mixin implementations.
.. _sec-plugins-mixins-available:
diff --git a/docs/plugins/viewmodels.rst b/docs/plugins/viewmodels.rst
index f389ce5ce..a5fc5bd46 100644
--- a/docs/plugins/viewmodels.rst
+++ b/docs/plugins/viewmodels.rst
@@ -56,9 +56,9 @@ Example:
// more of your view model's implementation
}
- // we don't explicitely declare a name property here
+ // we don't explicitly declare a name property here
// our view model will be registered under "myCustomViewModel" (implicit
- // name derived from contructor name) and "yourCustomViewModel" (explicitely
+ // name derived from constructor name) and "yourCustomViewModel" (explicitly
// provided as additional name)
OCTOPRINT_VIEWMODELS.push({
construct: MyCustomViewModel,
@@ -125,7 +125,7 @@ gcodeFilesViewModel
logViewModel
View model for the logfile settings dialog.
loginStateViewModel
- View model for the current loginstate of the user, very interesting for plugins that need to
+ View model for the current login state of the user, very interesting for plugins that need to
evaluate the current login state or information about the current user, e.g. associated roles.
navigationViewModel
View model for the navigation bar.
@@ -168,7 +168,7 @@ OctoPrint's web application will call several callbacks on all registered view m
Those are listed below:
onStartup()
- Called when the first initialization has been done: All view models are constructed and hence their dependencies
+ Called when the first initialization has been done. All view models are constructed and hence their dependencies
resolved, no bindings have been done yet.
onBeforeBinding()
@@ -210,7 +210,7 @@ onDataUpdaterPluginMessage(plugin, message)
Called when a plugin message is pushed from the server with the identifier of the calling plugin as first
and the actual message as the second parameter. Note that the latter might be a full fledged object, depending
on the plugin sending the message. You can use this method to asynchronously push data from your plugin's server
- component to it's frontend component.
+ component to its frontend component.
onUserLoggedIn(user)
Called when a user gets logged into the web app, either passively (upon initial load of the page due to a valid
@@ -220,6 +220,11 @@ onUserLoggedIn(user)
onUserLoggedOut()
Called when a user gets logged out of the web app.
+onUserPermissionsChanged(user)
+ Called when a change in the permissions of the current user is detected. The user data of the just logged in user
+ will be provided as only parameter. Note that this may also be triggered for not logged in guests if the guest
+ group is modified. In this case ``user`` will be undefined.
+
onTabChange(next, current)
Called before the main tab view switches to a new tab, so `before` the new tab becomes visible. Called with the
next (changed to) and current (still visible) tab's hash (e.g. ``#control``). Note that ``current`` might be undefined
@@ -299,6 +304,138 @@ on your view model, taking a list of all bound view models:
});
})
+.. _sec-plugins-viewmodels-livecycle:
+
+Lifecycle diagrams
+------------------
+
+.. _sec-plugins-viewmodels-startup:
+
+Web interface startup
+~~~~~~~~~~~~~~~~~~~~~
+
+.. mermaid::
+
+ sequenceDiagram
+ participant Main
+ participant DataUpdater
+ participant LoginStateViewModel
+ participant SettingsViewModel
+ participant UiStateViewModel
+
+ Note over DataUpdater: connectCallback = undefined
+ Note over UiStateViewModel: loaded = false
+
+ activate Main
+
+ Main->>+DataUpdater: connect
+ Note right of DataUpdater: initialized = false
+ DataUpdater-->>Main: ok
+ deactivate Main
+ DataUpdater->>DataUpdater: asynchronous connect to server...
+ activate DataUpdater
+ Note right of DataUpdater: store any callbacks instead of triggering (e.g. onServerConnect, fromHistoryData, fromCurrentData, ...)
+ DataUpdater-X+Main: done
+ deactivate DataUpdater
+ deactivate DataUpdater
+
+ Main->>+DataUpdater: connectCallback = onServerConnect
+ Note right of DataUpdater: connectCallback = onServerConnect
+ DataUpdater-->>-Main: ok
+ Main->>+Main: onServerConnect
+ Main->>+LoginStateViewModel: passiveLogin
+ LoginStateViewModel-->>Main: ok
+ Main-->>Main: ok
+ deactivate Main
+ deactivate Main
+
+ LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
+ Note over Main,UiStateViewModel: Session available!
+ LoginStateViewModel-X+Main: done
+ deactivate LoginStateViewModel
+ deactivate LoginStateViewModel
+
+ Main->>+DataUpdater: initialized
+ Note right of DataUpdater: initialized = true
+ DataUpdater->DataUpdater: trigger stored callbacks
+ DataUpdater-->>-Main: ok
+
+ Main->>+Main: fetchSettings
+ Note right of Main: trigger onStartup
+
+ Main->>+SettingsViewModel: requestData
+ SettingsViewModel-->>Main: ok
+ deactivate Main
+ deactivate Main
+
+ SettingsViewModel->>+SettingsViewModel: asynchronous settings fetch
+ Note over Main,UiStateViewModel: Settings available!
+ SettingsViewModel-X+Main: done
+ deactivate SettingsViewModel
+ deactivate SettingsViewModel
+
+ Main->>+Main: bindViewModels
+
+ loop for each view model
+ Main->Main: trigger onBeforeBinding
+ Main->Main: trigger onBoundTo
+ Main->Main: trigger onAfterBinding
+ end
+
+ Main->Main: trigger onAllBound
+ opt User is logged in
+ Main->>+LoginStateViewModel: onAllBound
+ LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
+ LoginStateViewModel-->>-Main: ok
+ end
+
+ Main->>+UiStateViewModel: loaded
+ Note right of UiStateViewModel: loaded = true
+ UiStateViewModel-->>-Main: ok
+
+ Main->Main: trigger onStartupComplete
+ deactivate Main
+ deactivate Main
+
+
+.. _sec-plugins-viewmodels-reconnect:
+
+Web interface reconnect
+~~~~~~~~~~~~~~~~~~~~~~~
+
+.. mermaid::
+
+ sequenceDiagram
+ participant onServerConnect
+ participant DataUpdater
+ participant LoginStateViewModel
+
+ activate DataUpdater
+ DataUpdater->>DataUpdater: call connectCallback
+ DataUpdater->>+onServerConnect: call
+ onServerConnect-->>DataUpdater: ok
+ deactivate DataUpdater
+
+ onServerConnect->>+LoginStateViewModel: passiveLogin
+ LoginStateViewModel-->>onServerConnect: ok
+ deactivate onServerConnect
+ LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
+ Note over onServerConnect,LoginStateViewModel: Session available!
+ opt User is logged in
+ LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
+ end
+
+ activate onServerConnect
+ LoginStateViewModel-XonServerConnect: done
+ deactivate LoginStateViewModel
+ deactivate LoginStateViewModel
+
+ onServerConnect->>+DataUpdater: initialized
+ DataUpdater->DataUpdater: trigger stored callbacks
+ DataUpdater-->>onServerConnect: ok
+ deactivate DataUpdater
+ deactivate onServerConnect
+
.. seealso::
`OctoPrint's core viewmodels `_
diff --git a/docs/sphinxext/onlineinclude.py b/docs/sphinxext/onlineinclude.py
index 633eeef35..b6d9a1810 100644
--- a/docs/sphinxext/onlineinclude.py
+++ b/docs/sphinxext/onlineinclude.py
@@ -7,41 +7,99 @@ __copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the
import codecs
-import urllib2
+import requests
+from contextlib import closing
-from sphinx.directives import LiteralInclude, dedent_lines
+from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
+ nodes, set_source_info, parselinenos, logger, container_wrapper
+
+if False:
+ # For type annotation
+ from typing import Any, List # NOQA
cache = dict()
+class OnlineIncludeReader(LiteralIncludeReader):
+
+ def read_file(self, filename, location=None):
+ # type: (unicode, Any) -> List[unicode]
+
+ global cache
+ try:
+ if filename in cache:
+ lines = cache[filename]
+ else:
+ with closing(requests.get(filename, stream=True)) as r:
+ r.encoding = self.encoding
+ lines = r.text.splitlines(True)
+ cache[filename] = lines
+
+ if 'tab-width' in self.options:
+ lines = [line.expandtabs(self.options['tab-width']) for line in lines]
+
+ return lines
+ except (IOError, OSError):
+ raise IOError(_('Include file %r not found or reading it failed') % filename)
+ except UnicodeError:
+ raise UnicodeError(_('Encoding %r used for reading included file %r seems to '
+ 'be wrong, try giving an :encoding: option') %
+ (self.encoding, filename))
+
+
class OnlineIncludeDirective(LiteralInclude):
- def read_with_encoding(self, filename, document, codec_info, encoding):
- global cache
+ def run(self):
+ # type: () -> List[nodes.Node]
+ document = self.state.document
+ if not document.settings.file_insertion_enabled:
+ return [document.reporter.warning('File insertion disabled',
+ line=self.lineno)]
+ env = document.settings.env
+
+ # convert options['diff'] to absolute path
+ if 'diff' in self.options:
+ _, path = env.relfn2path(self.options['diff'])
+ self.options['diff'] = path
- f = None
try:
- if not self.arguments[0] in cache:
- f = codecs.StreamReaderWriter(urllib2.urlopen(self.arguments[0]), codec_info[2],
- codec_info[3], 'strict')
- lines = f.readlines()
- cache[self.arguments[0]] = lines
- else:
- lines = cache[self.arguments[0]]
+ location = self.state_machine.get_source_and_line(self.lineno)
+ url = self.arguments[0]
+
+ reader = OnlineIncludeReader(url, self.options, env.config)
+ text, lines = reader.read(location=location)
+
+ retnode = nodes.literal_block(text, text, source=url)
+ set_source_info(self, retnode)
+ if self.options.get('diff'): # if diff is set, set udiff
+ retnode['language'] = 'udiff'
+ elif 'language' in self.options:
+ retnode['language'] = self.options['language']
+ retnode['linenos'] = ('linenos' in self.options or
+ 'lineno-start' in self.options or
+ 'lineno-match' in self.options)
+ retnode['classes'] += self.options.get('class', [])
+ extra_args = retnode['highlight_args'] = {}
+ if 'emphasize-lines' in self.options:
+ hl_lines = parselinenos(self.options['emphasize-lines'], lines)
+ if any(i >= lines for i in hl_lines):
+ logger.warning('line number spec is out of range(1-%d): %r' %
+ (lines, self.options['emphasize-lines']),
+ location=location)
+ extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines]
+ extra_args['linenostart'] = reader.lineno_start
+
+ if 'caption' in self.options:
+ caption = self.options['caption'] or self.arguments[0]
+ retnode = container_wrapper(self, retnode, caption)
+
+ # retnode will be note_implicit_target that is linked from caption and numref.
+ # when options['name'] is provided, it should be primary ID.
+ self.add_name(retnode)
+
+ return [retnode]
+ except Exception as exc:
+ return [document.reporter.warning(str(exc), line=self.lineno)]
- lines = dedent_lines(lines, self.options.get('dedent'))
- return lines
- except (IOError, OSError, urllib2.URLError):
- return [document.reporter.warning(
- 'Include file %r not found or reading it failed' % self.arguments[0],
- line=self.lineno)]
- except UnicodeError:
- return [document.reporter.warning(
- 'Encoding %r used for reading included file %r seems to '
- 'be wrong, try giving an :encoding: option' %
- (encoding, self.arguments[0]))]
- finally:
- if f is not None:
- f.close()
def visit_onlineinclude(translator, node):
translator.visit_literal_block(node)
@@ -53,4 +111,4 @@ def setup(app):
app.add_directive("onlineinclude", OnlineIncludeDirective)
handler = (visit_onlineinclude, depart_onlineinclude)
- app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
\ No newline at end of file
+ app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
diff --git a/requirements.txt b/requirements.txt
index 3175f72cd..3f4887daa 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -7,4 +7,6 @@
# variables INSTALL_REQUIRES and EXTRA_REQUIRES.
###
+# let's force the regular pypi URL, with https, just to be sure
+-i https://pypi.python.org/simple
.
diff --git a/setup.cfg b/setup.cfg
index 9be46c443..4320f0f8a 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -1,5 +1,5 @@
[metadata]
-description-file = README.md
+license_file = LICENSE.txt
[versioneer]
VCS = git
diff --git a/setup.py b/setup.py
index 029ac10c4..69e65d979 100644
--- a/setup.py
+++ b/setup.py
@@ -16,18 +16,19 @@ import octoprint_setuptools
INSTALL_REQUIRES = [
"flask>=0.12,<0.13",
"werkzeug>=0.11.1,<0.12",
- "tornado>=4.4.2,<4.5",
+ "tornado>=4.5.3,<5",
"Jinja2>=2.8,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
# guarantee backwards compatibility for plugins and such with that
# version, hence we need to pin to a lower version for now. See #1697
- "sockjs-tornado>=1.0.2,<1.1",
+ #"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a
+ # vendored one
"PyYAML>=3.12,<3.13",
"Flask-Login>=0.4,<0.5",
"Flask-Principal>=0.4,<0.5",
"Flask-Babel>=0.11,<0.12",
"Flask-Assets>=0.12,<0.13",
"markdown>=2.6.4,<2.7",
- "pyserial>=3.2.1,<3.3",
+ "pyserial>=3.4,<3.5",
"netaddr>=0.7.17,<0.8",
"watchdog>=0.8.3,<0.9",
"sarge>=0.1.4,<0.2",
@@ -35,9 +36,10 @@ INSTALL_REQUIRES = [
"pylru>=1.0.9,<1.1",
"rsa>=3.4,<3.5",
"pkginfo>=1.4.1,<1.5",
- "requests>=2.13.0,<2.14",
+ "requests>=2.18.4,<3",
"semantic_version>=2.6.0,<2.7",
- "psutil>=5.1.3,<5.2",
+ "psutil==5.4.3", # 5.4.4 introduced a breaking change concerning installing under non current
+ # setuptools versions. Pinning to 5.4.3 for now to work around this.
"Click>=6.7,<6.8",
"awesome-slugify>=1.6.5,<1.7",
"feedparser>=5.2.1,<5.3",
@@ -45,7 +47,12 @@ INSTALL_REQUIRES = [
"future>=0.15,<0.16",
"scandir>=1.3,<1.4",
"websocket-client>=0.40,<0.41",
- "python-dateutil>=2.6,<2.7"
+ "python-dateutil>=2.6,<2.7",
+ "wrapt>=1.10.10,<1.11",
+ "futures>=3.1.1,<3.2",
+ "emoji>=0.4.5,<0.5",
+ "monotonic>=1.3,<1.4",
+ "frozendict>=1.2,<1.3"
]
if sys.platform == "darwin":
@@ -56,22 +63,20 @@ EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint
develop=[
# Testing dependencies
- "mock>=2.0,<2.1",
+ "mock>=2.0.0,<3",
"nose>=1.3.0,<1.4",
"ddt",
# Documentation dependencies
- "sphinx>=1.3,<1.4",
+ "sphinx>=1.6,<1.7",
"sphinxcontrib-httpdomain",
+ "sphinxcontrib-mermaid>=0.3",
"sphinx_rtd_theme",
-
- # PyPi upload related
- "pypandoc"
],
# Dependencies for developing OctoPrint plugins
plugins=[
- "cookiecutter>=1.5,<1.6"
+ "cookiecutter>=1.5,<1.7"
]
)
@@ -84,6 +89,13 @@ DEPENDENCY_LINKS = []
#-----------------------------------------------------------------------------------------------------------------------
# Anything below here is just command setup and general setup configuration
+here = os.path.abspath(os.path.dirname(__file__))
+
+def read_file_contents(path):
+ import codecs
+ with codecs.open(path, encoding="utf-8") as f:
+ return f.read()
+
def data_copy_build_py_factory(files, baseclass):
class data_copy_build_py(baseclass):
files = dict()
@@ -139,45 +151,49 @@ def params():
version = versioneer.get_version()
cmdclass = get_cmdclass()
- description = "A snappy web interface for 3D printers"
- long_description = open("README.md").read()
+ description = "The snappy web interface for your 3D printer"
+ long_description = read_file_contents(os.path.join(here, "README.md"))
+ long_description_content_type = "text/markdown"
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",
+ "Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Flask",
+ "Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Manufacturing",
+ "Intended Audience :: Other Audience",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Natural Language :: English",
+ "Natural Language :: German",
"Operating System :: OS Independent",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
+ "Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: JavaScript",
- "Topic :: Internet :: WWW/HTTP",
- "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
- "Topic :: Internet :: WWW/HTTP :: WSGI",
"Topic :: Printing",
- "Topic :: System :: Networking :: Monitoring"
+ "Topic :: System :: Monitoring"
]
author = "Gina Häußge"
- author_email = "osd@foosel.net"
- url = "http://octoprint.org"
- license = "AGPLv3"
+ author_email = "gina@octoprint.org"
+ url = "https://octoprint.org"
+ license = "GNU Affero General Public License v3"
+ keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
+
+ project_urls={
+ "Community Forum": "https://discourse.octoprint.org",
+ "Bug Reports": "https://github.com/foosel/OctoPrint/issues",
+ "Source": "https://github.com/foosel/OctoPrint",
+ "Funding": "https://donate.octoprint.org"
+ }
packages = find_packages(where="src")
package_dir = {
diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py
index 3e24895ff..39932aadc 100644
--- a/src/octoprint/__init__.py
+++ b/src/octoprint/__init__.py
@@ -12,7 +12,7 @@ versions = get_versions()
__version__ = versions['version']
__branch__ = versions.get('branch', None)
-__display_version__ = "{} ({} branch)".format(__version__, __branch__) if __branch__ else __version__
+__display_version__ = __version__
__revision__ = versions.get('full-revisionid', versions.get('full', None))
del versions
@@ -57,9 +57,10 @@ class FatalStartupError(BaseException):
def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
logging_config=None, debug=False, verbosity=0, uncaught_logger=None,
- uncaught_handler=None, safe_mode=False, after_preinit_logging=None,
+ uncaught_handler=None, safe_mode=False, ignore_blacklist=False, after_preinit_logging=None,
after_settings=None, after_logging=None, after_safe_mode=None,
- after_plugin_manager=None):
+ after_event_manager=None, after_connectivity_checker=None,
+ after_plugin_manager=None, after_environment_detector=None):
kwargs = dict()
logger, recorder = preinit_logging(debug, verbosity, uncaught_logger, uncaught_handler)
@@ -94,13 +95,34 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
if callable(after_safe_mode):
after_safe_mode(**kwargs)
- plugin_manager = init_pluginsystem(settings, safe_mode=safe_mode)
+ event_manager = init_event_manager(settings)
+
+ kwargs["event_manager"] = event_manager
+ if callable(after_event_manager):
+ after_event_manager(**kwargs)
+
+ connectivity_checker = init_connectivity_checker(settings, event_manager)
+
+ kwargs["connectivity_checker"] = connectivity_checker
+ if callable(after_connectivity_checker):
+ after_connectivity_checker(**kwargs)
+
+ plugin_manager = init_pluginsystem(settings,
+ safe_mode=safe_mode,
+ ignore_blacklist=ignore_blacklist,
+ connectivity_checker=connectivity_checker)
kwargs["plugin_manager"] = plugin_manager
if callable(after_plugin_manager):
after_plugin_manager(**kwargs)
- return settings, logger, safe_mode, plugin_manager
+ environment_detector = init_environment_detector(plugin_manager)
+ kwargs["environment_detector"] = environment_detector
+
+ if callable(after_environment_detector):
+ after_environment_detector(**kwargs)
+
+ return settings, logger, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector
def init_settings(basedir, configfile):
@@ -176,7 +198,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
},
"handlers": {
"console": {
- "class": "logging.StreamHandler",
+ "class": "octoprint.logging.handlers.OctoPrintStreamHandler",
"level": "DEBUG",
"formatter": "simple",
"stream": "ext://sys.stdout"
@@ -194,7 +216,8 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
"level": "DEBUG",
"formatter": "serial",
"backupCount": 3,
- "filename": os.path.join(settings.getBaseFolder("logs"), "serial.log")
+ "filename": os.path.join(settings.getBaseFolder("logs"), "serial.log"),
+ "delay": True
},
"protocolFile": {
"class": "logging.handlers.RotatingFileHandler",
@@ -213,7 +236,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
},
"loggers": {
"SERIAL": {
- "level": "CRITICAL",
+ "level": "INFO",
"handlers": ["serialFile"],
"propagate": False
},
@@ -304,27 +327,28 @@ def set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handl
return logger
-def init_pluginsystem(settings, safe_mode=False):
+def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connectivity_checker=None):
"""Initializes the plugin manager based on the settings."""
import os
- logger = log.getLogger(__name__)
+ logger = log.getLogger(__name__ + ".startup")
plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True),
settings.getBaseFolder("plugins")]
plugin_entry_points = ["octoprint.plugin"]
plugin_disabled_list = settings.get(["plugins", "_disabled"])
+ plugin_blacklist = []
+ if not ignore_blacklist and settings.getBoolean(["server", "pluginBlacklist", "enabled"]):
+ plugin_blacklist = get_plugin_blacklist(settings, connectivity_checker=connectivity_checker)
+
plugin_validators = []
if safe_mode:
def validator(phase, plugin_info):
- if phase == "after_load":
+ if phase in ("before_import", "before_load", "before_enable"):
setattr(plugin_info, "safe_mode_victim", not plugin_info.bundled)
- setattr(plugin_info, "safe_mode_enabled", False)
- elif phase == "before_enable":
if not plugin_info.bundled:
- setattr(plugin_info, "safe_mode_enabled", True)
return False
return True
plugin_validators.append(validator)
@@ -334,13 +358,14 @@ def init_pluginsystem(settings, safe_mode=False):
plugin_folders=plugin_folders,
plugin_entry_points=plugin_entry_points,
plugin_disabled_list=plugin_disabled_list,
+ plugin_blacklist=plugin_blacklist,
plugin_validators=plugin_validators)
settings_overlays = dict()
disabled_from_overlays = dict()
def handle_plugin_loaded(name, plugin):
- if hasattr(plugin.instance, "__plugin_settings_overlay__"):
+ if plugin.instance and hasattr(plugin.instance, "__plugin_settings_overlay__"):
plugin.needs_restart = True
# plugin has a settings overlay, inject it
@@ -379,7 +404,7 @@ def init_pluginsystem(settings, safe_mode=False):
if not addon in already_processed and not addon in disabled_list:
disabled_list.append(addon)
- logger.info("Disabling plugin {} as defined by plugin {} through settings overlay".format(addon, name))
+ logger.info("Disabling plugin {} as defined by plugin {}".format(addon, name))
already_processed.append(name)
def handle_plugin_enabled(name, plugin):
@@ -393,6 +418,141 @@ def init_pluginsystem(settings, safe_mode=False):
pm.reload_plugins(startup=True, initialize_implementations=False)
return pm
+
+def get_plugin_blacklist(settings, connectivity_checker=None):
+ import requests
+ import os
+ import time
+ import yaml
+
+ from octoprint.util import bom_aware_open
+ from octoprint.util.version import is_octoprint_compatible
+
+ logger = log.getLogger(__name__ + ".startup")
+
+ if connectivity_checker is not None and not connectivity_checker.online:
+ logger.info("We don't appear to be online, not fetching plugin blacklist")
+ return []
+
+ def format_blacklist(entries):
+ format_entry = lambda x: "{} ({})".format(x[0], x[1]) if isinstance(x, (list, tuple)) and len(x) == 2 \
+ else "{} (any)".format(x)
+ return ", ".join(map(format_entry, entries))
+
+ def process_blacklist(entries):
+ result = []
+
+ if not isinstance(entries, list):
+ return result
+
+ for entry in entries:
+ if not "plugin" in entry:
+ continue
+
+ if "octoversions" in entry and not is_octoprint_compatible(*entry["octoversions"]):
+ continue
+
+ if "version" in entry:
+ logger.debug("Blacklisted plugin: {}, version: {}".format(entry["plugin"], entry["version"]))
+ result.append((entry["plugin"], entry["version"]))
+ elif "versions" in entry:
+ logger.debug("Blacklisted plugin: {}, versions: {}".format(entry["plugin"], ", ".join(entry["versions"])))
+ for version in entry["versions"]:
+ result.append((entry["plugin"], version))
+ else:
+ logger.debug("Blacklisted plugin: {}".format(entry["plugin"]))
+ result.append(entry["plugin"])
+
+ return result
+
+ def fetch_blacklist_from_cache(path, ttl):
+ if not os.path.isfile(path):
+ return None
+
+ if os.stat(path).st_mtime + ttl < time.time():
+ return None
+
+ with bom_aware_open(path, encoding="utf-8", mode="r") as f:
+ result = yaml.safe_load(f)
+
+ if isinstance(result, list):
+ return result
+
+ def fetch_blacklist_from_url(url, timeout=3, cache=None):
+ result = []
+ try:
+ r = requests.get(url, timeout=timeout)
+ result = process_blacklist(r.json())
+
+ if cache is not None:
+ try:
+ with bom_aware_open(cache, encoding="utf-8", mode="w") as f:
+ yaml.safe_dump(result, f)
+ except:
+ logger.info("Fetched plugin blacklist but couldn't write it to its cache file.")
+ except:
+ logger.info("Unable to fetch plugin blacklist from {}, proceeding without it.".format(url))
+ return result
+
+ try:
+ # first attempt to fetch from cache
+ cache_path = os.path.join(settings.getBaseFolder("data"), "plugin_blacklist.yaml")
+ ttl = settings.getInt(["server", "pluginBlacklist", "ttl"])
+ blacklist = fetch_blacklist_from_cache(cache_path, ttl)
+
+ if blacklist is None:
+ # no result from the cache, let's fetch it fresh
+ url = settings.get(["server", "pluginBlacklist", "url"])
+ timeout = settings.getFloat(["server", "pluginBlacklist", "timeout"])
+ blacklist = fetch_blacklist_from_url(url, timeout=timeout, cache=cache_path)
+
+ if blacklist is None:
+ # still now result, so no blacklist
+ blacklist = []
+
+ if blacklist:
+ logger.info("Blacklist processing done, "
+ "adding {} blacklisted plugin versions: {}".format(len(blacklist),
+ format_blacklist(blacklist)))
+ else:
+ logger.info("Blacklist processing done")
+
+ return blacklist
+ except:
+ logger.exception("Something went wrong while processing the plugin blacklist. Proceeding without it.")
+
+
+def init_event_manager(settings):
+ from octoprint.events import eventManager
+ return eventManager()
+
+
+def init_connectivity_checker(settings, event_manager):
+ from octoprint.events import Events
+ from octoprint.util import ConnectivityChecker
+
+ # start regular check if we are connected to the internet
+ connectivityEnabled = settings.getBoolean(["server", "onlineCheck", "enabled"])
+ connectivityInterval = settings.getInt(["server", "onlineCheck", "interval"])
+ connectivityHost = settings.get(["server", "onlineCheck", "host"])
+ connectivityPort = settings.getInt(["server", "onlineCheck", "port"])
+
+ def on_connectivity_change(old_value, new_value):
+ event_manager.fire(Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value, new=new_value))
+
+ connectivityChecker = ConnectivityChecker(connectivityInterval,
+ connectivityHost,
+ port=connectivityPort,
+ enabled=connectivityEnabled,
+ on_change=on_connectivity_change)
+
+ return connectivityChecker
+
+
+def init_environment_detector(plugin_manager):
+ from octoprint.environment import EnvironmentDetector
+ return EnvironmentDetector(plugin_manager)
+
#~~ server main method
def main():
diff --git a/src/octoprint/__main__.py b/src/octoprint/__main__.py
new file mode 100644
index 000000000..3dd81998d
--- /dev/null
+++ b/src/octoprint/__main__.py
@@ -0,0 +1,7 @@
+#!/usr/bin/env python2
+# coding=utf-8
+from __future__ import absolute_import, division, print_function
+
+if __name__ == "__main__":
+ import octoprint
+ octoprint.main()
diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py
index ee9406584..9c9eeab62 100644
--- a/src/octoprint/_version.py
+++ b/src/octoprint/_version.py
@@ -305,7 +305,6 @@ def git_parse_lookup_file(path):
if not os.path.exists(path):
return []
- import re
lookup = []
with open(path, "r") as f:
for line in f:
diff --git a/src/octoprint/access/__init__.py b/src/octoprint/access/__init__.py
new file mode 100644
index 000000000..eed3bf88b
--- /dev/null
+++ b/src/octoprint/access/__init__.py
@@ -0,0 +1,6 @@
+# coding=utf-8
+from __future__ import absolute_import, division, print_function
+
+ADMIN_GROUP = "admins"
+USER_GROUP = "users"
+GUEST_GROUP = "guests"
diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py
new file mode 100644
index 000000000..cfbe4abbc
--- /dev/null
+++ b/src/octoprint/access/groups.py
@@ -0,0 +1,506 @@
+# coding=utf-8
+from __future__ import absolute_import, division, print_function
+
+__author__ = "Marc Hannappel "
+__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
+__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
+
+import logging
+import os
+from functools import partial
+
+import yaml
+
+from past.builtins import basestring
+
+from octoprint.settings import settings
+from octoprint.util import atomic_write
+from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP
+from octoprint.access.permissions import Permissions, OctoPrintPermission
+from flask_principal import Need, Permission
+
+DEFAULT_ADMIN_PERMISSIONS = [Permissions.ADMIN]
+"""Default admin permissions are the legacy permissions from before 1.4.0"""
+
+DEFAULT_USER_PERMISSIONS = [Permissions.STATUS,
+ Permissions.CONNECTION,
+ Permissions.WEBCAM,
+ Permissions.FILES_UPLOAD,
+ Permissions.FILES_DOWNLOAD,
+ Permissions.FILES_DELETE,
+ Permissions.FILES_SELECT,
+ Permissions.PRINT,
+ Permissions.MONITOR_TERMINAL,
+ Permissions.CONTROL,
+ Permissions.SLICE,
+ Permissions.TIMELAPSE_LIST,
+ Permissions.TIMELAPSE_ADMIN]
+"""Default user permissions are the legacy permissions from before 1.4.0"""
+
+DEFAULT_GUEST_PERMISSIONS = [Permissions.STATUS,
+ Permissions.WEBCAM,
+ Permissions.FILES_DOWNLOAD,
+ Permissions.TIMELAPSE_LIST,
+ Permissions.MONITOR_TERMINAL]
+"""Default guest permissions are the legacy permissions from before 1.4.0"""
+
+
+GroupNeed = partial(Need, 'group')
+GroupNeed.__doc__ = """A need with the method preset to `"group"`."""
+
+
+class GroupPermission(Permission):
+ def __init__(self, key):
+ need = GroupNeed(key)
+ super(GroupPermission, self).__init__(need)
+
+
+class GroupManager(object):
+ @classmethod
+ def default_permissions_for_group(cls, group):
+ result = []
+ for permission in Permissions.all():
+ if group in permission.default_groups:
+ result.append(permission)
+ return result
+
+ def __init__(self):
+ self._logger = logging.getLogger(__name__)
+ self._group_change_listeners = []
+ self._init_defaults()
+
+ @property
+ def groups(self):
+ return []
+
+ @property
+ def admin_group(self):
+ return self.find_group(ADMIN_GROUP)
+
+ @property
+ def user_group(self):
+ return self.find_group(USER_GROUP)
+
+ @property
+ def guest_group(self):
+ return self.find_group(GUEST_GROUP)
+
+ def _init_defaults(self):
+ self.add_group(ADMIN_GROUP,
+ "Admins",
+ "Administrators",
+ self.default_permissions_for_group(ADMIN_GROUP),
+ changeable=False,
+ removable=False,
+ save=False)
+ self.add_group(USER_GROUP,
+ "Users",
+ "All logged in users",
+ self.default_permissions_for_group(USER_GROUP),
+ default=True,
+ removable=False,
+ toggleable=False,
+ save=False)
+ self.add_group(GUEST_GROUP,
+ "Guests",
+ "Anyone who is not currently logged in",
+ self.default_permissions_for_group(GUEST_GROUP),
+ removable=False,
+ toggleable=False,
+ save=False)
+
+ def register_listener(self, listener):
+ self._group_change_listeners.append(listener)
+
+ def unregister_listener(self, listener):
+ self._group_change_listeners.remove(listener)
+
+ def add_group(self, key, name, description, permissions, default=False, removable=True, changeable=True, toggleable=True, save=True, notify=True):
+ pass
+
+ def update_group(self, key, description=None, permissions=None, default=None, save=True, notify=True):
+ pass
+
+ def remove_group(self, key, save=True, notify=True):
+ pass
+
+ def find_group(self, key):
+ return None
+
+ def _to_permissions(self, *permissions):
+ return filter(lambda x: x is not None,
+ [Permissions.find(permission) for permission in permissions])
+
+ def _from_permissions(self, *permissions):
+ return [permission.key for permission in permissions]
+
+ def _to_group(self, group):
+ # noinspection PyCompatibility
+ if isinstance(group, Group):
+ return group
+ elif isinstance(group, basestring):
+ return self.find_group(group)
+ elif isinstance(group, dict):
+ return self.find_group(group.get("key"))
+ else:
+ return None
+
+ def _notify_listeners(self, action, group, *args, **kwargs):
+ method = "on_group_{}".format(action)
+ for listener in self._group_change_listeners:
+ try:
+ getattr(listener, method)(group, *args, **kwargs)
+ except:
+ self._logger.exception("Error notifying listener {!r} via {}".format(listener, method))
+
+class GroupChangeListener(object):
+
+ def on_group_added(self, group):
+ pass
+
+ def on_group_removed(self, group):
+ pass
+
+ def on_group_permissions_changed(self, group, added=None, removed=None):
+ pass
+
+
+class FilebasedGroupManager(GroupManager):
+ def __init__(self, path=None):
+ if path is None:
+ path = settings().get(["accessControl", "groupfile"])
+ if path is None:
+ path = os.path.join(settings().getBaseFolder("base"), "groups.yaml")
+
+ self._groupfile = path
+ self._groups = dict()
+ self._dirty = False
+
+ GroupManager.__init__(self)
+
+ self._load()
+
+ def _load(self):
+ if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile):
+ try:
+ with open(self._groupfile, "r") as f:
+ data = yaml.safe_load(f)
+
+ if not "groups" in data:
+ groups = data
+ data = dict(groups=groups)
+
+ groups = data.get("groups", dict())
+ tracked_permissions = data.get("tracked", list())
+
+ for key, attributes in groups.items():
+ if key in self._groups:
+ # group is already there (from the defaults most likely)
+ if not self._groups[key].is_changeable():
+ # group may not be changed -> bail
+ continue
+
+ removable = self._groups[key].is_removable()
+ changeable = self._groups[key].is_changeable()
+ toggleable = self._groups[key].is_toggleable()
+ else:
+ removable = True
+ changeable = True
+ toggleable = True
+
+ permissions = self._to_permissions(*attributes.get("permissions", []))
+ default_permissions = self.default_permissions_for_group(key)
+ for permission in default_permissions:
+ if not permission.key in tracked_permissions and not permission in permissions:
+ permissions.append(permission)
+
+ self._groups[key] = Group(key, attributes.get("name", ""),
+ description=attributes.get("description", ""),
+ permissions=permissions,
+ default=attributes.get("default", False),
+ removable=removable,
+ changeable=changeable,
+ toggleable=toggleable)
+ except:
+ self._logger.exception("Error while loading groups from file {}".format(self._groupfile))
+
+ def _save(self, force=False):
+ if self._groupfile is None or not self._dirty and not force:
+ return
+
+ groups = dict()
+ for key in self._groups.keys():
+ group = self._groups[key]
+ groups[key] = dict(
+ name=group._name,
+ description=group._description,
+ permissions=self._from_permissions(*group._permissions),
+ default=group._default
+ )
+
+ data = dict(groups=groups,
+ tracked=[x.key for x in Permissions.all()])
+
+ with atomic_write(self._groupfile, "wb", permissions=0o600, max_permissions=0o666) as f:
+ import yaml
+ yaml.safe_dump(data, f, default_flow_style=False, indent=" ", allow_unicode=True)
+ self._dirty = False
+ self._load()
+
+ @property
+ def groups(self):
+ return list(self._groups.values())
+
+ @property
+ def default_groups(self):
+ return [group for group in self._groups.values() if group.is_default()]
+
+ def find_group(self, key):
+ if key is None:
+ return None
+ return self._groups.get(key)
+
+ def add_group(self, key, name, description, permissions, default=False, removable=True,
+ changeable=True, toggleable=True, overwrite=False, notify=True, save=True):
+ if key in self._groups.keys() and not overwrite:
+ raise GroupAlreadyExists(key)
+
+ if not permissions:
+ permissions = []
+
+ permissions = self._to_permissions(*permissions)
+ assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
+
+ group = Group(key, name,
+ description=description,
+ permissions=permissions,
+ default=default,
+ changeable=changeable,
+ removable=removable,
+ toggleable=toggleable)
+ self._groups[key] = group
+
+ if save:
+ self._dirty = True
+ self._save()
+
+ if notify:
+ self._notify_listeners("added", group)
+
+ def remove_group(self, key, save=True, notify=True):
+ """Removes a Group by key"""
+ group = self._to_group(key)
+ if group is None:
+ raise UnknownGroup(key)
+
+ if not group.is_removable():
+ raise GroupUnremovable(key)
+
+ del self._groups[key]
+ self._dirty = True
+
+ if save:
+ self._save()
+
+ if notify:
+ self._notify_listeners("removed", group)
+
+ def update_group(self, key, description=None, permissions=None, default=None, save=True, notify=True):
+ group = self._to_group(key)
+ if group is None:
+ raise UnknownGroup(key)
+
+ if not group.is_changeable():
+ raise GroupCantBeChanged(key)
+
+ if description is not None and description != group.get_description():
+ group.change_description(description)
+ self._dirty = True
+
+ notifications = []
+
+ if permissions is not None:
+ permissions = self._to_permissions(*permissions)
+ assert (all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
+
+ removed_permissions = list(set(group._permissions) - set(permissions))
+ added_permissions = list(set(permissions) - set(group._permissions))
+
+ if removed_permissions:
+ self._dirty |= group.remove_permissions_from_group(removed_permissions)
+ if added_permissions:
+ self._dirty |= group.add_permissions_to_group(added_permissions)
+
+ notifications.append((("permissions_changed", group),
+ dict(added=added_permissions, removed=removed_permissions)))
+
+ if default is not None:
+ group.change_default(default)
+ self._dirty = True
+
+ if self._dirty:
+ if save:
+ self._save()
+
+ if notify:
+ for args, kwargs in notifications:
+ self._notify_listeners(*args, **kwargs)
+
+
+class GroupAlreadyExists(Exception):
+ def __init__(self, key):
+ Exception.__init__(self, "Group %s already exists" % key)
+
+
+class UnknownGroup(Exception):
+ def __init__(self, key):
+ Exception.__init__(self, "Unknown group: %s" % key)
+
+
+class GroupUnremovable(Exception):
+ def __init__(self, key):
+ Exception.__init__(self, "Group can't be removed: %s" % key)
+
+
+class GroupCantBeChanged(Exception):
+ def __init__(self, key):
+ Exception.__init__(self, "Group can't be changed: %s" % key)
+
+
+class Group(object):
+ def __init__(self, key, name, description="", permissions=None, default=False, removable=True, changeable=True, toggleable=True):
+ self._key = key
+ self._name = name
+ self._description = description
+ self._permissions = permissions
+ self._default = default
+ self._removable = removable
+ self._changeable = changeable
+ self._toggleable = toggleable
+
+ def as_dict(self):
+ from octoprint.access.permissions import OctoPrintPermission
+ return dict(
+ key=self.key,
+ name=self.get_name(),
+ description=self._description,
+ permissions=map(lambda p: p.key, self._permissions),
+ needs=OctoPrintPermission.convert_needs_to_dict(self.needs),
+ default=self._default,
+ removable=self._removable,
+ changeable=self._changeable,
+ toggleable=self._toggleable
+ )
+
+ @property
+ def key(self):
+ return self._key
+
+ def get_name(self):
+ return self._name
+
+ def get_description(self):
+ return self._description
+
+ def is_default(self):
+ return self._default
+
+ def is_changeable(self):
+ return self._changeable
+
+ def is_removable(self):
+ return self._removable
+
+ def is_toggleable(self):
+ return self._toggleable
+
+ def add_permissions_to_group(self, permissions):
+ """Adds a list of permissions to a group"""
+ if not self.is_changeable():
+ raise GroupCantBeChanged(self.key)
+
+ # Make sure the permissions variable is of type list
+ if not isinstance(permissions, list):
+ permissions = [permissions]
+
+ assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
+
+ dirty = False
+ for permission in permissions:
+ if permissions not in self.permissions:
+ self._permissions.append(permission)
+ dirty = True
+
+ return dirty
+
+ def remove_permissions_from_group(self, permissions):
+ """Removes a list of permissions from a group"""
+ if not self.is_changeable():
+ raise GroupCantBeChanged(self.key)
+
+ # Make sure the permissions variable is of type list
+ if not isinstance(permissions, list):
+ permissions = [permissions]
+
+ assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
+
+ dirty = False
+ for permission in permissions:
+ if permission in self._permissions:
+ self._permissions.remove(permission)
+ dirty = True
+
+ return dirty
+
+ def change_default(self, default):
+ """Changes the default flag of a Group"""
+ if not self.is_changeable():
+ raise GroupCantBeChanged(self.key)
+
+ self._default = default
+
+ def change_description(self, description):
+ """Changes the description of a group"""
+ self._description = description
+
+ @property
+ def permissions(self):
+ if Permissions.ADMIN in self._permissions:
+ return Permissions.all()
+
+ return filter(lambda p: p is not None, self._permissions)
+
+ @property
+ def needs(self):
+ needs = set()
+ needs.add(GroupNeed(self.key))
+ for p in self.permissions:
+ needs = needs.union(p.needs)
+
+ return needs
+
+ def has_permission(self, permission):
+ if Permissions.ADMIN.get_name() in self._permissions:
+ return True
+
+ return permission.needs.issubset(self.needs)
+
+ def __repr__(self):
+ return '{}("{}", "{}", description="{}", permissions={!r}, ' \
+ 'default={}, removable={}, changeable={})'.format(self.__class__.__name__,
+ self._key,
+ self._name,
+ self._description,
+ self._permissions,
+ bool(self._default),
+ bool(self._removable),
+ bool(self._changeable))
+
+ def __hash__(self):
+ return self.key.__hash__()
+
+ def __eq__(self, other):
+ return isinstance(other, Group) and other.key == self.key
+
+
+
diff --git a/src/octoprint/access/permissions.py b/src/octoprint/access/permissions.py
new file mode 100644
index 000000000..1a632bfaf
--- /dev/null
+++ b/src/octoprint/access/permissions.py
@@ -0,0 +1,369 @@
+# coding=utf-8
+from __future__ import absolute_import, division, print_function
+
+__author__ = "Marc Hannappel "
+__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
+__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
+
+
+from flask import g, abort
+from flask_babel import gettext
+from flask_principal import Permission, PermissionDenied, RoleNeed, Need
+
+from functools import wraps
+from collections import OrderedDict, defaultdict
+
+# noinspection PyCompatibility
+from past.builtins import basestring
+
+from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP
+
+
+class OctoPrintPermission(Permission):
+ @classmethod
+ def convert_needs_to_dict(cls, needs):
+ ret_needs = defaultdict(list)
+ for need in needs:
+ if need.value not in ret_needs[need.method]:
+ ret_needs[need.method].append(need.value)
+ return ret_needs
+
+ @classmethod
+ def convert_to_needs(cls, needs):
+ result = []
+ for need in needs:
+ # noinspection PyCompatibility
+ if isinstance(need, Need):
+ result.append(need)
+ elif isinstance(need, Permission):
+ result += need.needs
+ elif isinstance(need, basestring):
+ result.append(RoleNeed(need))
+ return result
+
+ def __init__(self, name, description, *needs, **kwargs):
+ self._name = name
+ self._description = description
+ self._dangerous = kwargs.pop("dangerous", False) == True
+ self._default_groups = kwargs.pop("default_groups", [])
+
+ self._key = None
+
+ Permission.__init__(self, *self.convert_to_needs(needs))
+
+ def as_dict(self):
+ return dict(
+ key=self.key,
+ name=self.get_name(),
+ dangerous=self._dangerous,
+ default_groups=self._default_groups,
+ description=self.get_description(),
+ needs=self.convert_needs_to_dict(self.needs)
+ )
+
+ @property
+ def key(self):
+ return self._key
+
+ @key.setter
+ def key(self, value):
+ self._key = value
+
+ @property
+ def default_groups(self):
+ return self._default_groups
+
+ def get_name(self):
+ return self._name
+
+ def get_description(self):
+ return self._description
+
+ def union(self, other):
+ """Create a new OctoPrintPermission with the requirements of the union of this
+ and other.
+
+ :param other: The other permission
+ """
+ p = self.__class__(self._name, self._description, *self.needs.union(other.needs))
+ p.excludes.update(self.excludes.union(other.excludes))
+ return p
+
+ def difference(self, other):
+ """Create a new OctoPrintPermission consisting of requirements in this
+ permission and not in the other.
+ """
+
+ p = self.__class__(self._name, self._description, *self.needs.difference(other.needs))
+ p.excludes.update(self.excludes.difference(other.excludes))
+ return p
+
+ def __repr__(self):
+ return '{}({!r}, {!r}, {})'.format(self.__class__.__name__,
+ self.get_name(),
+ self.get_description(),
+ ', '.join(map(repr, self.needs)))
+
+ def __hash__(self):
+ return self.get_name().__hash__()
+
+ def __eq__(self, other):
+ return isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name()
+
+
+class PluginOctoPrintPermission(OctoPrintPermission):
+
+ def __init__(self, *args, **kwargs):
+ self.plugin = kwargs.pop("plugin", None)
+ OctoPrintPermission.__init__(self, *args, **kwargs)
+
+ def as_dict(self):
+ result = OctoPrintPermission.as_dict(self)
+ result["plugin"] = self.plugin
+ return result
+
+
+class PluginIdentityContext(object):
+ """Identity context for not initialized Permissions
+
+ Needed to support @Permissions.PLUGIN_X_Y.require()
+
+ Will search the permission when needed
+ """
+ def __init__(self, key, http_exception=None):
+ self.key = key
+ self.http_exception = http_exception
+ """The permission of this principal
+ """
+
+ @property
+ def identity(self):
+ """The identity of this principal
+ """
+ return g.identity
+
+ def can(self):
+ """Whether the identity has access to the permission
+ """
+ permission = getattr(Permissions, self.key)
+ if permission is None or isinstance(permission, PluginPermissionDecorator):
+ raise UnknownPermission(self.key)
+
+ return permission.can()
+
+ def __call__(self, f):
+ @wraps(f)
+ def _decorated(*args, **kw):
+ with self:
+ rv = f(*args, **kw)
+ return rv
+
+ return _decorated
+
+ def __enter__(self):
+ permission = getattr(Permissions, self.key)
+ if permission is None or isinstance(permission, PluginPermissionDecorator):
+ raise UnknownPermission(self.key)
+
+ # check the permission here
+ if not permission.can():
+ if self.http_exception:
+ abort(self.http_exception, permission)
+ raise PermissionDenied(permission)
+
+ def __exit__(self, *args):
+ return False
+
+
+class PluginPermissionDecorator(Permission):
+ """Decorator Class for not initialized Permissions
+
+ Needed to support @Permissions.PLUGIN_X_Y.require()
+ """
+ def __init__(self, key):
+ self.key = key
+
+ def require(self, http_exception=None):
+ return PluginIdentityContext(self.key, http_exception)
+
+
+class PermissionsMetaClass(type):
+ permissions = OrderedDict()
+
+ def __new__(mcs, name, bases, args):
+ cls = type.__new__(mcs, name, bases, args)
+
+ for key, value in args.items():
+ if isinstance(value, OctoPrintPermission):
+ value.key = key
+ mcs.permissions[key] = value
+ delattr(cls, key)
+
+ return cls
+
+ def __setattr__(cls, key, value):
+ if isinstance(value, OctoPrintPermission):
+ if key in cls.permissions:
+ raise PermissionAlreadyExists(key)
+ value.key = key
+ cls.permissions[key] = value
+
+ def __getattr__(cls, key):
+ permission = cls.permissions.get(key)
+
+ if key.startswith("PLUGIN_") and permission is None:
+ return PluginPermissionDecorator(key)
+
+ return permission
+
+ def all(cls):
+ return cls.permissions.values()
+
+ def filter(cls, cb):
+ return filter(cb, cls.all())
+
+ def find(cls, p, filter=None):
+ key = None
+ if isinstance(p, OctoPrintPermission):
+ key = p.key
+ elif isinstance(p, dict):
+ key = p.get("key")
+ elif isinstance(p, basestring):
+ key = p
+
+ if key is None:
+ return None
+
+ return cls.match(lambda p: p.key == key, filter=filter)
+
+ def match(cls, match, filter=None):
+ if callable(filter):
+ permissions = cls.filter(filter)
+ else:
+ permissions = cls.all()
+
+ for permission in permissions:
+ if match(permission):
+ return permission
+
+ return None
+
+
+class Permissions(object):
+ __metaclass__ = PermissionsMetaClass
+
+ # Special permission
+ ADMIN = OctoPrintPermission("Admin",
+ gettext("Admin is allowed to do everything"),
+ RoleNeed("admin"),
+ dangerous=True,
+ default_groups=[ADMIN_GROUP])
+
+ STATUS = OctoPrintPermission("Status",
+ gettext("Allows to gather status information, e.g. job progress, "
+ "printer state, temperatures, ..."),
+ RoleNeed("status"),
+ default_groups=[USER_GROUP, GUEST_GROUP])
+
+ CONNECTION = OctoPrintPermission("Connection",
+ gettext("Allows to connect to and disconnect from a printer"),
+ RoleNeed("connection"),
+ default_groups=[USER_GROUP])
+
+ WEBCAM = OctoPrintPermission("Webcam",
+ gettext("Allows to watch the webcam stream"),
+ RoleNeed("webcam"),
+ default_groups=[USER_GROUP, GUEST_GROUP])
+
+ SYSTEM = OctoPrintPermission("System",
+ gettext("Allows to run system commands, e.g. restart OctoPrint, "
+ "shutdown or reboot the system"),
+ RoleNeed("system"),
+ dangerous=True)
+
+ FILES_LIST = OctoPrintPermission("File List",
+ gettext("Allows to retrieve a list of all uploaded files, including"
+ "their metadata (e.g. date, file size, analysis results, ...)"),
+ RoleNeed("files_list"),
+ default_groups=[USER_GROUP, GUEST_GROUP])
+ FILES_UPLOAD = OctoPrintPermission("File Upload",
+ gettext("Allows users to upload new files"),
+ RoleNeed("files_upload"),
+ default_groups=[USER_GROUP])
+ FILES_DOWNLOAD = OctoPrintPermission("File Download",
+ gettext("Allows users to download files. The GCODE viewer is "
+ "affected by this as well."),
+ RoleNeed("files_download"), FILES_LIST,
+ default_groups=[USER_GROUP, GUEST_GROUP])
+ FILES_DELETE = OctoPrintPermission("File Delete",
+ gettext("Allows users to delete files"),
+ RoleNeed("files_delete"), FILES_LIST,
+ default_groups=[USER_GROUP])
+ FILES_SELECT = OctoPrintPermission("File Select",
+ gettext("Allows to select a file for printing"),
+ RoleNeed("files_select"), FILES_LIST,
+ default_groups=[USER_GROUP])
+
+ PRINT = OctoPrintPermission("Print",
+ gettext("Allows to start, pause and cancel a print job. Includes the \"Select\" "
+ "permission"),
+ RoleNeed("print"), FILES_SELECT,
+ default_groups=[USER_GROUP])
+
+ GCODE_VIEWER = OctoPrintPermission("GCODE viewer",
+ gettext("Allows access to the GCODE viewer. Includes the \"File Download\""
+ "permission."),
+ RoleNeed("gcodeviewer"), FILES_DOWNLOAD,
+ default_groups=[USER_GROUP, GUEST_GROUP])
+
+ MONITOR_TERMINAL = OctoPrintPermission("Terminal",
+ gettext("Allows to watch the terminal tab but not to send commands "
+ "to the printer from it"),
+ RoleNeed("monitor_terminal"),
+ default_groups=[USER_GROUP, GUEST_GROUP])
+
+ CONTROL = OctoPrintPermission("Control",
+ gettext("Allows to control of the printer by using the temperature controls,"
+ "the control tab or sending commands through the terminal."),
+ RoleNeed("control"),
+ default_groups=[USER_GROUP])
+
+ SLICE = OctoPrintPermission("Slice",
+ gettext("Allows to slice files"),
+ RoleNeed("slice"),
+ default_groups=[USER_GROUP])
+
+ TIMELAPSE_LIST = OctoPrintPermission("Timelapse List",
+ gettext("Allows to list timelapse videos"),
+ RoleNeed("timelapse_list"),
+ default_groups=[USER_GROUP, GUEST_GROUP])
+ TIMELAPSE_DOWNLOAD = OctoPrintPermission("Timelapse Download",
+ gettext("Allows to download timelapse videos"),
+ RoleNeed("timelapse_download"),
+ default_groups=[USER_GROUP, GUEST_GROUP])
+ TIMELAPSE_DELETE = OctoPrintPermission("Timelapse Delete",
+ gettext("Allows to delete timelapse videos and unrendered timelapses"),
+ RoleNeed("timelapse_delete"),
+ default_groups=[USER_GROUP])
+ TIMELAPSE_ADMIN = OctoPrintPermission("Timelapse Admin",
+ gettext("Allows to change the timelapse settings and delete or "
+ "render unrendered timelapses. Includes the \"Timelapse List\","
+ "\"Timelapse Delete\" and \"Timelapse Download\" permissions"),
+ RoleNeed("timelapse_admin"), TIMELAPSE_LIST, TIMELAPSE_DOWNLOAD,
+ default_groups=[USER_GROUP])
+
+ SETTINGS = OctoPrintPermission("Settings",
+ gettext("Allows to manage settings"),
+ RoleNeed("settings"),
+ dangerous=True)
+
+
+
+class PermissionAlreadyExists(Exception):
+ def __init__(self, permission):
+ Exception.__init__(self, "Permission %s already exists" % permission)
+
+
+class UnknownPermission(Exception):
+ def __init__(self, permissionname):
+ Exception.__init__(self, "Unknown permission: %s" % permissionname)
diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py
new file mode 100644
index 000000000..fda4c675b
--- /dev/null
+++ b/src/octoprint/access/users.py
@@ -0,0 +1,1182 @@
+# coding=utf-8
+from __future__ import absolute_import, division, print_function
+
+__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
+__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
+
+from flask_login import UserMixin, AnonymousUserMixin
+from werkzeug.local import LocalProxy
+import hashlib
+import os
+import yaml
+import uuid
+import wrapt
+import time
+
+import logging
+
+# noinspection PyCompatibility
+from builtins import range, bytes
+
+from octoprint.settings import settings
+from octoprint.util import atomic_write, to_str, deprecated
+from octoprint.access.permissions import Permissions, OctoPrintPermission
+from octoprint.access.groups import GroupChangeListener, Group
+
+
+class UserManager(GroupChangeListener, object):
+ def __init__(self, group_manager):
+ self._group_manager = group_manager
+ self._group_manager.register_listener(self)
+
+ self._logger = logging.getLogger(__name__)
+ self._session_users_by_session = dict()
+ self._sessionids_by_userid = dict()
+ self._enabled = True
+
+ self._login_status_listeners = []
+
+ def register_login_status_listener(self, listener):
+ self._login_status_listeners.append(listener)
+
+ def unregister_login_status_listener(self, listener):
+ self._login_status_listeners.remove(listener)
+
+ def anonymous_user_factory(self):
+ if self.enabled:
+ return AnonymousUser([self._group_manager.guest_group])
+ else:
+ return AdminUser([self._group_manager.admin_group])
+
+ @property
+ def enabled(self):
+ return self._enabled
+
+ @enabled.setter
+ def enabled(self, value):
+ self._enabled = value
+
+ def enable(self):
+ self._enabled = True
+
+ def disable(self):
+ self._enabled = False
+
+ def login_user(self, user):
+ self._cleanup_sessions()
+
+ if user is None or user.is_anonymous:
+ return
+
+ if isinstance(user, LocalProxy):
+ # noinspection PyProtectedMember
+ user = user._get_current_object()
+
+ if not isinstance(user, User):
+ return None
+
+ if not isinstance(user, SessionUser):
+ user = SessionUser(user)
+
+ self._session_users_by_session[user.session] = user
+
+ userid = user.get_id()
+ if not userid in self._sessionids_by_userid:
+ self._sessionids_by_userid[userid] = set()
+
+ self._sessionids_by_userid[userid].add(user.session)
+
+ for listener in self._login_status_listeners:
+ try: listener.on_user_logged_in(user)
+ except: self._logger.exception("Error in on_user_logged_in on {!r}".format(listener))
+
+ self._logger.debug("Logged in user: %r" % user)
+
+ return user
+
+ def logout_user(self, user):
+ if user is None or user.is_anonymous:
+ return
+
+ if isinstance(user, LocalProxy):
+ user = user._get_current_object()
+
+ if not isinstance(user, SessionUser):
+ return
+
+ userid = user.get_id()
+ sessionid = user.session
+
+ if userid in self._sessionids_by_userid:
+ try:
+ self._sessionids_by_userid[userid].remove(sessionid)
+ except KeyError:
+ pass
+
+ if sessionid in self._session_users_by_session:
+ del self._session_users_by_session[sessionid]
+
+ for listener in self._login_status_listeners:
+ try: listener.on_user_logged_out(user)
+ except: self._logger.exception("Error in on_user_logged_out on {!r}".format(listener))
+
+ self._logger.debug("Logged out user: %r" % user)
+
+ def _cleanup_sessions(self):
+ import time
+ for session, user in self._session_users_by_session.items():
+ if not isinstance(user, SessionUser):
+ continue
+ if user.created + (24 * 60 * 60) < time.time():
+ self.logout_user(user)
+
+ @staticmethod
+ def create_password_hash(password, salt=None):
+ if not salt:
+ salt = settings().get(["accessControl", "salt"])
+ if salt is None:
+ import string
+ from random import choice
+ chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
+ salt = "".join(choice(chars) for _ in range(32))
+ settings().set(["accessControl", "salt"], salt)
+ settings().save()
+
+ return hashlib.sha512(to_str(password, encoding="utf-8", errors="replace") + to_str(salt)).hexdigest()
+
+ def check_password(self, username, password):
+ user = self.find_user(username)
+ if not user:
+ return False
+
+ hash = UserManager.create_password_hash(password)
+ if user.check_password(hash):
+ # new hash matches, correct password
+ return True
+ else:
+ # new hash doesn't match, but maybe the old one does, so check that!
+ oldHash = UserManager.create_password_hash(password, salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW")
+ if user.check_password(oldHash):
+ # old hash matches, we migrate the stored password hash to the new one and return True since it's the correct password
+ self.change_user_password(username, password)
+ return True
+ else:
+ # old hash doesn't match either, wrong password
+ return False
+
+ def add_user(self, username, password, active, permissions, groups, overwrite=False):
+ pass
+
+ def change_user_activation(self, username, active):
+ pass
+
+ def change_user_permissions(self, username, permissions):
+ pass
+
+ def add_permissions_to_user(self, username, permissions):
+ pass
+
+ def remove_permissions_from_user(self, username, permissions):
+ pass
+
+ def change_user_groups(self, username, groups):
+ pass
+
+ def add_groups_to_user(self, username, groups):
+ pass
+
+ def remove_groups_from_user(self, username, groups):
+ pass
+
+ def remove_groups_from_users(self, group):
+ pass
+
+ def change_user_password(self, username, password):
+ pass
+
+ def get_user_setting(self, username, key):
+ return None
+
+ def get_all_user_settings(self, username):
+ return dict()
+
+ def change_user_setting(self, username, key, value):
+ pass
+
+ def change_user_settings(self, username, new_settings):
+ pass
+
+ def remove_user(self, username):
+ if username in self._sessionids_by_userid:
+ sessions = self._sessionids_by_userid[username]
+ for session in sessions:
+ if session in self._session_users_by_session:
+ del self._session_users_by_session[session]
+ del self._sessionids_by_userid[username]
+
+ def find_user(self, userid=None, session=None):
+ if session is not None and session in self._session_users_by_session:
+ user = self._session_users_by_session[session]
+ if userid is None or userid == user.get_id():
+ return user
+
+ return None
+
+ def find_sessions_for(self, matcher):
+ result = []
+ for user in self.get_all_users():
+ if matcher(user):
+ try:
+ session_ids = self._sessionids_by_userid[user.get_id()]
+ for session_id in session_ids:
+ try:
+ result.append(self._session_users_by_session[session_id])
+ except KeyError:
+ # unknown session after all
+ continue
+ except KeyError:
+ # no session for user
+ pass
+ return result
+
+ def get_all_users(self):
+ return []
+
+ def has_been_customized(self):
+ return False
+
+ def on_group_removed(self, group):
+ self._logger.debug("Group {} got removed, removing from all users".format(group.key))
+ self.remove_groups_from_users([group])
+
+ def on_group_permissions_changed(self, group, added=None, removed=None):
+ users = self.find_sessions_for(lambda u: group in u.groups)
+ for listener in self._login_status_listeners:
+ try:
+ for user in users:
+ listener.on_user_modified(user)
+ except:
+ self._logger.exception("Error in on_user_modified on {!r}".format(listener))
+
+ def _trigger_on_user_modified(self, user):
+ if isinstance(user, basestring):
+ # user id
+ users = []
+ try:
+ session_ids = self._sessionids_by_userid[user]
+ for session_id in session_ids:
+ try:
+ users.append(self._session_users_by_session[session_id])
+ except KeyError:
+ # unknown session id
+ continue
+ except KeyError:
+ # no session for user
+ return
+ elif isinstance(user, User) and not isinstance(user, SessionUser):
+ users = self.find_sessions_for(lambda u: u.get_id() == user.get_id())
+ elif isinstance(user, User):
+ users = [user]
+ else:
+ return
+
+ for listener in self._login_status_listeners:
+ try:
+ for user in users:
+ listener.on_user_modified(user)
+ except:
+ self._logger.exception("Error in on_user_modified on {!r}".format(listener))
+
+ def _trigger_on_user_removed(self, username):
+ for listener in self._login_status_listeners:
+ try:
+ listener.on_user_removed(username)
+ except:
+ self._logger.exception("Error in on_user_removed on {!r}".format(listener))
+
+ #~~ Deprecated methods follow
+
+ # TODO: Remove deprecated methods in OctoPrint 1.5.0
+
+ @staticmethod
+ def createPasswordHash(*args, **kwargs):
+ """
+ .. deprecated: 1.4.0
+
+ Replaced by :func:`~UserManager.create_password_hash`
+ """
+ # we can't use the deprecated decorator here since this method is static
+ import warnings
+ warnings.warn("createPasswordHash has been renamed to create_password_hash", DeprecationWarning, stacklevel=2)
+ return UserManager.create_password_hash(*args, **kwargs)
+
+ @deprecated("changeUserRoles has been replaced by change_user_permissions",
+ includedoc="Replaced by :func:`change_user_permissions`",
+ since="1.4.0")
+ def changeUserRoles(self, username, roles):
+ user = self.find_user(username)
+ if user is None:
+ raise UnknownUser(username)
+
+ removed_roles = set(user._roles) - set(roles)
+ self.removeRolesFromUser(username, removed_roles, user=user)
+
+ added_roles = set(roles) - set(user._roles)
+ self.addRolesToUser(username, added_roles, user=user)
+
+ @deprecated("addRolesToUser has been replaced by add_permissions_to_user",
+ includedoc="Replaced by :func:`add_permissions_to_user`",
+ since="1.4.0")
+ def addRolesToUser(self, username, roles, user=None):
+ if user is None:
+ user = self.find_user(username)
+
+ if user is None:
+ raise UnknownUser(username)
+
+ if "admin" in roles:
+ self.add_groups_to_user(username, self._group_manager.admin_group)
+
+ if "user" in roles:
+ self.remove_groups_from_user(username, self._group_manager.user_group)
+
+ @deprecated("removeRolesFromUser has been replaced by remove_permissions_from_user",
+ includedoc="Replaced by :func:`remove_permissions_from_user`",
+ since="1.4.0")
+ def removeRolesFromUser(self, username, roles, user=None):
+ if user is None:
+ user = self.find_user(username)
+
+ if user is None:
+ raise UnknownUser(username)
+
+ if "admin" in roles:
+ self.remove_groups_from_user(username, self._group_manager.admin_group)
+ self.remove_permissions_from_user(username, Permissions.ADMIN)
+
+ if "user" in roles:
+ self.remove_groups_from_user(username, self._group_manager.user_group)
+
+ checkPassword = deprecated("checkPassword has been renamed to check_password",
+ includedoc="Replaced by :func:`check_password`",
+ since="1.4.0")(check_password)
+ addUser = deprecated("addUser has been renamed to add_user",
+ includedoc="Replaced by :func:`add_user`",
+ since="1.4.0")(add_user)
+ changeUserActivation = deprecated("changeUserActivation has been renamed to change_user_activation",
+ includedoc="Replaced by :func:`change_user_activation`",
+ since="1.4.0")(change_user_activation)
+ changeUserPassword = deprecated("changeUserPassword has been renamed to change_user_password",
+ includedoc="Replaced by :func:`change_user_password`",
+ since="1.4.0")(change_user_password)
+ getUserSetting = deprecated("getUserSetting has been renamed to get_user_setting",
+ includedoc="Replaced by :func:`get_user_setting`",
+ since="1.4.0")(get_user_setting)
+ getAllUserSettings = deprecated("getAllUserSettings has been renamed to get_all_user_settings",
+ includedoc="Replaced by :func:`get_all_user_settings`",
+ since="1.4.0")(get_all_user_settings)
+ changeUserSetting = deprecated("changeUserSetting has been renamed to change_user_setting",
+ includedoc="Replaced by :func:`change_user_setting`",
+ since="1.4.0")(change_user_setting)
+ changeUserSettings = deprecated("changeUserSettings has been renamed to change_user_settings",
+ includedoc="Replaced by :func:`change_user_settings`",
+ since="1.4.0")(change_user_settings)
+ removeUser = deprecated("removeUser has been renamed to remove_user",
+ includedoc="Replaced by :func:`remove_user`",
+ since="1.4.0")(remove_user)
+ findUser = deprecated("findUser has been renamed to find_user",
+ includedoc="Replaced by :func:`find_user`",
+ since="1.4.0")(find_user)
+ getAllUsers = deprecated("getAllUsers has been renamed to get_all_users",
+ includedoc="Replaced by :func:`get_all_users`",
+ since="1.4.0")(get_all_users)
+ hasBeenCustomized = deprecated("hasBeenCustomized has been renamed to has_been_customized",
+ includedoc="Replaced by :func:`has_been_customized`",
+ since="1.4.0")(has_been_customized)
+
+
+class LoginStatusListener(object):
+
+ def on_user_logged_in(self, user):
+ pass
+
+ def on_user_logged_out(self, user):
+ pass
+
+ def on_user_modified(self, user):
+ pass
+
+ def on_user_removed(self, userid):
+ pass
+
+
+##~~ FilebasedUserManager, takes available users from users.yaml file
+
+class FilebasedUserManager(UserManager):
+ def __init__(self, group_manager, path=None):
+ UserManager.__init__(self, group_manager)
+
+ if path is None:
+ path = settings().get(["accessControl", "userfile"])
+ if path is None:
+ path = os.path.join(settings().getBaseFolder("base"), "users.yaml")
+
+ self._userfile = path
+
+ self._users = {}
+ self._dirty = False
+
+ self._customized = None
+ self._load()
+
+ def _load(self):
+ if os.path.exists(self._userfile) and os.path.isfile(self._userfile):
+ self._customized = True
+ with open(self._userfile, "r") as f:
+ data = yaml.safe_load(f)
+ for name in data.keys():
+ attributes = data[name]
+ permissions = []
+ if "permissions" in attributes:
+ permissions = attributes["permissions"]
+
+ groups = {self._group_manager.user_group} # the user group is mandatory for all logged in users
+ if "groups" in attributes:
+ groups |= set(attributes["groups"])
+
+ # migrate from roles to permissions
+ if "roles" in attributes and not "permissions" in attributes:
+ self._logger.info("Migrating user {} to new granular permission system".format(name))
+
+ groups |= set(self._migrate_roles_to_groups(attributes["roles"]))
+ self._dirty = True
+
+ apikey = None
+ if "apikey" in attributes:
+ apikey = attributes["apikey"]
+ settings = dict()
+ if "settings" in attributes:
+ settings = attributes["settings"]
+
+ self._users[name] = User(username=name,
+ passwordHash=attributes["password"],
+ active=attributes["active"],
+ permissions=self._to_permissions(*permissions),
+ groups=self._to_groups(*groups),
+ apikey=apikey,
+ settings=settings)
+ for sessionid in self._sessionids_by_userid.get(name, set()):
+ if sessionid in self._session_users_by_session:
+ self._session_users_by_session[sessionid].update_user(self._users[name])
+
+ if self._dirty:
+ self._save()
+
+ else:
+ self._customized = False
+
+ def _save(self, force=False):
+ if not self._dirty and not force:
+ return
+
+ data = {}
+ for name in self._users.keys():
+ user = self._users[name]
+
+ if not user or not isinstance(user, User):
+ continue
+
+ data[name] = {
+ "password": user._passwordHash,
+ "active": user._active,
+ "groups": self._from_groups(*user._groups),
+ "permissions": self._from_permissions(*user._permissions),
+ "apikey": user._apikey,
+ "settings": user._settings,
+
+ # TODO: deprecated, remove in 1.5.0
+ "roles": user._roles
+ }
+
+ with atomic_write(self._userfile, "wb", permissions=0o600, max_permissions=0o666) as f:
+ yaml.safe_dump(data, f, default_flow_style=False, indent=" ", allow_unicode=True)
+ self._dirty = False
+ self._load()
+
+ def _migrate_roles_to_groups(self, roles):
+ # If admin is inside the roles, just return admin group
+ if "admin" in roles:
+ return [self._group_manager.admin_group, self._group_manager.user_group]
+ else:
+ return [self._group_manager.user_group]
+
+ def _refresh_groups(self, user):
+ user._groups = self._to_groups(*map(lambda g: g.key, user.groups))
+
+ def add_user(self, username, password, active=False, permissions=None, groups=None, apikey=None, overwrite=False):
+ if not permissions:
+ permissions = []
+ permissions = self._to_permissions(*permissions)
+
+ if not groups:
+ groups = self._group_manager.default_groups
+ groups = self._to_groups(*groups)
+
+ if username in self._users.keys() and not overwrite:
+ raise UserAlreadyExists(username)
+
+ self._users[username] = User(username, UserManager.create_password_hash(password), active, permissions, groups, apikey=apikey)
+ self._dirty = True
+ self._save()
+
+ def change_user_activation(self, username, active):
+ if username not in self._users.keys():
+ raise UnknownUser(username)
+
+ if self._users[username].is_active != active:
+ self._users[username]._active = active
+ self._dirty = True
+ self._save()
+
+ self._trigger_on_user_modified(username)
+
+ def change_user_permissions(self, username, permissions):
+ if username not in self._users.keys():
+ raise UnknownUser(username)
+
+ user = self._users[username]
+
+ permissions = self._to_permissions(*permissions)
+
+ removed_permissions = list(set(user._permissions) - set(permissions))
+ added_permissions = list(set(permissions) - set(user._permissions))
+
+ if len(removed_permissions) > 0:
+ user.remove_permissions_from_user(removed_permissions)
+ self._dirty = True
+
+ if len(added_permissions) > 0:
+ user.add_permissions_to_user(added_permissions)
+ self._dirty = True
+
+ if self._dirty:
+ self._save()
+ self._trigger_on_user_modified(username)
+
+ def add_permissions_to_user(self, username, permissions):
+ if username not in self._users.keys():
+ raise UnknownUser(username)
+
+ if self._users[username].add_permissions_to_user(self._to_permissions(*permissions)):
+ self._dirty = True
+ self._save()
+ self._trigger_on_user_modified(username)
+
+ def remove_permissions_from_user(self, username, permissions):
+ if username not in self._users.keys():
+ raise UnknownUser(username)
+
+ if self._users[username].remove_permissions_from_user(self._to_permissions(*permissions)):
+ self._dirty = True
+ self._save()
+ self._trigger_on_user_modified(username)
+
+ def remove_permissions_from_users(self, permissions):
+ modified = []
+ for user in self._users.keys():
+ dirty = user.remove_permissions_from_user(self._to_permissions(*permissions))
+ if dirty:
+ self._dirty = True
+ modified.append(user.get_id())
+
+ if self._dirty:
+ self._save()
+ for username in modified:
+ self._trigger_on_user_modified(username)
+
+ def change_user_groups(self, username, groups):
+ if username not in self._users.keys():
+ raise UnknownUser(username)
+
+ user = self._users[username]
+
+ groups = self._to_groups(*groups)
+
+ removed_groups = list(set(user._groups) - set(groups))
+ added_groups = list(set(groups) - set(user._groups))
+
+ if len(removed_groups):
+ self._dirty |= user.remove_groups_from_user(removed_groups)
+ if len(added_groups):
+ self._dirty |= user.add_groups_to_user(added_groups)
+
+ if self._dirty:
+ self._save()
+ self._trigger_on_user_modified(username)
+
+ def add_groups_to_user(self, username, groups, save=True, notify=True):
+ if username not in self._users.keys():
+ raise UnknownUser(username)
+
+ if self._users[username].add_groups_to_user(self._to_groups(*groups)):
+ self._dirty = True
+
+ if save:
+ self._save()
+
+ if notify:
+ self._trigger_on_user_modified(username)
+
+ def remove_groups_from_user(self, username, groups, save=True, notify=True):
+ if username not in self._users.keys():
+ raise UnknownUser(username)
+
+ if self._users[username].remove_groups_from_user(self._to_groups(*groups)):
+ self._dirty = True
+
+ if save:
+ self._save()
+
+ if notify:
+ self._trigger_on_user_modified(username)
+
+ def remove_groups_from_users(self, groups):
+ modified = []
+ for username in self._users.keys():
+ dirty = self._users[username].remove_groups_from_user(self._to_groups(*groups))
+ if dirty:
+ self._dirty = True
+ modified.append(username)
+
+ if self._dirty:
+ self._save()
+
+ for username in modified:
+ self._trigger_on_user_modified(username)
+
+ def change_user_password(self, username, password):
+ if not username in self._users.keys():
+ raise UnknownUser(username)
+
+ passwordHash = UserManager.create_password_hash(password)
+ user = self._users[username]
+ if user._passwordHash != passwordHash:
+ user._passwordHash = passwordHash
+ self._dirty = True
+ self._save()
+
+ def change_user_setting(self, username, key, value):
+ if not username in self._users.keys():
+ raise UnknownUser(username)
+
+ user = self._users[username]
+ old_value = user.get_setting(key)
+ if not old_value or old_value != value:
+ user.set_setting(key, value)
+ self._dirty = self._dirty or old_value != value
+ self._save()
+
+ def change_user_settings(self, username, new_settings):
+ if not username in self._users:
+ raise UnknownUser(username)
+
+ user = self._users[username]
+ for key, value in new_settings.items():
+ old_value = user.get_setting(key)
+ user.set_setting(key, value)
+ self._dirty = self._dirty or old_value != value
+ self._save()
+
+ def get_all_user_settings(self, username):
+ if not username in self._users.keys():
+ raise UnknownUser(username)
+
+ user = self._users[username]
+ return user.get_all_settings()
+
+ def get_user_setting(self, username, key):
+ if not username in self._users.keys():
+ raise UnknownUser(username)
+
+ user = self._users[username]
+ return user.get_setting(key)
+
+ def generate_api_key(self, username):
+ if not username in self._users.keys():
+ raise UnknownUser(username)
+
+ user = self._users[username]
+ user._apikey = ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes))
+ self._dirty = True
+ self._save()
+ return user._apikey
+
+ def delete_api_key(self, username):
+ if not username in self._users.keys():
+ raise UnknownUser(username)
+
+ user = self._users[username]
+ user._apikey = None
+ self._dirty = True
+ self._save()
+
+ def remove_user(self, username):
+ UserManager.remove_user(self, username)
+
+ if not username in self._users.keys():
+ raise UnknownUser(username)
+
+ del self._users[username]
+ self._dirty = True
+ self._save()
+
+ def find_user(self, userid=None, apikey=None, session=None):
+ user = UserManager.find_user(self, userid=userid, session=session)
+
+ if user is not None:
+ return user
+
+ if userid is not None:
+ if userid not in self._users.keys():
+ return None
+ return self._users[userid]
+
+ elif apikey is not None:
+ for user in self._users.values():
+ if apikey == user._apikey:
+ return user
+ return None
+
+ else:
+ return None
+
+ def get_all_users(self):
+ return list(self._users.values())
+
+ def has_been_customized(self):
+ return self._customized
+
+ def on_group_permissions_changed(self, group, added=None, removed=None):
+ # refresh our group references
+ for user in self.get_all_users():
+ if group in user.groups:
+ self._refresh_groups(user)
+
+ # call parent
+ UserManager.on_group_permissions_changed(self, group, added=added, removed=removed)
+
+ #~~ Helpers
+
+ def _to_groups(self, *groups):
+ return list(set(filter(lambda x: x is not None,
+ [self._group_manager._to_group(group) for group in groups])))
+
+ def _to_permissions(self, *permissions):
+ return list(set(filter(lambda x: x is not None,
+ [Permissions.find(permission) for permission in permissions])))
+
+ def _from_groups(self, *groups):
+ return list(set([group.key for group in groups]))
+
+ def _from_permissions(self, *permissions):
+ return list(set([permission.key for permission in permissions]))
+
+ # ~~ Deprecated methods follow
+
+ # TODO: Remove deprecated methods in OctoPrint 1.5.0
+
+ generateApiKey = deprecated("generateApiKey has been renamed to generate_api_key",
+ includedoc="Replaced by :func:`generate_api_key`",
+ since="1.4.0")(generate_api_key)
+ deleteApiKey = deprecated("deleteApiKey has been renamed to delete_api_key",
+ includedoc="Replaced by :func:`delete_api_key`",
+ since="1.4.0")(delete_api_key)
+
+##~~ Exceptions
+
+class UserAlreadyExists(Exception):
+ def __init__(self, username):
+ Exception.__init__(self, "User %s already exists" % username)
+
+
+class UnknownUser(Exception):
+ def __init__(self, username):
+ Exception.__init__(self, "Unknown user: %s" % username)
+
+
+class UnknownRole(Exception):
+ def _init_(self, role):
+ Exception.__init__(self, "Unknown role: %s" % role)
+
+##~~ Refactoring helpers
+
+class MethodReplacedByBooleanProperty(object):
+
+ def __init__(self, name, message, getter):
+ self._name = name
+ self._message = message
+ self._getter = getter
+
+ @property
+ def _attr(self):
+ return self._getter()
+
+ def __call__(self):
+ from warnings import warn
+ warn(DeprecationWarning(self._message.format(name=self._name)), stacklevel=2)
+ return self._attr
+
+ def __eq__(self, other):
+ return self._attr == other
+
+ def __ne__(self, other):
+ return self._attr != other
+
+ def __bool__(self):
+ # Python 3
+ return self._attr
+
+ def __nonzero__(self):
+ # Python 2
+ return self._attr
+
+ def __hash__(self):
+ return hash(self._attr)
+
+ def __repr__(self):
+ return "MethodReplacedByProperty({}, {}, {})".format(self._name, self._message, self._getter)
+
+ def __str__(self):
+ return str(self._attr)
+
+
+# TODO: Remove compatibility layer in OctoPrint 1.5.0
+class FlaskLoginMethodReplacedByBooleanProperty(MethodReplacedByBooleanProperty):
+
+ def __init__(self, name, getter):
+ message = "{name} is now a property in Flask-Login versions >= 0.3.0, which OctoPrint now uses. " + \
+ "Use {name} instead of {name}(). This compatibility layer will be removed in OctoPrint 1.5.0."
+ MethodReplacedByBooleanProperty.__init__(self, name, message, getter)
+
+
+# TODO: Remove compatibility layer in OctoPrint 1.5.0
+class OctoPrintUserMethodReplacedByBooleanProperty(MethodReplacedByBooleanProperty):
+
+ def __init__(self, name, getter):
+ message = "{name} is now a property for consistency reasons with Flask-Login versions >= 0.3.0, which " + \
+ "OctoPrint now uses. Use {name} instead of {name}(). This compatibility layer will be removed " + \
+ "in OctoPrint 1.5.0."
+ MethodReplacedByBooleanProperty.__init__(self, name, message, getter)
+
+##~~ User object
+
+class User(UserMixin):
+ def __init__(self, username, passwordHash, active, permissions=None, groups=None, apikey=None, settings=None):
+ if permissions is None:
+ permissions = []
+ if groups is None:
+ groups = []
+
+ self._username = username
+ self._passwordHash = passwordHash
+ self._active = active
+ self._permissions = permissions
+ self._groups = groups
+ self._apikey = apikey
+
+ if settings is None:
+ settings = dict()
+
+ self._settings = settings
+
+ def as_dict(self):
+ from octoprint.access.permissions import OctoPrintPermission
+ return {
+ "name": self._username,
+ "active": bool(self.is_active),
+ "permissions": map(lambda p: p.key, self._permissions),
+ "groups": map(lambda g: g.key, self._groups),
+ "needs": OctoPrintPermission.convert_needs_to_dict(self.needs),
+ "apikey": self._apikey,
+ "settings": self._settings,
+
+ # TODO: deprecated, remove in 1.5.0
+ "admin": self.has_permission(Permissions.ADMIN),
+ "user": not self.is_anonymous,
+ "roles": self._roles
+ }
+
+ def check_password(self, passwordHash):
+ return self._passwordHash == passwordHash
+
+ def get_id(self):
+ return self.get_name()
+
+ def get_name(self):
+ return self._username
+
+ @property
+ def is_anonymous(self):
+ return FlaskLoginMethodReplacedByBooleanProperty("is_anonymous", lambda: False)
+
+ @property
+ def is_authenticated(self):
+ return FlaskLoginMethodReplacedByBooleanProperty("is_authenticated", lambda: True)
+
+ @property
+ def is_active(self):
+ return FlaskLoginMethodReplacedByBooleanProperty("is_active", lambda: self._active)
+
+ def get_all_settings(self):
+ return self._settings
+
+ def get_setting(self, key):
+ if not isinstance(key, (tuple, list)):
+ path = [key]
+ else:
+ path = key
+
+ return self._get_setting(path)
+
+ def set_setting(self, key, value):
+ if not isinstance(key, (tuple, list)):
+ path = [key]
+ else:
+ path = key
+ return self._set_setting(path, value)
+
+ def _get_setting(self, path):
+ s = self._settings
+ for p in path:
+ if isinstance(s, dict) and p in s:
+ s = s[p]
+ else:
+ return None
+ return s
+
+ def _set_setting(self, path, value):
+ s = self._settings
+ for p in path[:-1]:
+ if p not in s:
+ s[p] = dict()
+
+ if not isinstance(s[p], dict):
+ s[p] = dict()
+
+ s = s[p]
+
+ key = path[-1]
+ s[key] = value
+ return True
+
+ def add_permissions_to_user(self, permissions):
+ # Make sure the permissions variable is of type list
+ if not isinstance(permissions, list):
+ permissions = [permissions]
+
+ assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
+
+ dirty = False
+ for permission in permissions:
+ if permissions not in self._permissions:
+ self._permissions.append(permission)
+ dirty = True
+
+ return dirty
+
+ def remove_permissions_from_user(self, permissions):
+ # Make sure the permissions variable is of type list
+ if not isinstance(permissions, list):
+ permissions = [permissions]
+
+ assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions)))
+
+ dirty = False
+ for permission in permissions:
+ if permission in self._permissions:
+ self._permissions.remove(permission)
+ dirty = True
+
+ return dirty
+
+ def add_groups_to_user(self, groups):
+ # Make sure the groups variable is of type list
+ if not isinstance(groups, list):
+ groups = [groups]
+
+ assert(all(map(lambda p: isinstance(p, Group), groups)))
+
+ dirty = False
+ for group in groups:
+ if group.is_toggleable() and group not in self._groups:
+ self._groups.append(group)
+ dirty = True
+
+ return dirty
+
+ def remove_groups_from_user(self, groups):
+ # Make sure the groups variable is of type list
+ if not isinstance(groups, list):
+ groups = [groups]
+
+ assert(all(map(lambda p: isinstance(p, Group), groups)))
+
+ dirty = False
+ for group in groups:
+ if group.is_toggleable() and group in self._groups:
+ self._groups.remove(group)
+ dirty = True
+
+ return dirty
+
+ @property
+ def permissions(self):
+ if self._permissions is None:
+ return []
+
+ if Permissions.ADMIN in self._permissions:
+ return Permissions.all()
+
+ return filter(lambda p: p is not None, self._permissions)
+
+ @property
+ def groups(self):
+ return list(self._groups)
+
+ @property
+ def needs(self):
+ needs = set()
+
+ for permission in self.permissions:
+ if permission is not None:
+ needs = needs.union(permission.needs)
+
+ for group in self.groups:
+ if group is not None:
+ needs = needs.union(group.needs)
+
+ return needs
+
+ def has_permission(self, permission):
+ return self.has_needs(*permission.needs)
+
+ def has_needs(self, *needs):
+ if Permissions.ADMIN in self._permissions:
+ return True
+ return set(needs).issubset(self.needs)
+
+ def __repr__(self):
+ return "User(id=%s,name=%s,active=%r,user=True,admin=%r,permissions=%s,groups=%s)" % (self.get_id(), self.get_name(), bool(self.is_active), self.has_permission(Permissions.ADMIN), self._permissions, self._groups)
+
+ # ~~ Deprecated methods & properties follow
+
+ # TODO: Remove deprecated methods & properties in OctoPrint 1.5.0
+
+ asDict = deprecated("asDict has been renamed to as_dict",
+ includedoc="Replaced by :func:`as_dict`",
+ since="1.4.0")(as_dict)
+
+ @property
+ @deprecated("is_user is deprecated, please use has_permission", since="1.4.0")
+ def is_user(self):
+ return OctoPrintUserMethodReplacedByBooleanProperty("is_user", lambda: not self.is_anonymous)
+
+ @property
+ @deprecated("is_admin is deprecated, please use has_permission", since="1.4.0")
+ def is_admin(self):
+ return OctoPrintUserMethodReplacedByBooleanProperty("is_admin", lambda: self.has_permission(Permissions.ADMIN))
+
+ @property
+ @deprecated("roles is deprecated, please use has_permission", since="1.4.0")
+ def roles(self):
+ return self._roles
+
+ @property
+ def _roles(self):
+ """Helper for the deprecated self.roles and serializing to yaml"""
+ if self.has_permission(Permissions.ADMIN):
+ return ["user", "admin"]
+ elif not self.is_anonymous:
+ return ["user"]
+ else:
+ return []
+
+
+class AnonymousUser(AnonymousUserMixin, User):
+ def __init__(self, groups):
+ User.__init__(self, None, "", True, [], groups)
+
+ @property
+ def is_anonymous(self):
+ return FlaskLoginMethodReplacedByBooleanProperty("is_anonymous", lambda: True)
+
+ @property
+ def is_authenticated(self):
+ return FlaskLoginMethodReplacedByBooleanProperty("is_authenticated", lambda: False)
+
+ @property
+ def is_active(self):
+ return FlaskLoginMethodReplacedByBooleanProperty("is_active", lambda: self._active)
+
+ def check_password(self, passwordHash):
+ return True
+
+ def as_dict(self):
+ from octoprint.access.permissions import OctoPrintPermission
+ return {
+ "needs": OctoPrintPermission.convert_needs_to_dict(self.needs)
+ }
+
+ def __repr__(self):
+ return "AnonymousUser(groups=%s)" % self._groups
+
+
+class SessionUser(wrapt.ObjectProxy):
+ def __init__(self, user):
+ wrapt.ObjectProxy.__init__(self, user)
+
+ self._self_session = "".join('%02X' % z for z in bytes(uuid.uuid4().bytes))
+ self._self_created = time.time()
+ self._self_touched = time.time()
+
+ @property
+ def session(self):
+ return self._self_session
+
+ @property
+ def created(self):
+ return self._self_created
+
+ @property
+ def touched(self):
+ return self._self_touched
+
+ def touch(self):
+ self._self_touched = time.time()
+
+ @deprecated("SessionUser.get_session() has been deprecated, use SessionUser.session instead", since="1.3.5")
+ def get_session(self):
+ return self.session
+
+ def update_user(self, user):
+ self.__wrapped__ = user
+
+ def as_dict(self):
+ result = self.__wrapped__.as_dict()
+ result.update(dict(session=self.session))
+ return result
+
+ def __repr__(self):
+ return "SessionUser({!r},session={},created={})".format(self.__wrapped__, self.session, self.created)
+
+##~~ User object to use when global api key is used to access the API
+
+class ApiUser(User):
+ def __init__(self, groups):
+ User.__init__(self, "_api", "", True, [], groups)
+
+##~~ User object to use when access control is disabled
+
+class AdminUser(User):
+ def __init__(self, groups):
+ User.__init__(self, "_admin", "", True, [], groups)
diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py
index 7a4133ce9..34ad3f30e 100644
--- a/src/octoprint/cli/__init__.py
+++ b/src/octoprint/cli/__init__.py
@@ -102,13 +102,13 @@ def standard_options(hidden=False):
options = [
factory("--basedir", "-b", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False,
- help="Specify the basedir to use for uploads, timelapses etc."),
+ help="Specify the basedir to use for configs, uploads, timelapses etc."),
factory("--config", "-c", "configfile", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Specify the config file to use."),
factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
- help="Increase logging verbosity"),
+ help="Increase logging verbosity."),
factory("--safe", "safe_mode", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
- help="Enable safe mode; disables all third party plugins")
+ help="Enable safe mode; disables all third party plugins.")
]
return bulk_options(options)
@@ -123,6 +123,7 @@ legacy_options = bulk_options([
hidden_option("--daemon", type=click.Choice(["start", "stop", "restart"]), callback=set_ctx_obj_option),
hidden_option("--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option),
hidden_option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option),
+ hidden_option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option)
])
"""Legacy options available directly on the "octoprint" command in earlier versions.
Kept available for reasons of backwards compatibility, but hidden from the
@@ -135,9 +136,10 @@ from .plugins import plugin_commands
from .dev import dev_commands
from .client import client_commands
from .config import config_commands
+from .analysis import analysis_commands
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
- sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands])
+ sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands])
@standard_options()
@legacy_options
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py
new file mode 100644
index 000000000..34c90d78d
--- /dev/null
+++ b/src/octoprint/cli/analysis.py
@@ -0,0 +1,73 @@
+# coding=utf-8
+from __future__ import absolute_import, division, print_function
+
+__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
+__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
+
+import click
+
+#~~ "octoprint util" commands
+
+@click.group()
+def analysis_commands():
+ pass
+
+@analysis_commands.group(name="analysis")
+def util():
+ """Analysis tools."""
+ pass
+
+
+@util.command(name="gcode")
+@click.option("--throttle", "throttle", type=float, default=None)
+@click.option("--throttle-lines", "throttle_lines", type=int, default=None)
+@click.option("--speed-x", "speedx", type=float, default=6000)
+@click.option("--speed-y", "speedy", type=float, default=6000)
+@click.option("--speed-z", "speedz", type=float, default=300)
+@click.option("--offset", "offset", type=(float, float), multiple=True)
+@click.option("--max-t", "maxt", type=int, default=10)
+@click.option("--g90-extruder", "g90_extruder", is_flag=True)
+@click.option("--progress", "progress", is_flag=True)
+@click.argument("path", type=click.Path())
+def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle_lines, g90_extruder, progress):
+ """Runs a GCODE file analysis."""
+
+ import time
+ import yaml
+ from octoprint.util.gcodeInterpreter import gcode
+
+ throttle_callback = None
+ if throttle:
+ def throttle_callback(filePos, readBytes):
+ if filePos % throttle_lines == 0:
+ # only apply throttle every $throttle_lines lines
+ time.sleep(throttle)
+
+ offsets = offset
+ if offsets is None:
+ offsets = []
+ elif isinstance(offset, tuple):
+ offsets = list(offsets)
+ offsets = [(0, 0)] + offsets
+ if len(offsets) < maxt:
+ offsets += [(0, 0)] * (maxt - len(offsets))
+
+ start_time = time.time()
+
+ progress_callback = None
+ if progress:
+ def progress_callback(percentage):
+ click.echo("PROGRESS:{}".format(percentage))
+ interpreter = gcode(progress_callback=progress_callback)
+
+ interpreter.load(path,
+ speedx=speedx,
+ speedy=speedy,
+ offsets=offsets,
+ throttle=throttle_callback,
+ max_extruders=maxt,
+ g90_extruder=g90_extruder)
+
+ click.echo("DONE:{}s".format(time.time() - start_time))
+ click.echo("RESULTS:")
+ click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py
index 97fcce652..b40f710c3 100644
--- a/src/octoprint/cli/client.py
+++ b/src/octoprint/cli/client.py
@@ -9,7 +9,7 @@ import json
import octoprint_client
-from octoprint.cli import get_ctx_obj_option
+from octoprint.cli import get_ctx_obj_option, bulk_options
from octoprint import init_settings, FatalStartupError
@@ -23,43 +23,66 @@ class JsonStringParamType(click.ParamType):
self.fail("%s is not a valid json string" % value, param, ctx)
+def create_client(settings=None, apikey=None, host=None, port=None, httpuser=None, httppass=None, https=False, prefix=None):
+ assert(host is not None or settings is not None)
+ assert(port is not None or settings is not None)
+ assert(apikey is not None or settings is not None)
+
+ if not host:
+ host = settings.get(["server", "host"])
+ host = host if host != "0.0.0.0" else "127.0.0.1"
+ if not port:
+ port = settings.getInt(["server", "port"])
+
+ if not apikey:
+ apikey = settings.get(["api", "key"])
+
+ baseurl = octoprint_client.build_base_url(https=https,
+ httpuser=httpuser,
+ httppass=httppass,
+ host=host,
+ port=port,
+ prefix=prefix)
+
+ return octoprint_client.Client(baseurl, apikey)
+
+
+client_options = bulk_options([
+ click.option("--apikey", "-a", type=click.STRING),
+ click.option("--host", "-h", type=click.STRING),
+ click.option("--port", "-p", type=click.INT),
+ click.option("--httpuser", type=click.STRING),
+ click.option("--httppass", type=click.STRING),
+ click.option("--https", is_flag=True),
+ click.option("--prefix", type=click.STRING)
+])
+"""Common options to configure an API client."""
+
+
@click.group()
def client_commands():
pass
@client_commands.group("client", context_settings=dict(ignore_unknown_options=True))
-@click.option("--apikey", "-a", type=click.STRING)
-@click.option("--host", "-h", type=click.STRING)
-@click.option("--port", "-p", type=click.INT)
-@click.option("--httpuser", type=click.STRING)
-@click.option("--httppass", type=click.STRING)
-@click.option("--https", is_flag=True)
-@click.option("--prefix", type=click.STRING)
+@client_options
@click.pass_context
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
"""Basic API client."""
try:
+ settings = None
if not host or not port or not apikey:
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
- if not host:
- host = settings.get(["server", "host"])
- host = host if host != "0.0.0.0" else "127.0.0.1"
- if not port:
- port = settings.getInt(["server", "port"])
+ ctx.obj.client = create_client(settings=settings,
+ apikey=apikey,
+ host=host,
+ port=port,
+ httpuser=httpuser,
+ httppass=httppass,
+ https=https,
+ prefix=prefix)
- if not apikey:
- apikey = settings.get(["api", "key"])
-
- baseurl = octoprint_client.build_base_url(https=https,
- httpuser=httpuser,
- httppass=httppass,
- host=host,
- port=port,
- prefix=prefix)
-
- ctx.obj.client = octoprint_client.Client(baseurl, apikey)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the client.", err=True)
diff --git a/src/octoprint/cli/config.py b/src/octoprint/cli/config.py
index 5e21aad80..744cfee43 100644
--- a/src/octoprint/cli/config.py
+++ b/src/octoprint/cli/config.py
@@ -9,7 +9,7 @@ import click
import logging
from octoprint import init_settings, FatalStartupError
-from octoprint.cli import pass_octoprint_ctx, standard_options, bulk_options, get_ctx_obj_option
+from octoprint.cli import standard_options, bulk_options, get_ctx_obj_option
import yaml
import json
@@ -54,7 +54,7 @@ def config(ctx):
ctx.obj.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
except FatalStartupError as e:
click.echo(e.message, err=True)
- click.echo("There was a fatal error initializing the client.", err=True)
+ click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
@@ -70,7 +70,6 @@ def config(ctx):
help="Interpret value as int")
@click.option("--json", "as_json", is_flag=True,
help="Parse value from json")
-@pass_octoprint_ctx
@click.pass_context
def set_command(ctx, path, value, as_bool, as_float, as_int, as_json):
"""Sets a config path to the provided value."""
@@ -163,7 +162,6 @@ def insert_value_command(ctx, path, index, value, as_json=False):
@click.argument("path", type=click.STRING)
@click.argument("value", type=click.STRING)
@click.option("--json", "as_json", is_flag=True)
-@pass_octoprint_ctx
@click.pass_context
def remove_value_command(ctx, path, value, as_json=False):
"""Removes value from list at config path."""
@@ -216,3 +214,28 @@ def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
output = pprint.pformat(value)
click.echo(output)
+
+
+@config.command(name="effective")
+@click.option("--json", "as_json", is_flag=True,
+ help="Output value formatted as JSON")
+@click.option("--yaml", "as_yaml", is_flag=True,
+ help="Output value formatted as YAML")
+@click.option("--raw", "as_raw", is_flag=True,
+ help="Output value as raw string representation")
+@standard_options(hidden=True)
+@click.pass_context
+def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False):
+ """Retrieves the full effective config."""
+ value = ctx.obj.settings.effective
+
+ if as_json:
+ output = json.dumps(value)
+ elif as_yaml:
+ output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True)
+ elif as_raw:
+ output = value
+ else:
+ output = pprint.pformat(value)
+
+ click.echo(output)
diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py
index 8b13eb1c5..facfc80cb 100644
--- a/src/octoprint/cli/plugins.py
+++ b/src/octoprint/cli/plugins.py
@@ -43,6 +43,7 @@ class OctoPrintPluginCommands(click.MultiCommand):
if self._initialized:
return
+ click.echo("Initializing settings & plugin subsystem...")
if ctx.obj is None:
ctx.obj = OctoPrintContext()
@@ -51,7 +52,8 @@ class OctoPrintPluginCommands(click.MultiCommand):
from octoprint import init_settings, init_pluginsystem, FatalStartupError
try:
self.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
- self.plugin_manager = init_pluginsystem(self.settings, safe_mode=get_ctx_obj_option(ctx, "safe_mode", False))
+ self.plugin_manager = init_pluginsystem(self.settings,
+ safe_mode=get_ctx_obj_option(ctx, "safe_mode", False))
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings or the plugin system.", err=True)
@@ -60,6 +62,8 @@ class OctoPrintPluginCommands(click.MultiCommand):
# fetch registered hooks
self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands")
+ logging.basicConfig(level=logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARN)
+
self._initialized = True
def list_commands(self, ctx):
@@ -88,14 +92,14 @@ class OctoPrintPluginCommands(click.MultiCommand):
continue
result[name + self.sep + command.name] = command
except:
- self._logger.exception("Error while retrieving cli commants for plugin {}".format(name))
+ self._logger.exception("Error while retrieving cli commands for plugin {}".format(name))
return result
@click.group()
@pass_octoprint_ctx
def plugin_commands(obj):
- logging.basicConfig(level=logging.DEBUG if obj.verbosity > 0 else logging.WARN)
+ pass
@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands)
def plugins():
diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py
index cfadc559b..1e7a98f19 100644
--- a/src/octoprint/cli/server.py
+++ b/src/octoprint/cli/server.py
@@ -11,7 +11,8 @@ import sys
from octoprint.cli import bulk_options, standard_options, set_ctx_obj_option, get_ctx_obj_option
-def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode, octoprint_daemon=None):
+def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode,
+ ignore_blacklist, octoprint_daemon=None):
"""Initializes the environment and starts up the server."""
from octoprint import init_platform, __display_version__, FatalStartupError
@@ -19,7 +20,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
def log_startup(recorder=None, safe_mode=None, **kwargs):
from octoprint.logging import get_divider_line
- logger = logging.getLogger("octoprint.server")
+ logger = logging.getLogger("octoprint.startup")
logger.info(get_divider_line("*"))
logger.info("Starting OctoPrint {}".format(__display_version__))
@@ -47,7 +48,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
"https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl")
logger.info(get_divider_line("*"))
- def log_register_rollover(safe_mode=None, plugin_manager=None, **kwargs):
+ def log_register_rollover(safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs):
from octoprint.logging import get_handler, log_to_handler, get_divider_line
from octoprint.logging.handlers import OctoPrintLogHandler
@@ -66,20 +67,24 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
if safe_mode:
_log("SAFE MODE is active. Third party plugins are disabled!")
plugin_manager.log_all_plugins(only_to_handler=handler)
+ environment_detector.log_detected_environment(only_to_handler=handler)
_log(get_divider_line("-"))
OctoPrintLogHandler.registerRolloverCallback(rollover_callback)
try:
- settings, _, safe_mode, plugin_manager = init_platform(basedir,
- configfile,
- logging_file=logging_config,
- debug=debug,
- verbosity=verbosity,
- uncaught_logger=__name__,
- safe_mode=safe_mode,
- after_safe_mode=log_startup,
- after_plugin_manager=log_register_rollover)
+ components = init_platform(basedir, configfile,
+ logging_file=logging_config,
+ debug=debug,
+ verbosity=verbosity,
+ uncaught_logger=__name__,
+ safe_mode=safe_mode,
+ ignore_blacklist=ignore_blacklist,
+ after_safe_mode=log_startup,
+ after_environment_detector=log_register_rollover)
+
+ settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components
+
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error starting up OctoPrint.", err=True)
@@ -87,6 +92,9 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
from octoprint.server import Server
octoprint_server = Server(settings=settings,
plugin_manager=plugin_manager,
+ event_manager=event_manager,
+ connectivity_checker=connectivity_checker,
+ environment_detector=environment_detector,
host=host,
port=port,
debug=debug,
@@ -107,7 +115,9 @@ server_options = bulk_options([
click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option,
help="Allow OctoPrint to run as user root."),
click.option("--debug", is_flag=True, callback=set_ctx_obj_option,
- help="Enable debug mode.")
+ help="Enable debug mode."),
+ click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option,
+ help="Disable processing of the plugin blacklist.")
])
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``,
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
@@ -125,9 +135,30 @@ def server_commands():
pass
+@server_commands.command(name="safemode")
+@standard_options()
+@click.pass_context
+def enable_safemode(ctx, **kwargs):
+ """Sets the safe mode flag for the next start."""
+ from octoprint import init_settings, FatalStartupError
+
+ logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
+ try:
+ settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
+ except FatalStartupError as e:
+ click.echo(e.message, err=True)
+ click.echo("There was a fatal error initializing the settings manager.", err=True)
+ ctx.exit(-1)
+
+ settings.setBoolean(["server", "startOnceInSafeMode"], True)
+ settings.save()
+
+ click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
+
+
@server_commands.command(name="serve")
+@standard_options()
@server_options
-@standard_options(hidden=True)
@click.pass_context
def serve_command(ctx, **kwargs):
"""Starts the OctoPrint server."""
@@ -145,18 +176,20 @@ def serve_command(ctx, **kwargs):
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = get_value("safe_mode")
+ ignore_blacklist = get_value("ignore_blacklist")
run_server(basedir, configfile, host, port, debug,
- allow_root, logging, verbosity, safe_mode)
+ allow_root, logging, verbosity, safe_mode,
+ ignore_blacklist)
if sys.platform != "win32" and sys.platform != "darwin":
# we do not support daemon mode under windows or macosx
@server_commands.command(name="daemon")
+ @standard_options()
@server_options
@daemon_options
- @standard_options(hidden=True)
@click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]),
metavar="start|stop|restart|status")
@click.pass_context
@@ -164,7 +197,7 @@ if sys.platform != "win32" and sys.platform != "darwin":
"""
Starts, stops or restarts in daemon mode.
- Please note that daemon mode is only supported under Linux right now.
+ Please note that daemon mode is not supported under Windows and MacOSX right now.
"""
def get_value(key):
@@ -181,6 +214,7 @@ if sys.platform != "win32" and sys.platform != "darwin":
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = get_value("safe_mode")
+ ignore_blacklist = get_value("ignore_blacklist")
if pid is None:
click.echo("No path to a pidfile set",
@@ -189,7 +223,8 @@ if sys.platform != "win32" and sys.platform != "darwin":
from octoprint.daemon import Daemon
class OctoPrintDaemon(Daemon):
- def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode):
+ def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity,
+ safe_mode, ignore_blacklist):
Daemon.__init__(self, pidfile)
self._basedir = basedir
@@ -201,14 +236,15 @@ if sys.platform != "win32" and sys.platform != "darwin":
self._logging_config = logging_config
self._verbosity = verbosity
self._safe_mode = safe_mode
+ self._ignore_blacklist = ignore_blacklist
def run(self):
run_server(self._basedir, self._configfile, self._host, self._port, self._debug,
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
- octoprint_daemon=self)
+ self._ignore_blacklist, octoprint_daemon=self)
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity,
- safe_mode)
+ safe_mode, ignore_blacklist)
if command == "start":
octoprint_daemon.start()
diff --git a/src/octoprint/daemon.py b/src/octoprint/daemon.py
index b6888271b..6b42e1d88 100644
--- a/src/octoprint/daemon.py
+++ b/src/octoprint/daemon.py
@@ -6,7 +6,7 @@ Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon
"""
from __future__ import absolute_import, division, print_function
-import sys, os, time, signal, io
+import sys, os, time, signal
class Daemon:
"""
diff --git a/src/octoprint/environment.py b/src/octoprint/environment.py
new file mode 100644
index 000000000..4d539297e
--- /dev/null
+++ b/src/octoprint/environment.py
@@ -0,0 +1,167 @@
+# coding=utf-8
+from __future__ import absolute_import
+
+__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
+__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
+
+import copy
+import logging
+import os
+import platform
+import sys
+import threading
+import yaml
+
+import psutil
+
+from octoprint.plugin import EnvironmentDetectionPlugin
+from octoprint.util.platform import get_os
+
+class EnvironmentDetector(object):
+
+ def __init__(self, plugin_manager):
+ self._plugin_manager = plugin_manager
+
+ self._cache = None
+ self._cache_lock = threading.RLock()
+
+ self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
+
+ self._logger = logging.getLogger(__name__)
+
+ @property
+ def environment(self):
+ with self._cache_lock:
+ if self._cache is None:
+ self.run_detection()
+ return copy.deepcopy(self._cache)
+
+ def run_detection(self, notify_plugins=True):
+ try:
+ environment = dict()
+ environment["os"] = self._detect_os()
+ environment["python"] = self._detect_python()
+ environment["hardware"] = self._detect_hardware()
+
+ plugin_result = self._detect_from_plugins()
+ if plugin_result:
+ environment["plugins"] = plugin_result
+
+ with self._cache_lock:
+ self._cache = environment
+
+ if notify_plugins:
+ self.notify_plugins()
+
+ return environment
+ except:
+ self._logger.exception("Unexpected error while detecting environment")
+ with self._cache_lock:
+ self._cache = dict()
+ return self._cache
+
+ def _detect_os(self):
+ return dict(id=get_os(),
+ platform=sys.platform)
+
+ def _detect_python(self):
+ result = dict(version="unknown",
+ pip="unknown")
+
+ # determine python version
+ try:
+ result["version"] = platform.python_version()
+ except:
+ self._logger.exception("Error detecting python version")
+
+ # determine if we are running from a virtual environment
+ try:
+ if hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)):
+ result["virtualenv"] = sys.prefix
+ except:
+ self._logger.exception("Error detecting whether we are running in a virtual environment")
+
+ # try to find pip version
+ try:
+ import pkg_resources
+ result["pip"] = pkg_resources.get_distribution("pip").version
+ except:
+ self._logger.exception("Error detecting pip version")
+
+ return result
+
+ def _detect_hardware(self):
+ result = dict(cores="unknown",
+ freq="unknown",
+ ram="unknown")
+
+ try:
+ cores = psutil.cpu_count()
+ cpu_freq = psutil.cpu_freq()
+ ram = psutil.virtual_memory()
+ if cores:
+ result["cores"] = cores
+ if cpu_freq and hasattr(cpu_freq, "max"):
+ result["freq"] = cpu_freq.max
+ if ram and hasattr(ram, "total"):
+ result["ram"] = ram.total
+ except:
+ self._logger.exception("Error while detecting hardware environment")
+
+ return result
+
+ def _detect_from_plugins(self):
+ result = dict()
+
+ for implementation in self._environment_plugins:
+ try:
+ additional = implementation.get_additional_environment()
+ if additional is not None and isinstance(additional, dict) and len(additional):
+ result[implementation._identifier] = additional
+ except:
+ self._logger.exception("Error while fetching additional "
+ "environment data from plugin {}".format(implementation._identifier))
+
+ return result
+
+ def log_detected_environment(self, only_to_handler=None):
+ def _log(message, level=logging.INFO):
+ if only_to_handler is not None:
+ import octoprint.logging
+ octoprint.logging.log_to_handler(self._logger, only_to_handler, level, message, [])
+ else:
+ self._logger.log(level, message)
+
+ try:
+ _log(self._format())
+ except:
+ self._logger.exception("Error logging detected environment")
+
+ def _format(self):
+ with self._cache_lock:
+ if self._cache is None:
+ self.run_detection()
+ environment = copy.deepcopy(self._cache)
+
+ dumped_environment = yaml.safe_dump(environment,
+ default_flow_style=False,
+ indent=" ",
+ allow_unicode=True).strip()
+ environment_lines = "\n".join(map(lambda l: "| {}".format(l), dumped_environment.split("\n")))
+ return u"Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"],
+ environment["os"]["id"].title(),
+ environment["os"]["platform"],
+ environment_lines)
+
+ def notify_plugins(self):
+ with self._cache_lock:
+ if self._cache is None:
+ self.run_detection(notify_plugins=False)
+ environment = copy.deepcopy(self._cache)
+
+ for implementation in self._environment_plugins:
+ try:
+ implementation.on_environment_detected(environment)
+ except:
+ self._logger.exception("Error while sending environment "
+ "detection result to plugin {}".format(implementation._identifier))
diff --git a/src/octoprint/events.py b/src/octoprint/events.py
index c8630e59a..5a638a128 100644
--- a/src/octoprint/events.py
+++ b/src/octoprint/events.py
@@ -27,9 +27,10 @@ def all_events():
class Events(object):
- # application startup
+ # server
STARTUP = "Startup"
SHUTDOWN = "Shutdown"
+ CONNECTIVITY_CHANGED = "ConnectivityChanged"
# connect/disconnect to printer
CONNECTING = "Connecting"
@@ -39,6 +40,7 @@ class Events(object):
# State changes
PRINTER_STATE_CHANGED = "PrinterStateChanged"
+ PRINTER_RESET = "PrinterReset"
# connect/disconnect by client
CLIENT_OPENED = "ClientOpened"
@@ -53,19 +55,21 @@ class Events(object):
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
- FILE_ADDED = "FileAdded",
- FILE_REMOVED = "FileRemoved",
- FOLDER_ADDED = "FolderAdded",
- FOLDER_REMOVED = "FolderRemoved",
+ FILE_ADDED = "FileAdded"
+ FILE_REMOVED = "FileRemoved"
+ FOLDER_ADDED = "FolderAdded"
+ FOLDER_REMOVED = "FolderRemoved"
# SD Upload
TRANSFER_STARTED = "TransferStarted"
TRANSFER_DONE = "TransferDone"
+ TRANSFER_FAILED = "TransferFailed"
# print job
PRINT_STARTED = "PrintStarted"
PRINT_DONE = "PrintDone"
PRINT_FAILED = "PrintFailed"
+ PRINT_CANCELLING = "PrintCancelling"
PRINT_CANCELLED = "PrintCancelled"
PRINT_PAUSED = "PrintPaused"
PRINT_RESUMED = "PrintResumed"
@@ -84,6 +88,8 @@ class Events(object):
EJECT = "Eject"
E_STOP = "EStop"
POSITION_UPDATE = "PositionUpdate"
+ FIRMWARE_DATA = "FirmwareData"
+ TOOL_CHANGE = "ToolChange"
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
# Timelapse
@@ -130,9 +136,11 @@ class EventManager(object):
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
+ self._startup_signaled = False
self._shutdown_signaled = False
self._queue = queue.Queue()
+ self._held_back = queue.Queue()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
@@ -159,7 +167,8 @@ class EventManager(object):
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
"on_event",
- args=(event, payload))
+ args=(event, payload),
+ initialized=True)
self._logger.info("Event loop shut down")
except:
self._logger.exception("Ooops, the event bus worker loop crashed")
@@ -175,7 +184,30 @@ class EventManager(object):
payload being a payload object specific to the event.
"""
- self._queue.put((event, payload))
+ send_held_back = False
+ if event == Events.STARTUP:
+ self._logger.info("Processing startup event, this is our first event")
+ self._startup_signaled = True
+ send_held_back = True
+
+ self._enqueue(event, payload)
+
+ if send_held_back:
+ self._logger.info("Adding {} events to queue that "
+ "were held back before startup event".format(self._held_back.qsize()))
+ while True:
+ try:
+ self._queue.put(self._held_back.get(block=False))
+ except queue.Empty:
+ break
+
+ def _enqueue(self, event, payload):
+ if self._startup_signaled:
+ q = self._queue
+ else:
+ q = self._held_back
+
+ q.put((event, payload))
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables":
# when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
@@ -183,7 +215,7 @@ class EventManager(object):
import copy
legacy_payload = copy.deepcopy(payload)
legacy_payload["type"] = "gcode"
- self._queue.put((event, legacy_payload))
+ q.put((event, legacy_payload))
def subscribe(self, event, callback):
"""
@@ -202,12 +234,12 @@ class EventManager(object):
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
"""
- if not callback in self._registeredListeners[event]:
- # callback not subscribed to event, just return
- return
-
- self._registeredListeners[event].remove(callback)
- self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event))
+ try:
+ self._registeredListeners[event].remove(callback)
+ self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event))
+ except ValueError:
+ # not registered
+ pass
def join(self, timeout=None):
self._worker.join(timeout)
diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py
index 856acc8ef..398201609 100644
--- a/src/octoprint/filemanager/__init__.py
+++ b/src/octoprint/filemanager/__init__.py
@@ -40,13 +40,47 @@ def full_extension_tree():
)
)
+ def leaf_merger(a, b):
+ supported_leaf_types = (ContentTypeMapping, ContentTypeDetector, list)
+ if not isinstance(a, supported_leaf_types) or not isinstance(b, supported_leaf_types):
+ raise ValueError()
+
+ if isinstance(a, ContentTypeDetector) and isinstance(b, ContentTypeMapping):
+ raise ValueError()
+
+ if isinstance(a, ContentTypeMapping) and isinstance(b, ContentTypeDetector):
+ raise ValueError()
+
+ a_list = a if isinstance(a, list) else a.extensions
+ b_list = b if isinstance(b, list) else b.extensions
+ merged = a_list + b_list
+
+ content_type = None
+ if isinstance(b, ContentTypeMapping):
+ content_type = b.content_type
+ elif isinstance(a, ContentTypeMapping):
+ content_type = a.content_type
+
+ detector = None
+ if isinstance(b, ContentTypeDetector):
+ detector = b.detector
+ elif isinstance(a, ContentTypeDetector):
+ detector = a.detector
+
+ if content_type is not None:
+ return ContentTypeMapping(merged, content_type)
+ elif detector is not None:
+ return ContentTypeDetector(merged, detector)
+ else:
+ return merged
+
extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree")
for name, hook in extension_tree_hooks.items():
try:
hook_result = hook()
if hook_result is None or not isinstance(hook_result, dict):
continue
- result = octoprint.util.dict_merge(result, hook_result)
+ result = octoprint.util.dict_merge(result, hook_result, leaf_merger=leaf_merger)
except:
logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from hook {name}".format(name=name))
@@ -180,9 +214,12 @@ class FileManager(object):
import octoprint.settings
self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml")
- def initialize(self):
+ def initialize(self, process_backlog=False):
self.reload_plugins()
+ if process_backlog:
+ self.process_backlog()
+ def process_backlog(self):
def worker():
self._logger.info("Adding backlog items from all storage types to analysis queue...".format(**locals()))
for storage_type, storage_manager in self._storage_managers.items():
@@ -253,11 +290,33 @@ class FileManager(object):
def default_slicer(self):
return self._slicing_manager.default_slicer
+ def analyse(self, destination, path, printer_profile_id=None):
+ if not self.file_exists(destination, path):
+ return
+
+ if printer_profile_id is None:
+ printer_profile = self._printer_profile_manager.get_current_or_default()
+ else:
+ printer_profile = self._printer_profile_manager.get(printer_profile_id)
+ if printer_profile is None:
+ printer_profile = self._printer_profile_manager.get_current_or_default()
+
+ queue_entry = self._analysis_queue_entry(destination, path)
+ self._analysis_queue.dequeue(queue_entry)
+
+ queue_entry = self._analysis_queue_entry(destination, path, printer_profile=printer_profile)
+ if queue_entry:
+ return self._analysis_queue.enqueue(queue_entry, high_priority=True)
+
+ return False
+
def slice(self, slicer_name, source_location, source_path, dest_location, dest_path,
- position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None):
+ position=None, profile=None, printer_profile_id=None, overrides=None, display=None,
+ callback=None, callback_args=None):
absolute_source_path = self.path_on_disk(source_location, source_path)
- def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
+ def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time,
+ printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
try:
if _error:
eventManager().fire(Events.SLICING_FAILED, dict(stl=source_path,
@@ -282,7 +341,9 @@ class FileManager(object):
io.FileIO(tmp_path, "rb"))
printer_profile = self._printer_profile_manager.get(printer_profile_id)
- self.add_file(dest_location, dest_path, file_obj, links=links, allow_overwrite=True, printer_profile=printer_profile, analysis=_analysis)
+ self.add_file(dest_location, dest_path, file_obj,
+ display=display, links=links, allow_overwrite=True,
+ printer_profile=printer_profile, analysis=_analysis)
end_time = time.time()
eventManager().fire(Events.SLICING_DONE, dict(stl=source_path,
@@ -394,7 +455,7 @@ class FileManager(object):
result[dst] = self._storage_managers[dst].list_files(path=path, filter=filter, recursive=recursive)
return result
- def add_file(self, destination, path, file_object, links=None, allow_overwrite=False, printer_profile=None, analysis=None):
+ def add_file(self, destination, path, file_object, links=None, allow_overwrite=False, printer_profile=None, analysis=None, display=None):
if printer_profile is None:
printer_profile = self._printer_profile_manager.get_current_or_default()
@@ -409,9 +470,11 @@ class FileManager(object):
file_object = hook_file_object
queue_entry = self._analysis_queue_entry(destination, path)
- self._analysis_queue.dequeue(queue_entry)
- path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
+ if queue_entry is not None:
+ self._analysis_queue.dequeue(queue_entry)
+
+ path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite, display=display)
if analysis is None:
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile)
@@ -478,8 +541,8 @@ class FileManager(object):
type=get_file_type(dst_name)))
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
- def add_folder(self, destination, path, ignore_existing=True):
- path_in_storage = self._storage(destination).add_folder(path, ignore_existing=ignore_existing)
+ def add_folder(self, destination, path, ignore_existing=True, display=None):
+ path_in_storage = self._storage(destination).add_folder(path, ignore_existing=ignore_existing, display=display)
_, name = self._storage(destination).split_path(path_in_storage)
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
@@ -502,7 +565,7 @@ class FileManager(object):
def copy_folder(self, destination, source, dst):
path_in_storage = self._storage(destination).copy_folder(source, dst)
- self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
+ self._determine_analysis_backlog(destination, self._storage(destination), root=path_in_storage)
_, name = self._storage(destination).split_path(path_in_storage)
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
@@ -513,13 +576,12 @@ class FileManager(object):
def move_folder(self, destination, source, dst):
self._analysis_queue.dequeue_folder(destination, source)
self._analysis_queue.pause()
- self._storage(destination).move_folder(source, dst)
- self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
+ dst_path_in_storage = self._storage(destination).move_folder(source, dst)
+ self._determine_analysis_backlog(destination, self._storage(destination), root=dst_path_in_storage)
self._analysis_queue.resume()
source_path_in_storage = self._storage(destination).path_in_storage(source)
_, source_name = self._storage(destination).split_path(source_path_in_storage)
- dst_path_in_storage = self._storage(destination).path_in_storage(destination)
_, dst_name = self._storage(destination).split_path(dst_path_in_storage)
eventManager().fire(Events.FOLDER_REMOVED, dict(storage=destination,
@@ -602,6 +664,9 @@ class FileManager(object):
def path_on_disk(self, destination, path):
return self._storage(destination).path_on_disk(path)
+ def canonicalize(self, destination, path):
+ return self._storage(destination).canonicalize(path)
+
def sanitize(self, destination, path):
return self._storage(destination).sanitize(path)
diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py
index a774cc378..11c5aac29 100644
--- a/src/octoprint/filemanager/analysis.py
+++ b/src/octoprint/filemanager/analysis.py
@@ -19,8 +19,6 @@ import time
from octoprint.events import Events, eventManager
from octoprint.settings import settings
-import octoprint.util.gcodeInterpreter as gcodeInterpreter
-
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")):
"""
@@ -78,6 +76,9 @@ class AnalysisQueue(object):
self._callbacks.remove(callback)
def enqueue(self, entry, high_priority=False):
+ if entry is None:
+ return False
+
if not entry.type in self._queues:
return False
@@ -85,6 +86,9 @@ class AnalysisQueue(object):
return True
def dequeue(self, entry):
+ if entry is None:
+ return False
+
if not entry.type in self._queues:
return False
@@ -305,39 +309,95 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
* The extruded volume in cm³
"""
- def _do_analysis(self, high_priority=False):
- try:
- throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
- throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
- if throttle > 0:
- def throttle_callback(filePos, readBytes):
- if filePos % throttle_lines == 0:
- # only apply throttle every 100 lines
- time.sleep(throttle)
- else:
- throttle_callback = None
+ def __init__(self, finished_callback):
+ AbstractAnalysisQueue.__init__(self, finished_callback)
- self._gcode = gcodeInterpreter.gcode()
- self._gcode.load(self._current.absolute_path, self._current.printer_profile, throttle=throttle_callback)
+ self._aborted = False
+ self._reenqueue = False
+
+ def _do_analysis(self, high_priority=False):
+ import sarge
+ import sys
+ import yaml
+
+ try:
+ throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
+ else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
+ throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
+ max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
+ g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
+ speedx = self._current.printer_profile["axes"]["x"]["speed"]
+ speedy = self._current.printer_profile["axes"]["y"]["speed"]
+ offsets = self._current.printer_profile["extruder"]["offsets"]
+
+ command = [sys.executable, "-m", "octoprint", "analysis", "gcode",
+ "--speed-x={}".format(speedx), "--speed-y={}".format(speedy),
+ "--max-t={}".format(max_extruders), "--throttle={}".format(throttle),
+ "--throttle-lines={}".format(throttle_lines)]
+ for offset in offsets[1:]:
+ command += ["--offset", str(offset[0]), str(offset[1])]
+ if g90_extruder:
+ command += ["--g90-extruder"]
+ command.append(self._current.absolute_path)
+
+ self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
+
+ self._aborted = False
+ p = sarge.run(command, async=True, stdout=sarge.Capture())
+
+ while len(p.commands) == 0:
+ # somewhat ugly... we can't use wait_events because
+ # the events might not be all set if an exception
+ # by sarge is triggered within the async process
+ # thread
+ time.sleep(0.01)
+
+ # by now we should have a command, let's wait for its
+ # process to have been prepared
+ p.commands[0].process_ready.wait()
+
+ if not p.commands[0].process:
+ # the process might have been set to None in case of any exception
+ raise RuntimeError(u"Error while trying to run command {}".format(" ".join(command)))
+
+ try:
+ # let's wait for stuff to finish
+ while p.returncode is None:
+ if self._aborted:
+ # oh, we shall abort, let's do so!
+ p.commands[0].terminate()
+ raise AnalysisAborted(reenqueue=self._reenqueue)
+
+ # else continue
+ p.commands[0].poll()
+ finally:
+ p.close()
+
+ output = p.stdout.text
+ self._logger.debug("Got output: {!r}".format(output))
+
+ if not "RESULTS:" in output:
+ raise RuntimeError("No analysis result found")
+
+ _, output = output.split("RESULTS:")
+ analysis = yaml.safe_load(output)
result = dict()
- result["printingArea"] = self._gcode.printing_area
- result["dimensions"] = self._gcode.dimensions
- if self._gcode.totalMoveTimeMinute:
- result["estimatedPrintTime"] = self._gcode.totalMoveTimeMinute * 60
- if self._gcode.extrusionAmount:
+ result["printingArea"] = analysis["printing_area"]
+ result["dimensions"] = analysis["dimensions"]
+ if analysis["total_time"]:
+ result["estimatedPrintTime"] = analysis["total_time"] * 60
+ if analysis["extrusion_length"]:
result["filament"] = dict()
- for i in range(len(self._gcode.extrusionAmount)):
+ for i in range(len(analysis["extrusion_length"])):
result["filament"]["tool%d" % i] = {
- "length": self._gcode.extrusionAmount[i],
- "volume": self._gcode.extrusionVolume[i]
+ "length": analysis["extrusion_length"][i],
+ "volume": analysis["extrusion_volume"][i]
}
return result
- except gcodeInterpreter.AnalysisAborted as ex:
- raise AnalysisAborted(reenqueue=ex.reenqueue)
finally:
self._gcode = None
def _do_abort(self, reenqueue=True):
- if self._gcode:
- self._gcode.abort(reenqueue=reenqueue)
+ self._aborted = True
+ self._reenqueue = reenqueue
diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py
index e63e49a81..cd6f76519 100644
--- a/src/octoprint/filemanager/storage.py
+++ b/src/octoprint/filemanager/storage.py
@@ -10,6 +10,7 @@ import logging
import os
import pylru
import shutil
+import re
try:
from os import scandir, walk
@@ -22,9 +23,12 @@ from copy import deepcopy
from past.builtins import basestring
+from emoji import demojize
+from slugify import Slugify
+
import octoprint.filemanager
-from octoprint.util import is_hidden_path
+from octoprint.util import is_hidden_path, to_unicode
class StorageInterface(object):
"""
@@ -149,12 +153,13 @@ class StorageInterface(object):
from root of base folder
:param function filter: a filter that matches the files that are to be returned, may be left out in which case no
filtering will take place
- :param bool recursive: will also step into sub folders for building the complete list if set to True
+ :param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only
+ do one step down into sub folders to be able to populate the ``children``.
:return: a dictionary mapping entry names to entry data that represents the whole file list
"""
raise NotImplementedError()
- def add_folder(self, path, ignore_existing=True):
+ def add_folder(self, path, ignore_existing=True, display=None):
"""
Adds a folder as ``path``
@@ -162,6 +167,7 @@ class StorageInterface(object):
:param string path: the path of the new folder
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
+ :param unicode display: display name of the folder
:return: the sanitized name of the new folder to be used for future references to the folder
"""
raise NotImplementedError()
@@ -171,14 +177,14 @@ class StorageInterface(object):
Removes the folder at ``path``
:param string path: the path of the folder to remove
- :param bool recursive: if set to True, contained folders and files will also be removed, otherwise and error will
- be raised if the folder is not empty (apart from ``.metadata.yaml``) when it's to be removed
+ :param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will
+ be raised if the folder is not empty (apart from any metadata files) when it's to be removed
"""
raise NotImplementedError()
def copy_folder(self, source, destination):
"""
- Copys the folder ``source`` to ``destination``
+ Copies the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
@@ -198,7 +204,7 @@ class StorageInterface(object):
"""
raise NotImplementedError()
- def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
+ def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
"""
Adds the file ``file_object`` as ``path``
@@ -209,6 +215,7 @@ class StorageInterface(object):
:param list links: any links to add with the file
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
and its metadata will just be silently overwritten
+ :param unicode display: display name of the file
:return: the sanitized name of the file to be used for future references to it
"""
raise NotImplementedError()
@@ -226,7 +233,7 @@ class StorageInterface(object):
def copy_file(self, source, destination):
"""
- Copys the file ``source`` to ``destination``
+ Copies the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
@@ -334,6 +341,23 @@ class StorageInterface(object):
"""
raise NotImplementedError()
+ def canonicalize(self, path):
+ """
+ Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
+ implementation must separate those if necessary.
+
+ By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
+ of stripping any invalid characters.
+
+ Args:
+ path: the path to canonicalize
+
+ Returns:
+ a 2-tuple containing the canonicalized path and file name
+
+ """
+ return self.sanitize(path)
+
def sanitize(self, path):
"""
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
@@ -410,6 +434,7 @@ class StorageError(Exception):
INVALID_DESTINATION = "invalid_destination"
DOES_NOT_EXIST = "does_not_exist"
ALREADY_EXISTS = "already_exists"
+ SOURCE_EQUALS_DESTINATION = "source_equals_destination"
NOT_EMPTY = "not_empty"
def __init__(self, message, code=None, cause=None):
@@ -426,12 +451,28 @@ class LocalFileStorage(StorageInterface):
"""
The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk.
- Metadata is managed inside ``.metadata.yaml`` files in the respective folders, indexed by the sanitized filenames
+ Metadata is managed inside ``.metadata.json`` files in the respective folders, indexed by the sanitized filenames
stored within the folder. Metadata access is managed through an LRU cache to minimize access overhead.
This storage type implements :func:`path_on_disk`.
"""
+ _UNICODE_VARIATIONS = re.compile(u"[\uFE00-\uFE0F]")
+
+ @classmethod
+ def _no_unicode_variations(cls, text):
+ return cls._UNICODE_VARIATIONS.sub(u"", text)
+
+ _SLUGIFY = Slugify()
+ _SLUGIFY.safe_chars = "-_.()[] "
+
+ @classmethod
+ def _slugify(cls, text):
+ text = to_unicode(text)
+ text = cls._no_unicode_variations(text)
+ text = demojize(text, delimiters=(u"", u""))
+ return cls._SLUGIFY(text)
+
def __init__(self, basefolder, create=False):
"""
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
@@ -442,7 +483,7 @@ class LocalFileStorage(StorageInterface):
"""
self._logger = logging.getLogger(__name__)
- self.basefolder = os.path.realpath(os.path.abspath(basefolder))
+ self.basefolder = os.path.realpath(os.path.abspath(to_unicode(basefolder)))
if not os.path.exists(self.basefolder) and create:
os.makedirs(self.basefolder)
if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder):
@@ -454,10 +495,6 @@ class LocalFileStorage(StorageInterface):
self._metadata_cache = pylru.lrucache(10)
- from slugify import Slugify
- self._slugify = Slugify()
- self._slugify.safe_chars = "-_.()[] "
-
self._old_metadata = None
self._initialize_metadata()
@@ -535,7 +572,7 @@ class LocalFileStorage(StorageInterface):
path = os.path.join(self.basefolder, path)
def last_modified_for_path(p):
- metadata = os.path.join(p, ".metadata.yaml")
+ metadata = os.path.join(p, ".metadata.json")
if os.path.exists(metadata):
return max(os.stat(p).st_mtime, os.stat(metadata).st_mtime)
else:
@@ -564,17 +601,22 @@ class LocalFileStorage(StorageInterface):
def list_files(self, path=None, filter=None, recursive=True):
if path:
- path = self.sanitize_path(path)
+ path = self.sanitize_path(to_unicode(path))
base = self.path_in_storage(path)
if base:
- base += "/"
+ base += u"/"
else:
path = self.basefolder
- base = ""
+ base = u""
return self._list_folder(path, base=base, entry_filter=filter, recursive=recursive)
- def add_folder(self, path, ignore_existing=True):
- path, name = self.sanitize(path)
+ def add_folder(self, path, ignore_existing=True, display=None):
+ display_path, display_name = self.canonicalize(path)
+ path = self.sanitize_path(display_path)
+ name = self.sanitize_name(display_name)
+
+ if display is not None:
+ display_name = display
folder_path = os.path.join(path, name)
if os.path.exists(folder_path):
@@ -583,6 +625,11 @@ class LocalFileStorage(StorageInterface):
else:
os.mkdir(folder_path)
+ if display_name != name:
+ metadata = self._get_metadata_entry(path, name, default=dict())
+ metadata["display"] = display_name
+ self._update_metadata_entry(path, name, metadata)
+
return self.path_in_storage((path, name))
def remove_folder(self, path, recursive=True):
@@ -594,7 +641,7 @@ class LocalFileStorage(StorageInterface):
empty = True
for entry in scandir(folder_path):
- if entry.name == ".metadata.yaml":
+ if entry.name == ".metadata.json" or entry.name == ".metadata.yaml":
continue
empty = False
break
@@ -605,12 +652,15 @@ class LocalFileStorage(StorageInterface):
import shutil
shutil.rmtree(folder_path)
- self._delete_metadata(folder_path)
+ self._remove_metadata_entry(path, name)
- def _get_source_destination_data(self, source, destination):
+ def _get_source_destination_data(self, source, destination, must_not_equal=False):
"""Prepares data dicts about source and destination for copy/move."""
source_path, source_name = self.sanitize(source)
- destination_path, destination_name = self.sanitize(destination)
+
+ destination_canon_path, destination_canon_name = self.canonicalize(destination)
+ destination_path = self.sanitize_path(destination_canon_path)
+ destination_name = self.sanitize_name(destination_canon_name)
source_fullpath = os.path.join(source_path, source_name)
destination_fullpath = os.path.join(destination_path, destination_name)
@@ -620,45 +670,88 @@ class LocalFileStorage(StorageInterface):
if not os.path.isdir(destination_path):
raise StorageError("Destination path {} does not exist or is not a folder".format(destination_path), code=StorageError.INVALID_DESTINATION)
- if os.path.exists(destination_fullpath):
+ if os.path.exists(destination_fullpath) and source_fullpath != destination_fullpath:
raise StorageError("{} does already exist in {}".format(destination_name, destination_path), code=StorageError.INVALID_DESTINATION)
+ source_meta = self._get_metadata_entry(source_path, source_name)
+ if source_meta:
+ source_display = source_meta.get("display", source_name)
+ else:
+ source_display = source_name
+
+ if (must_not_equal or source_display == destination_canon_name) and source_fullpath == destination_fullpath:
+ raise StorageError("Source {} and destination {} are the same folder".format(source_path, destination_path), code=StorageError.SOURCE_EQUALS_DESTINATION)
+
source_data = dict(
path=source_path,
name=source_name,
+ display=source_display,
fullpath=source_fullpath,
)
destination_data = dict(
path=destination_path,
name=destination_name,
+ display=destination_canon_name,
fullpath=destination_fullpath,
)
return source_data, destination_data
+ def _set_display_metadata(self, destination_data, source_data=None):
+ if source_data and destination_data["name"] == source_data["name"] and source_data["name"] != source_data["display"]:
+ display = source_data["display"]
+ elif destination_data["name"] != destination_data["display"]:
+ display = destination_data["display"]
+ else:
+ display = None
+
+ destination_meta = self._get_metadata_entry(destination_data["path"], destination_data["name"],
+ default=dict())
+ if display:
+ destination_meta["display"] = display
+ self._update_metadata_entry(destination_data["path"], destination_data["name"], destination_meta)
+ elif "display" in destination_meta:
+ del destination_meta["display"]
+ self._update_metadata_entry(destination_data["path"], destination_data["name"], destination_meta)
+
def copy_folder(self, source, destination):
- source_data, destination_data = self._get_source_destination_data(source, destination)
+ source_data, destination_data = self._get_source_destination_data(source, destination, must_not_equal=True)
try:
shutil.copytree(source_data["fullpath"], destination_data["fullpath"])
except Exception as e:
raise StorageError("Could not copy %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
+ self._set_display_metadata(destination_data, source_data=source_data)
+
return self.path_in_storage(destination_data["fullpath"])
def move_folder(self, source, destination):
source_data, destination_data = self._get_source_destination_data(source, destination)
+ # only a display rename? Update that and bail early
+ if source_data["fullpath"] == destination_data["fullpath"]:
+ self._set_display_metadata(destination_data)
+ return self.path_in_storage(destination_data["fullpath"])
+
try:
shutil.move(source_data["fullpath"], destination_data["fullpath"])
except Exception as e:
raise StorageError("Could not move %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
+ self._set_display_metadata(destination_data, source_data=source_data)
+ self._remove_metadata_entry(source_data["path"], source_data["name"])
self._delete_metadata(source_data["fullpath"])
return self.path_in_storage(destination_data["fullpath"])
- def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
- path, name = self.sanitize(path)
+ def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
+ display_path, display_name = self.canonicalize(path)
+ path = self.sanitize_path(display_path)
+ name = self.sanitize_name(display_name)
+
+ if display:
+ display_name = display
+
if not octoprint.filemanager.valid_file_type(name):
raise StorageError("{name} is an unrecognized file type".format(**locals()), code=StorageError.INVALID_FILE)
@@ -670,6 +763,7 @@ class LocalFileStorage(StorageInterface):
# make sure folders exist
if not os.path.exists(path):
+ # TODO persist display names of path segments!
os.makedirs(path)
# save the file
@@ -678,9 +772,19 @@ class LocalFileStorage(StorageInterface):
# save the file's hash to the metadata of the folder
file_hash = self._create_hash(file_path)
metadata = self._get_metadata_entry(path, name, default=dict())
+ metadata_dirty = False
if not "hash" in metadata or metadata["hash"] != file_hash:
# hash changed -> throw away old metadata
- self._update_metadata_entry(path, name, dict(hash=file_hash))
+ metadata = dict(hash=file_hash)
+ metadata_dirty = True
+
+ if not "display" in metadata and display_name != name:
+ # display name is not the same as file name -> store in metadata
+ metadata["display"] = display_name
+ metadata_dirty = True
+
+ if metadata_dirty:
+ self._update_metadata_entry(path, name, metadata)
# process any links that were also provided for adding to the file
if not links:
@@ -713,7 +817,7 @@ class LocalFileStorage(StorageInterface):
self._remove_metadata_entry(path, name)
def copy_file(self, source, destination):
- source_data, destination_data = self._get_source_destination_data(source, destination)
+ source_data, destination_data = self._get_source_destination_data(source, destination, must_not_equal=True)
try:
shutil.copy2(source_data["fullpath"], destination_data["fullpath"])
@@ -722,12 +826,18 @@ class LocalFileStorage(StorageInterface):
self._copy_metadata_entry(source_data["path"], source_data["name"],
destination_data["path"], destination_data["name"])
+ self._set_display_metadata(destination_data, source_data=source_data)
return self.path_in_storage(destination_data["fullpath"])
def move_file(self, source, destination, allow_overwrite=False):
source_data, destination_data = self._get_source_destination_data(source, destination)
+ # only a display rename? Update that and bail early
+ if source_data["fullpath"] == destination_data["fullpath"]:
+ self._set_display_metadata(destination_data)
+ return self.path_in_storage(destination_data["fullpath"])
+
try:
shutil.move(source_data["fullpath"], destination_data["fullpath"])
except Exception as e:
@@ -736,6 +846,7 @@ class LocalFileStorage(StorageInterface):
self._copy_metadata_entry(source_data["path"], source_data["name"],
destination_data["path"], destination_data["name"],
delete_source=True)
+ self._set_display_metadata(destination_data, source_data=source_data)
return self.path_in_storage(destination_data["fullpath"])
@@ -777,7 +888,7 @@ class LocalFileStorage(StorageInterface):
def remove_history(self, path, index):
path, name = self.sanitize(path)
- self._update_history(name, path, index)
+ self._delete_history(name, path, index)
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
path, name = self.sanitize(path)
@@ -815,14 +926,15 @@ class LocalFileStorage(StorageInterface):
self._save_metadata(path, metadata)
def split_path(self, path):
- split = path.split("/")
+ path = to_unicode(path)
+ split = path.split(u"/")
if len(split) == 1:
- return "", split[0]
+ return u"", split[0]
else:
return self.join_path(*split[:-1]), split[-1]
def join_path(self, *path):
- return "/".join(path)
+ return u"/".join(map(to_unicode, path))
def sanitize(self, path):
"""
@@ -839,40 +951,48 @@ class LocalFileStorage(StorageInterface):
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``.
"""
- name = None
- if isinstance(path, (str, unicode, basestring)):
- if path.startswith(self.basefolder):
- path = path[len(self.basefolder):]
- path = path.replace(os.path.sep, "/")
- path = path.split("/")
- if isinstance(path, (list, tuple)):
- if len(path) == 1:
- name = path[0]
- path = "/"
- else:
- name = path[-1]
- path = "/" + self.join_path(*path[:-1])
- if not path:
- path = "/"
+ path, name = self.canonicalize(path)
name = self.sanitize_name(name)
path = self.sanitize_path(path)
return path, name
+ def canonicalize(self, path):
+ name = None
+ if isinstance(path, basestring):
+ path = to_unicode(path)
+ if path.startswith(self.basefolder):
+ path = path[len(self.basefolder):]
+ path = path.replace(os.path.sep, u"/")
+ path = path.split(u"/")
+ if isinstance(path, (list, tuple)):
+ if len(path) == 1:
+ name = to_unicode(path[0])
+ path = u""
+ else:
+ name = to_unicode(path[-1])
+ path = self.join_path(*map(to_unicode, path[:-1]))
+ if not path:
+ path = u""
+
+ return path, name
+
def sanitize_name(self, name):
"""
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise
slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``,
``(``, and ``)`` as is.
"""
+ name = to_unicode(name)
+
if name is None:
return None
- if "/" in name or "\\" in name:
+ if u"/" in name or u"\\" in name:
raise ValueError("name must not contain / or \\")
- result = self._slugify(name).replace(" ", "_")
- if result and result != "." and result != ".." and result[0] == ".":
+ result = self._slugify(name).replace(u" ", u"_")
+ if result and result != u"." and result != u".." and result[0] == u".":
# hidden files under *nix
result = result[1:]
return result
@@ -883,12 +1003,15 @@ class LocalFileStorage(StorageInterface):
relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the
absolute path including leading ``basefolder`` path.
"""
- if path[0] == "/":
- path = path[1:]
- elif path[0] == "." and path[1] == "/":
- path = path[2:]
+ path = to_unicode(path)
- path_elements = path.split("/")
+ if len(path):
+ if path[0] == u"/":
+ path = path[1:]
+ elif path[0] == u"." and path[1] == u"/":
+ path = path[2:]
+
+ path_elements = path.split(u"/")
joined_path = self.basefolder
for path_element in path_elements:
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
@@ -898,6 +1021,7 @@ class LocalFileStorage(StorageInterface):
return path
def _sanitize_entry(self, entry, path, entry_path):
+ entry = to_unicode(entry)
sanitized = self.sanitize_name(entry)
if sanitized != entry:
# entry is not sanitized yet, let's take care of that
@@ -907,16 +1031,16 @@ class LocalFileStorage(StorageInterface):
counter = 1
while os.path.exists(sanitized_path):
counter += 1
- sanitized = self.sanitize_name("{}_({}){}".format(sanitized_name, counter, sanitized_ext))
+ sanitized = self.sanitize_name(u"{}_({}){}".format(sanitized_name, counter, sanitized_ext))
sanitized_path = os.path.join(path, sanitized)
try:
shutil.move(entry_path, sanitized_path)
- self._logger.info("Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
+ self._logger.info(u"Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
return sanitized, sanitized_path
except:
- self._logger.exception("Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
+ self._logger.exception(u"Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
raise
return entry, entry_path
@@ -925,10 +1049,11 @@ class LocalFileStorage(StorageInterface):
if isinstance(path, (tuple, list)):
path = self.join_path(*path)
if isinstance(path, (str, unicode, basestring)):
+ path = to_unicode(path)
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
- path = path.replace(os.path.sep, "/")
- if path.startswith("/"):
+ path = path.replace(os.path.sep, u"/")
+ if path.startswith(u"/"):
path = path[1:]
return path
@@ -1005,7 +1130,7 @@ class LocalFileStorage(StorageInterface):
try:
print_time = float(print_time)
except:
- self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.yaml: {!r}".format(name, path, print_time))
+ self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time))
continue
if not printer_profile in former_print_times:
@@ -1168,7 +1293,7 @@ class LocalFileStorage(StorageInterface):
if metadata_dirty:
self._save_metadata(path, metadata)
- def _list_folder(self, path, base="", entry_filter=None, recursive=True, **kwargs):
+ def _list_folder(self, path, base="", entry_filter=None, recursive=True, include_children=True, **kwargs):
if entry_filter is None:
entry_filter = kwargs.get("filter", None)
@@ -1184,7 +1309,7 @@ class LocalFileStorage(StorageInterface):
continue
try:
- entry_name = entry.name
+ entry_name = entry_display = entry.name
entry_path = entry.path
entry_is_file = entry.is_file()
entry_is_dir = entry.is_dir()
@@ -1197,6 +1322,7 @@ class LocalFileStorage(StorageInterface):
try:
new_entry_name, new_entry_path = self._sanitize_entry(entry_name, path, entry_path)
if entry_name != new_entry_name or entry_path != new_entry_path:
+ entry_display = to_unicode(entry_name)
entry_name = new_entry_name
entry_path = new_entry_path
entry_stat = os.stat(entry_path)
@@ -1206,67 +1332,101 @@ class LocalFileStorage(StorageInterface):
path_in_location = entry_name if not base else base + entry_name
- # file handling
- if entry_is_file:
- type_path = octoprint.filemanager.get_file_type(entry_name)
- if not type_path:
- # only supported extensions
- continue
- else:
- file_type = type_path[0]
+ try:
+ # file handling
+ if entry_is_file:
+ type_path = octoprint.filemanager.get_file_type(entry_name)
+ if not type_path:
+ # only supported extensions
+ continue
+ else:
+ file_type = type_path[0]
- if entry_name in metadata and isinstance(metadata[entry_name], dict):
- entry_data = metadata[entry_name]
- else:
- entry_data = self._add_basic_metadata(path, entry_name, save=False, metadata=metadata)
- metadata_dirty = True
+ if entry_name in metadata and isinstance(metadata[entry_name], dict):
+ entry_metadata = metadata[entry_name]
+ if not "display" in entry_metadata and entry_display != entry_name:
+ metadata[entry_name]["display"] = entry_display
+ entry_metadata["display"] = entry_display
+ metadata_dirty = True
+ else:
+ entry_metadata = self._add_basic_metadata(path, entry_name,
+ display_name=entry_display,
+ save=False,
+ metadata=metadata)
+ metadata_dirty = True
- # TODO extract model hash from source if possible to recreate link
+ # TODO extract model hash from source if possible to recreate link
- if not entry_filter or entry_filter(entry_name, entry_data):
- # only add files passing the optional filter
- extended_entry_data = dict()
- extended_entry_data.update(entry_data)
- extended_entry_data["name"] = entry_name
- extended_entry_data["path"] = path_in_location
- extended_entry_data["type"] = file_type
- extended_entry_data["typePath"] = type_path
- stat = entry_stat
- if stat:
- extended_entry_data["size"] = stat.st_size
- extended_entry_data["date"] = int(stat.st_mtime)
+ if not entry_filter or entry_filter(entry_name, entry_metadata):
+ # only add files passing the optional filter
+ extended_entry_data = dict()
+ extended_entry_data.update(entry_metadata)
+ extended_entry_data["name"] = entry_name
+ extended_entry_data["display"] = entry_metadata.get("display", entry_name)
+ extended_entry_data["path"] = path_in_location
+ extended_entry_data["type"] = file_type
+ extended_entry_data["typePath"] = type_path
+ stat = entry_stat
+ if stat:
+ extended_entry_data["size"] = stat.st_size
+ extended_entry_data["date"] = int(stat.st_mtime)
- result[entry_name] = extended_entry_data
+ result[entry_name] = extended_entry_data
- # folder recursion
- elif entry_is_dir:
- entry_data = dict(
- name=entry_name,
- path=path_in_location,
- type="folder",
- type_path=["folder"]
- )
- if recursive:
- sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter,
- recursive=recursive)
- entry_data["children"] = sub_result
+ # folder recursion
+ elif entry_is_dir:
+ if entry_name in metadata and isinstance(metadata[entry_name], dict):
+ entry_metadata = metadata[entry_name]
+ if not "display" in entry_metadata and entry_display != entry_name:
+ metadata[entry_name]["display"] = entry_display
+ entry_metadata["display"] = entry_display
+ metadata_dirty = True
+ elif entry_name != entry_display:
+ entry_metadata = self._add_basic_metadata(path, entry_name,
+ display_name=entry_display,
+ save=False,
+ metadata=metadata)
+ metadata_dirty = True
+ else:
+ entry_metadata = dict()
- if not entry_filter or entry_filter(entry_name, entry_data):
- def get_size():
- total_size = 0
- for element in entry_data["children"].values():
- if "size" in element:
- total_size += element["size"]
-
- return total_size
-
- # only add folders passing the optional filter
- extended_entry_data = dict()
- extended_entry_data.update(entry_data)
+ entry_data = dict(
+ name=entry_name,
+ display=entry_metadata.get("display", entry_name),
+ path=path_in_location,
+ type="folder",
+ typePath=["folder"]
+ )
if recursive:
- extended_entry_data["size"] = get_size()
+ sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter,
+ recursive=recursive)
+ entry_data["children"] = sub_result
+ elif include_children:
+ sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter,
+ recursive=False, include_children=False)
+ entry_data["children"] = sub_result
- result[entry_name] = extended_entry_data
+ if not entry_filter or entry_filter(entry_name, entry_data):
+ # only add folders passing the optional filter
+
+ def get_size():
+ total_size = 0
+ for element in entry_data["children"].values():
+ if "size" in element:
+ total_size += element["size"]
+
+ return total_size
+
+ extended_entry_data = dict()
+ extended_entry_data.update(entry_data)
+ if recursive:
+ extended_entry_data["size"] = get_size()
+
+ result[entry_name] = extended_entry_data
+ except:
+ # So something went wrong somewhere while processing this file entry - log that and continue
+ self._logger.exception("Error while processing entry {}".format(entry_path))
+ continue
# TODO recreate links if we have metadata less entries
@@ -1276,22 +1436,33 @@ class LocalFileStorage(StorageInterface):
return result
- def _add_basic_metadata(self, path, entry, additional_metadata=None, save=True, metadata=None):
+ def _add_basic_metadata(self, path, entry, display_name=None, additional_metadata=None, save=True, metadata=None):
if additional_metadata is None:
additional_metadata = dict()
if metadata is None:
metadata = self._get_metadata(path)
- entry_data = dict(
- hash=self._create_hash(os.path.join(path, entry)),
- links=[],
- notes=[]
- )
+ entry_path = os.path.join(path, entry)
- if path == self.basefolder and self._old_metadata is not None and entry in self._old_metadata and "gcodeAnalysis" in self._old_metadata[entry]:
- # if there is still old metadata available and that contains an analysis for this file, use it!
- entry_data["analysis"] = self._old_metadata[entry]["gcodeAnalysis"]
+ if os.path.isfile(entry_path):
+ entry_data = dict(
+ hash=self._create_hash(os.path.join(path, entry)),
+ links=[],
+ notes=[]
+ )
+ if path == self.basefolder and self._old_metadata is not None and entry in self._old_metadata and "gcodeAnalysis" in self._old_metadata[entry]:
+ # if there is still old metadata available and that contains an analysis for this file, use it!
+ entry_data["analysis"] = self._old_metadata[entry]["gcodeAnalysis"]
+
+ elif os.path.isdir(entry_path):
+ entry_data = dict()
+
+ else:
+ return
+
+ if display_name is not None and not display_name == entry:
+ entry_data["display"] = display_name
entry_data.update(additional_metadata)
metadata[entry] = entry_data
@@ -1342,7 +1513,7 @@ class LocalFileStorage(StorageInterface):
metadata[name] = data
self._save_metadata(path, metadata)
- def _copy_metadata_entry(self, source_path, source_name, destination_path, destination_name, delete_source=False):
+ def _copy_metadata_entry(self, source_path, source_name, destination_path, destination_name, delete_source=False, updates=None):
with self._get_metadata_lock(source_path):
source_data = self._get_metadata_entry(source_path, source_name, default=dict())
if not source_data:
@@ -1351,6 +1522,9 @@ class LocalFileStorage(StorageInterface):
if delete_source:
self._remove_metadata_entry(source_path, source_name)
+ if updates is not None:
+ source_data.update(updates)
+
with self._get_metadata_lock(destination_path):
self._update_metadata_entry(destination_path, destination_name, source_data)
@@ -1359,42 +1533,81 @@ class LocalFileStorage(StorageInterface):
if path in self._metadata_cache:
return deepcopy(self._metadata_cache[path])
- metadata_path = os.path.join(path, ".metadata.yaml")
+ self._migrate_metadata(path)
+
+ metadata_path = os.path.join(path, ".metadata.json")
if os.path.exists(metadata_path):
with open(metadata_path) as f:
try:
- import yaml
- metadata = yaml.safe_load(f)
+ import json
+ metadata = json.load(f)
except:
- self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
+ self._logger.exception("Error while reading .metadata.json from {path}".format(**locals()))
else:
- self._metadata_cache[path] = deepcopy(metadata)
- return metadata
+ if isinstance(metadata, dict):
+ self._metadata_cache[path] = deepcopy(metadata)
+ return metadata
return dict()
def _save_metadata(self, path, metadata):
with self._get_metadata_lock(path):
- metadata_path = os.path.join(path, ".metadata.yaml")
+ metadata_path = os.path.join(path, ".metadata.json")
try:
- import yaml
+ import json
with atomic_write(metadata_path) as f:
- yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
+ json.dump(metadata, f, indent=4, separators=(",", ": "))
except:
- self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals()))
+ self._logger.exception("Error while writing .metadata.json to {path}".format(**locals()))
else:
self._metadata_cache[path] = deepcopy(metadata)
def _delete_metadata(self, path):
with self._get_metadata_lock(path):
- metadata_path = os.path.join(path, ".metadata.yaml")
- if os.path.exists(metadata_path):
- try:
- os.remove(metadata_path)
- except:
- self._logger.exception("Error while deleting .metadata.yaml from {path}".format(**locals()))
+ metadata_files = (".metadata.json", ".metadata.yaml")
+ for metadata_file in metadata_files:
+ metadata_path = os.path.join(path, metadata_file)
+ if os.path.exists(metadata_path):
+ try:
+ os.remove(metadata_path)
+ except:
+ self._logger.exception("Error while deleting {metadata_file} from {path}".format(**locals()))
if path in self._metadata_cache:
del self._metadata_cache[path]
+ def _migrate_metadata(self, path):
+ # we switched to json in 1.3.9 - if we still have yaml here, migrate it now
+ import yaml
+ import json
+
+ with self._get_metadata_lock(path):
+ metadata_path_yaml = os.path.join(path, ".metadata.yaml")
+ metadata_path_json = os.path.join(path, ".metadata.json")
+
+ if not os.path.exists(metadata_path_yaml):
+ # nothing to migrate
+ return
+
+ if os.path.exists(metadata_path_json):
+ # already migrated
+ # TODO 1.3.10 Remove ".metadata.yaml" files
+ return
+
+ with open(metadata_path_yaml) as f:
+ try:
+ metadata = yaml.safe_load(f)
+ except:
+ self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
+ return
+
+ if not isinstance(metadata, dict):
+ # looks invalid, ignore it
+ return
+
+ with atomic_write(metadata_path_json) as f:
+ json.dump(metadata, f, indent=4, separators=(",", ": "))
+
+ # TODO 1.3.10 Remove ".metadata.yaml" files
+
@contextmanager
def _get_metadata_lock(self, path):
with self._metadata_lock_mutex:
@@ -1406,8 +1619,9 @@ class LocalFileStorage(StorageInterface):
counter += 1
self._metadata_locks[path] = (counter, lock)
- yield lock
+ yield lock
+ with self._metadata_lock_mutex:
counter = self._metadata_locks[path][0]
counter -= 1
if counter <= 0:
diff --git a/src/octoprint/logging/__init__.py b/src/octoprint/logging/__init__.py
index 1f78abae7..1021b169a 100644
--- a/src/octoprint/logging/__init__.py
+++ b/src/octoprint/logging/__init__.py
@@ -135,3 +135,16 @@ def get_divider_line(c, message=None, length=78, indent=3):
return c * indent + " " + message + " " + c * (length - indent - 2 - len(message))
else:
return c * indent + " " + message
+
+
+def prefix_multilines(text, prefix=": "):
+ lines = text.splitlines()
+ if not lines:
+ return ""
+
+ if len(lines) == 1:
+ return lines[0]
+
+ return lines[0] + "\n" + "\n".join(map(lambda line: prefix + line,
+ lines[1:]))
+
diff --git a/src/octoprint/logging/handlers.py b/src/octoprint/logging/handlers.py
index 7d106a4b1..ade943c76 100644
--- a/src/octoprint/logging/handlers.py
+++ b/src/octoprint/logging/handlers.py
@@ -6,10 +6,30 @@ import os
import re
import time
+# noinspection PyCompatibility
+import concurrent.futures
+
+
+class AsyncLogHandlerMixin(logging.Handler):
+ def __init__(self, *args, **kwargs):
+ self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
+ super(AsyncLogHandlerMixin, self).__init__(*args, **kwargs)
+
+ def emit(self, record):
+ try:
+ self._executor.submit(self._emit, record)
+ except:
+ self.handleError(record)
+
+ def _emit(self, record):
+ # noinspection PyUnresolvedReferences
+ super(AsyncLogHandlerMixin, self).emit(record)
+
+
class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, *args, **kwargs):
- logging.handlers.TimedRotatingFileHandler.__init__(self, *args, **kwargs)
+ super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs)
# clean up old files on handler start
if self.backupCount > 0:
@@ -17,7 +37,7 @@ class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler
os.remove(s)
-class OctoPrintLogHandler(CleaningTimedRotatingFileHandler):
+class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler):
rollover_callbacks = []
@classmethod
@@ -25,32 +45,33 @@ class OctoPrintLogHandler(CleaningTimedRotatingFileHandler):
cls.rollover_callbacks.append((callback, args, kwargs))
def doRollover(self):
- CleaningTimedRotatingFileHandler.doRollover(self)
+ super(OctoPrintLogHandler, self).doRollover()
- for rcb in self.__class__.rollover_callbacks:
+ for rcb in self.rollover_callbacks:
callback, args, kwargs = rcb
callback(*args, **kwargs)
-class SerialLogHandler(logging.handlers.RotatingFileHandler):
+class OctoPrintStreamHandler(AsyncLogHandlerMixin, logging.StreamHandler):
+ pass
- _do_rollover = False
- _suffix_template = "%Y-%m-%d_%H-%M-%S"
- _file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
+
+class SerialLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler):
+
+ do_rollover = False
+ suffix_template = "%Y-%m-%d_%H-%M-%S"
+ file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
@classmethod
def on_open_connection(cls):
- cls._do_rollover = True
+ cls.do_rollover = True
def __init__(self, *args, **kwargs):
- logging.handlers.RotatingFileHandler.__init__(self, *args, **kwargs)
+ super(SerialLogHandler, self).__init__(*args, **kwargs)
self.cleanupFiles()
- def emit(self, record):
- logging.handlers.RotatingFileHandler.emit(self, record)
-
def shouldRollover(self, record):
- return self.__class__._do_rollover
+ return type(self).do_rollover
def getFilesToDelete(self):
"""
@@ -64,7 +85,7 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
for fileName in fileNames:
if fileName[:plen] == prefix:
suffix = fileName[plen:]
- if self.__class__._file_pattern.match(suffix):
+ if type(self).file_pattern.match(suffix):
result.append(os.path.join(dirName, fileName))
result.sort()
if len(result) < self.backupCount:
@@ -88,7 +109,7 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
if os.path.exists(self.baseFilename):
# figure out creation date/time to use for file suffix
t = time.localtime(os.stat(self.baseFilename).st_mtime)
- dfn = self.baseFilename + "." + time.strftime(self.__class__._suffix_template, t)
+ dfn = self.baseFilename + "." + time.strftime(type(self).suffix_template, t)
if os.path.exists(dfn):
os.remove(dfn)
os.rename(self.baseFilename, dfn)
@@ -98,8 +119,8 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
self.stream = self._open()
class RecordingLogHandler(logging.Handler):
- def __init__(self, target=None, level=logging.NOTSET):
- logging.Handler.__init__(self, level=level)
+ def __init__(self, target=None, *args, **kwargs):
+ super(RecordingLogHandler, self).__init__(*args, **kwargs)
self._buffer = []
self._target = target
@@ -133,6 +154,7 @@ class RecordingLogHandler(logging.Handler):
return len(self._buffer)
+# noinspection PyAbstractClass
class CombinedLogHandler(logging.Handler):
def __init__(self, *handlers):
logging.Handler.__init__(self)
diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py
index 57adfb2ed..d71c52f23 100644
--- a/src/octoprint/plugin/__init__.py
+++ b/src/octoprint/plugin/__init__.py
@@ -44,8 +44,9 @@ def _validate_plugin(phase, plugin_info):
setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks)
return True
-def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None,
- plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None):
+def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None,
+ plugin_blacklist=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None,
+ plugin_validators=None):
"""
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
singleton.
@@ -58,13 +59,13 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
plugin_folders (list): A list of folders (as strings containing the absolute path to them) in which to look for
potential plugin modules. If not provided this defaults to the configured ``plugins`` base folder and
``src/plugins`` within OctoPrint's code base.
- plugin_types (list): A list of recognized plugin types for which to look for provided implementations. If not
- provided this defaults to the plugin types found in :mod:`octoprint.plugin.types` without
- :class:`~octoprint.plugin.OctoPrintPlugin`.
+ plugin_bases (list): A list of recognized plugin base classes for which to look for provided implementations. If not
+ provided this defaults to :class:`~octoprint.plugin.OctoPrintPlugin`.
plugin_entry_points (list): A list of entry points pointing to modules which to load as plugins. If not provided
this defaults to the entry point ``octoprint.plugin``.
plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this
defaults to all plugins for which ``enabled`` is set to ``False`` in the settings.
+ plugin_blacklist (list): A list of plugin identifiers/identifier-version tuples that are currently blacklisted.
plugin_restart_needing_hooks (list): A list of hook namespaces which cause a plugin to need a restart in order
be enabled/disabled. Does not have to contain full hook identifiers, will be matched with startswith similar
to logging handlers
@@ -88,23 +89,13 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
else:
if init:
- if plugin_types is None:
- plugin_types = [StartupPlugin,
- ShutdownPlugin,
- TemplatePlugin,
- SettingsPlugin,
- SimpleApiPlugin,
- AssetPlugin,
- BlueprintPlugin,
- EventHandlerPlugin,
- SlicerPlugin,
- AppPlugin,
- ProgressPlugin,
- WizardPlugin,
- UiPlugin]
+ if plugin_bases is None:
+ plugin_bases = [OctoPrintPlugin]
if plugin_restart_needing_hooks is None:
- plugin_restart_needing_hooks = ["octoprint.server.http"]
+ plugin_restart_needing_hooks = ["octoprint.server.http.*",
+ "octoprint.printer.factory",
+ "octoprint.access.permissions"]
if plugin_obsolete_hooks is None:
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
@@ -115,10 +106,11 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
plugin_validators.append(_validate_plugin)
_instance = PluginManager(plugin_folders,
- plugin_types,
+ plugin_bases,
plugin_entry_points,
logging_prefix="octoprint.plugins.",
plugin_disabled_list=plugin_disabled_list,
+ plugin_blacklist=plugin_blacklist,
plugin_restart_needing_hooks=plugin_restart_needing_hooks,
plugin_obsolete_hooks=plugin_obsolete_hooks,
plugin_validators=plugin_validators)
@@ -176,7 +168,7 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
-def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None):
+def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True):
"""
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
@@ -212,6 +204,8 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
error_callback (function): A callback to invoke after the call of an implementation resulted in an exception.
Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
+ initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status
+ is determined be presence of injected ``_identifier`` property.
"""
@@ -224,6 +218,9 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
for plugin in plugins:
+ if initialized and not hasattr(plugin, "_identifier"):
+ continue
+
if hasattr(plugin, method):
try:
result = getattr(plugin, method)(*args, **kwargs)
@@ -263,13 +260,17 @@ class PluginSettings(object):
:returns: The retrieved settings value.
:rtype: object
- .. method:: get_int(path)
+ .. method:: get_int(path, min=None, max=None)
- Like :func:`get` but tries to convert the retrieved value to ``int``.
+ Like :func:`get` but tries to convert the retrieved value to ``int``. If ``min`` is provided and the retrieved
+ value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if
+ the value is greater than it.
- .. method:: get_float(path)
+ .. method:: get_float(path, min=None, max=None)
- Like :func:`get` but tries to convert the retrieved value to ``float``.
+ Like :func:`get` but tries to convert the retrieved value to ``float``. If ``min`` is provided and the retrieved
+ value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if
+ the value is greater than it.
.. method:: get_boolean(path)
@@ -285,13 +286,19 @@ class PluginSettings(object):
:param boolean force: If set to True, the modified configuration will even be written back to disk if
the value didn't change.
- .. method:: set_int(path, value, force=False)
+ .. method:: set_int(path, value, force=False, min=None, max=None)
Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it.
+ If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal
+ to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than
+ that, ``max`` if greater than that) will be set instead.
- .. method:: set_float(path, value, force=False)
+ .. method:: set_float(path, value, force=False, min=None, max=None)
Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it.
+ If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal
+ to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than
+ that, ``max`` if greater than that) will be set instead.
.. method:: set_boolean(path, value, force=False)
diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py
index 4f98a29ab..e46526236 100644
--- a/src/octoprint/plugin/core.py
+++ b/src/octoprint/plugin/core.py
@@ -31,10 +31,14 @@ import os
import imp
from collections import defaultdict, namedtuple, OrderedDict
import logging
+import fnmatch
+import inspect
import pkg_resources
import pkginfo
+from past.builtins import basestring
+
try:
from os import scandir
except ImportError:
@@ -56,7 +60,7 @@ class PluginInfo(object):
Arguments:
key (str): Identifier of the plugin
location (str): Installation folder of the plugin
- instance (module): Plugin module instance
+ instance (module): Plugin module instance - this may be ``None`` if the plugin has been blacklisted!
name (str): Human readable name of the plugin
version (str): Version of the plugin
description (str): Description of the plugin
@@ -133,12 +137,14 @@ class PluginInfo(object):
attr_disable = '__plugin_disable__'
""" Module attribute which to call when disabling the plugin. """
- def __init__(self, key, location, instance, name=None, version=None, description=None, author=None, url=None, license=None):
+ def __init__(self, key, location, instance, name=None, version=None, description=None, author=None, url=None, license=None, parsed_metadata=None):
self.key = key
self.location = location
self.instance = instance
self.origin = None
self.enabled = True
+ self.blacklisted = False
+ self.forced_disabled = False
self.bundled = False
self.loaded = False
self.managable = True
@@ -151,10 +157,17 @@ class PluginInfo(object):
self._url = url
self._license = license
+ self._logger = logging.getLogger(__name__)
+
+ self._cached_parsed_metadata = parsed_metadata
+
def validate(self, phase, additional_validators=None):
result = True
- if phase == "before_load":
+ if phase == "before_import":
+ result = not self.forced_disabled and not self.blacklisted and result
+
+ elif phase == "before_load":
# if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__
if hasattr(self.instance, self.__class__.attr_init):
if not hasattr(self.instance, self.__class__.attr_load):
@@ -188,7 +201,7 @@ class PluginInfo(object):
if additional_validators is not None:
for validator in additional_validators:
- result = result and validator(phase, self)
+ result = validator(phase, self) and result
return result
@@ -200,7 +213,7 @@ class PluginInfo(object):
def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""),
show_location=False, location_str=" - {location}",
- show_enabled=False, enabled_strs=("* ", " ")):
+ show_enabled=False, enabled_strs=("* ", " ", "X ")):
"""
Long string representation of the plugin's information. Will return a string of the format ````.
@@ -208,8 +221,8 @@ class PluginInfo(object):
The will be filled from ``enabled_str``, ``bundled_str`` and ``location_str`` as follows:
``enabled_str``
- a 2-tuple, the first entry being the string to insert when the plugin is enabled, the second
- entry the string to insert when it is not.
+ a 3-tuple, the first entry being the string to insert when the plugin is enabled, the second
+ entry the string to insert when it is not, the third entry the string when it is blacklisted.
``bundled_str``
a 2-tuple, the first entry being the string to insert when the plugin is bundled, the second
entry the string to insert when it is not.
@@ -229,7 +242,7 @@ class PluginInfo(object):
str: The long string representation of the plugin as described above
"""
if show_enabled:
- ret = enabled_strs[0] if self.enabled else enabled_strs[1]
+ ret = enabled_strs[2] if self.blacklisted else (enabled_strs[0] if self.enabled else enabled_strs[1])
else:
ret = ""
@@ -283,7 +296,9 @@ class PluginInfo(object):
Returns:
str: Name of the plugin, fallback is the plugin's identifier.
"""
- return self._get_instance_attribute(self.__class__.attr_name, defaults=(self._name, self.key))
+ return self._get_instance_attribute(self.__class__.attr_name,
+ defaults=(self._name, self.key),
+ incl_metadata=True)
@property
def description(self):
@@ -295,7 +310,9 @@ class PluginInfo(object):
Returns:
str or None: Description of the plugin.
"""
- return self._get_instance_attribute(self.__class__.attr_description, default=self._description)
+ return self._get_instance_attribute(self.__class__.attr_description,
+ default=self._description,
+ incl_metadata=True)
@property
def disabling_discouraged(self):
@@ -319,7 +336,9 @@ class PluginInfo(object):
Returns:
str or None: Version of the plugin.
"""
- return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version, default=self._version)
+ return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version,
+ default=self._version,
+ incl_metadata=True)
@property
def author(self):
@@ -330,7 +349,9 @@ class PluginInfo(object):
Returns:
str or None: Author of the plugin.
"""
- return self._get_instance_attribute(self.__class__.attr_author, default=self._author)
+ return self._get_instance_attribute(self.__class__.attr_author,
+ default=self._author,
+ incl_metadata=True)
@property
def url(self):
@@ -341,7 +362,9 @@ class PluginInfo(object):
Returns:
str or None: Website URL for the plugin.
"""
- return self._get_instance_attribute(self.__class__.attr_url, default=self._url)
+ return self._get_instance_attribute(self.__class__.attr_url,
+ default=self._url,
+ incl_metadata=True)
@property
def license(self):
@@ -352,7 +375,9 @@ class PluginInfo(object):
Returns:
str or None: License of the plugin.
"""
- return self._get_instance_attribute(self.__class__.attr_license, default=self._license)
+ return self._get_instance_attribute(self.__class__.attr_license,
+ default=self._license,
+ incl_metadata=True)
@property
def hooks(self):
@@ -443,15 +468,79 @@ class PluginInfo(object):
"""
return self._get_instance_attribute(self.__class__.attr_disable, default=lambda: True)
- def _get_instance_attribute(self, attr, default=None, defaults=None):
- if not hasattr(self.instance, attr):
- if defaults is not None:
+ def _get_instance_attribute(self, attr, default=None, defaults=None, incl_metadata=False):
+ if self.instance is None or not hasattr(self.instance, attr):
+ if incl_metadata and attr in self.parsed_metadata:
+ return self.parsed_metadata[attr]
+
+ elif defaults is not None:
for value in defaults:
+ if callable(value):
+ value = value()
if value is not None:
return value
+
return default
+
return getattr(self.instance, attr)
+ @property
+ def parsed_metadata(self):
+ if self._cached_parsed_metadata is None:
+ self._cached_parsed_metadata = self._parse_metadata()
+ return self._cached_parsed_metadata
+
+ def _parse_metadata(self):
+ result = dict()
+
+ path = self.location
+ if not path:
+ return result
+
+ if os.path.isdir(path):
+ path = os.path.join(self.location, "__init__.py")
+
+ if not os.path.isfile(path):
+ return result
+
+ if not path.endswith(".py"):
+ # we only support parsing plain text source files
+ return result
+
+ self._logger.debug("Parsing plugin metadata for {} from AST of {}".format(self.key, path))
+
+ try:
+ import ast
+
+ with open(path, "rb") as f:
+ root = ast.parse(f.read())
+
+ assignments = filter(lambda x: isinstance(x, ast.Assign) and x.targets,
+ root.body)
+
+ def extract_target_ids(node):
+ return map(lambda x: x.id,
+ filter(lambda x: isinstance(x, ast.Name), node.targets))
+
+ for key in (self.__class__.attr_name, self.__class__.attr_version, self.__class__.attr_author,
+ self.__class__.attr_description, self.__class__.attr_url, self.__class__.attr_license):
+ for a in reversed(assignments):
+ targets = extract_target_ids(a)
+ if key in targets:
+ if isinstance(a.value, ast.Str):
+ result[key] = a.value.s
+
+ elif isinstance(a.value, ast.Call) and hasattr(a.value, "func") \
+ and a.value.func.id == "gettext" and a.value.args \
+ and isinstance(a.value.args[0], ast.Str):
+ result[key] = a.value.args[0].s
+
+ break
+ except:
+ pass
+
+ return result
+
class PluginManager(object):
"""
@@ -461,26 +550,29 @@ class PluginManager(object):
It is able to discover plugins both through possible file system locations as well as customizable entry points.
"""
- def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None,
- plugin_disabled_list=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None,
- plugin_validators=None):
+ def __init__(self, plugin_folders, plugin_bases, plugin_entry_points, logging_prefix=None,
+ plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None,
+ plugin_obsolete_hooks=None, plugin_validators=None):
self.logger = logging.getLogger(__name__)
if logging_prefix is None:
logging_prefix = ""
if plugin_folders is None:
plugin_folders = []
- if plugin_types is None:
- plugin_types = []
+ if plugin_bases is None:
+ plugin_bases = []
if plugin_entry_points is None:
plugin_entry_points = []
if plugin_disabled_list is None:
plugin_disabled_list = []
+ if plugin_blacklist is None:
+ plugin_blacklist = []
self.plugin_folders = plugin_folders
- self.plugin_types = plugin_types
+ self.plugin_bases = plugin_bases
self.plugin_entry_points = plugin_entry_points
self.plugin_disabled_list = plugin_disabled_list
+ self.plugin_blacklist = plugin_blacklist
self.plugin_restart_needing_hooks = plugin_restart_needing_hooks
self.plugin_obsolete_hooks = plugin_obsolete_hooks
self.plugin_validators = plugin_validators
@@ -542,60 +634,84 @@ class PluginManager(object):
if existing is None:
existing = dict(self.plugins)
- result = dict()
+ result = OrderedDict()
if self.plugin_folders:
- result.update(self._find_plugins_from_folders(self.plugin_folders, existing, ignored_uninstalled=ignore_uninstalled))
+ try:
+ result.update(self._find_plugins_from_folders(self.plugin_folders,
+ existing,
+ ignored_uninstalled=ignore_uninstalled))
+ except:
+ self.logger.exception("Error fetching plugins from folders")
if self.plugin_entry_points:
existing.update(result)
- result.update(self._find_plugins_from_entry_points(self.plugin_entry_points, existing, ignore_uninstalled=ignore_uninstalled))
+ try:
+ result.update(self._find_plugins_from_entry_points(self.plugin_entry_points,
+ existing,
+ ignore_uninstalled=ignore_uninstalled))
+ except:
+ self.logger.exception("Error fetching plugins from entry points")
return result
def _find_plugins_from_folders(self, folders, existing, ignored_uninstalled=True):
- result = dict()
+ result = OrderedDict()
for folder in folders:
- flagged_readonly = False
- if isinstance(folder, (list, tuple)):
- if len(folder) == 2:
- 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))
- continue
-
- for entry in scandir(folder):
- if entry.is_dir() and os.path.isfile(os.path.join(entry.path, "__init__.py")):
- key = entry.name
- elif entry.is_file() and entry.name.endswith(".py"):
- key = entry.name[:-3] # strip off the .py extension
- if key.startswith("__"):
- # might be an __init__.py in our plugins folder, or something else we don't want
- # to handle
+ try:
+ flagged_readonly = False
+ if isinstance(folder, (list, tuple)):
+ if len(folder) == 2:
+ folder, flagged_readonly = folder
+ else:
continue
- else:
+ 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))
continue
- if key in existing or key in result or (ignored_uninstalled and key in self.marked_plugins["uninstalled"]):
- # plugin is already defined, ignore it
- continue
+ for entry in scandir(folder):
+ try:
+ if entry.is_dir():
+ init_py = os.path.join(entry.path, "__init__.py")
+ init_pyc = os.path.join(entry.path, "__init__.pyc")
- plugin = self._import_plugin_from_module(key, folder=folder)
- if plugin:
- plugin.origin = FolderOrigin("folder", folder)
- plugin.managable = not flagged_readonly and not actual_readonly
- plugin.bundled = flagged_readonly
+ if not os.path.isfile(init_py) and not os.path.isfile(init_pyc):
+ # neither does exist, we ignore this
+ continue
- plugin.enabled = False
+ key = entry.name
- result[key] = plugin
+ elif entry.is_file():
+ key, ext = os.path.splitext(entry.name)
+ if ext not in (".py", ".pyc") or key.startswith("__"):
+ # neither py nor pyc, or starts with __ (like __init__), we ignore this
+ continue
+
+ else:
+ # whatever this is, we ignore it
+ continue
+
+ if key in existing or key in result or (ignored_uninstalled and key in self.marked_plugins["uninstalled"]):
+ # plugin is already defined, ignore it
+ continue
+
+ bundled = flagged_readonly
+
+ plugin = self._import_plugin_from_module(key, folder=folder, bundled=bundled)
+ if plugin:
+ plugin.origin = FolderOrigin("folder", folder)
+ plugin.managable = not flagged_readonly and not actual_readonly
+ plugin.enabled = False
+ result[key] = plugin
+ except:
+ self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder))
+ except:
+ self.logger.exception("Error processing folder {}".format(folder))
return result
def _find_plugins_from_entry_points(self, groups, existing, ignore_uninstalled=True):
- result = dict()
+ result = OrderedDict()
# let's make sure we have a current working set ...
working_set = pkg_resources.WorkingSet()
@@ -612,55 +728,69 @@ class PluginManager(object):
if not isinstance(groups, (list, tuple)):
groups = [groups]
- for group in groups:
- for entry_point in working_set.iter_entry_points(group=group, name=None):
- key = entry_point.name
- module_name = entry_point.module_name
- version = entry_point.dist.version
-
- if key in existing or key in result or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]):
- # plugin is already defined or marked as uninstalled, ignore it
- continue
-
- kwargs = dict(module_name=module_name, version=version)
- package_name = None
+ def wrapped(gen):
+ # to protect against some issues in installed packages that make iteration over entry points
+ # fall on its face - e.g. https://groups.google.com/forum/#!msg/octoprint/DyXdqhR0U7c/kKMUsMmIBgAJ
+ for entry in gen:
try:
- module_pkginfo = InstalledEntryPoint(entry_point)
+ yield entry
except:
- self.logger.exception("Something went wrong while retrieving package info data for module %s" % module_name)
- else:
- kwargs.update(dict(
- name=module_pkginfo.name,
- summary=module_pkginfo.summary,
- author=module_pkginfo.author,
- url=module_pkginfo.home_page,
- license=module_pkginfo.license
- ))
- package_name = module_pkginfo.name
+ self.logger.exception("Something went wrong while processing the entry points of a package in the "
+ "Python environment - broken entry_points.txt in some package?")
- plugin = self._import_plugin_from_module(key, **kwargs)
- if plugin:
- plugin.origin = EntryPointOrigin("entry_point", group, module_name, package_name, version)
+ for group in groups:
+ for entry_point in wrapped(working_set.iter_entry_points(group=group, name=None)):
+ try:
+ key = entry_point.name
+ module_name = entry_point.module_name
+ version = entry_point.dist.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 is_sub_path_of(plugin.location, self._python_prefix)
- or is_editable_install(self._python_install_dir,
- package_name,
- module_name,
- plugin.location))
+ if key in existing or key in result or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]):
+ # plugin is already defined or marked as uninstalled, ignore it
+ continue
- plugin.enabled = False
- result[key] = plugin
+ kwargs = dict(module_name=module_name, version=version)
+ package_name = None
+ try:
+ module_pkginfo = InstalledEntryPoint(entry_point)
+ except:
+ self.logger.exception("Something went wrong while retrieving package info data for module %s" % module_name)
+ else:
+ kwargs.update(dict(
+ name=module_pkginfo.name,
+ summary=module_pkginfo.summary,
+ author=module_pkginfo.author,
+ url=module_pkginfo.home_page,
+ license=module_pkginfo.license
+ ))
+ package_name = module_pkginfo.name
+
+ plugin = self._import_plugin_from_module(key, **kwargs)
+ if plugin:
+ plugin.origin = EntryPointOrigin("entry_point", group, module_name, package_name, version)
+ plugin.enabled = False
+
+ # 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 is_sub_path_of(plugin.location, self._python_prefix)
+ or is_editable_install(self._python_install_dir,
+ package_name,
+ module_name,
+ plugin.location))
+
+ result[key] = plugin
+ except:
+ self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group))
return result
- def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None):
+ def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None,
+ author=None, url=None, license=None, bundled=False):
# TODO error handling
try:
if folder:
@@ -673,8 +803,41 @@ class PluginManager(object):
self.logger.warn("Could not locate plugin {key}".format(key=key))
return None
- plugin = self._import_plugin(key, *module, name=name, version=version, summary=summary, author=author, url=url, license=license)
- if plugin is None:
+ # Create a simple dummy entry first ...
+ plugin = PluginInfo(key, module[1], None, name=name, version=version, description=summary, author=author,
+ url=url, license=license)
+ plugin.bundled = bundled
+
+ if self._is_plugin_disabled(key):
+ self.logger.info("Plugin {} is disabled.".format(plugin))
+ plugin.forced_disabled = True
+
+ if self._is_plugin_blacklisted(key) or (plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version)):
+ self.logger.warn("Plugin {} is blacklisted.".format(plugin))
+ plugin.blacklisted = True
+
+ if not plugin.validate("before_import", additional_validators=self.plugin_validators):
+ return plugin
+
+ # ... then create and return the real one
+ return self._import_plugin(key, *module,
+ name=name, version=version, summary=summary, author=author, url=url,
+ license=license, bundled=bundled, parsed_metadata=plugin.parsed_metadata)
+
+ def _import_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None):
+ try:
+ instance = imp.load_module(key, f, filename, description)
+ plugin = PluginInfo(key, filename, instance,
+ name=name,
+ version=version,
+ description=summary,
+ author=author,
+ url=url,
+ license=license,
+ parsed_metadata=parsed_metadata)
+ plugin.bundled = bundled
+ except:
+ self.logger.exception("Error loading plugin {key}".format(key=key))
return None
if plugin.check():
@@ -683,18 +846,22 @@ class PluginManager(object):
self.logger.warn("Plugin \"{plugin}\" did not pass check".format(plugin=str(plugin)))
return None
-
- def _import_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None):
- try:
- instance = imp.load_module(key, f, filename, description)
- return PluginInfo(key, filename, instance, name=name, version=version, description=summary, author=author, url=url, license=license)
- except:
- self.logger.exception("Error loading plugin {key}".format(key=key))
- return None
-
def _is_plugin_disabled(self, key):
return key in self.plugin_disabled_list or key.endswith('disabled')
+ def _is_plugin_blacklisted(self, key):
+ return key in self.plugin_blacklist
+
+ def _is_plugin_version_blacklisted(self, key, version):
+ def matches_plugin(entry):
+ if isinstance(entry, (tuple, list)) and len(entry) == 2:
+ entry_key, entry_version = entry
+ return entry_key == key and entry_version == version
+ return False
+
+ return any(map(lambda entry: matches_plugin(entry),
+ self.plugin_blacklist))
+
def reload_plugins(self, startup=False, initialize_implementations=True, force_reload=None):
self.logger.info("Loading plugins from {folders} and installed plugin packages...".format(
folders=", ".join(map(lambda x: x[0] if isinstance(x, tuple) else str(x), self.plugin_folders))
@@ -709,7 +876,8 @@ class PluginManager(object):
# 1st pass: loading the plugins
for name, plugin in plugins.items():
try:
- self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations)
+ if not plugin.blacklisted and not plugin.forced_disabled:
+ self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations)
except PluginNeedsRestart:
pass
except PluginLifecycleException as e:
@@ -722,7 +890,10 @@ class PluginManager(object):
# 2nd pass: enabling those plugins that need enabling
for name, plugin in plugins.items():
try:
- if plugin.loaded and not self._is_plugin_disabled(name):
+ if plugin.loaded and not plugin.forced_disabled:
+ if plugin.blacklisted:
+ self.logger.warn("Plugin {} is blacklisted. Not enabling it.".format(plugin))
+ continue
self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup)
except PluginNeedsRestart:
pass
@@ -776,7 +947,6 @@ class PluginManager(object):
plugin.load()
plugin.validate("after_load", additional_validators=self.plugin_validators)
self.on_plugin_loaded(name, plugin)
-
plugin.loaded = True
self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals()))
@@ -910,9 +1080,9 @@ class PluginManager(object):
# evaluate registered implementation
if plugin.implementation:
- for plugin_type in self.plugin_types:
- if isinstance(plugin.implementation, plugin_type):
- self.plugin_implementations_by_type[plugin_type].append((name, plugin.implementation))
+ mixins = self.mixins_matching_bases(plugin.implementation.__class__, *self.plugin_bases)
+ for mixin in mixins:
+ self.plugin_implementations_by_type[mixin].append((name, plugin.implementation))
self.plugin_implementations[name] = plugin.implementation
@@ -935,9 +1105,10 @@ class PluginManager(object):
if name in self.plugin_implementations:
del self.plugin_implementations[name]
- for plugin_type in self.plugin_types:
+ mixins = self.mixins_matching_bases(plugin.implementation.__class__, *self.plugin_bases)
+ for mixin in mixins:
try:
- self.plugin_implementations_by_type[plugin_type].remove((name, plugin.implementation))
+ self.plugin_implementations_by_type[mixin].remove((name, plugin.implementation))
except ValueError:
# that's ok, the plugin was just not registered for the type
pass
@@ -946,45 +1117,118 @@ class PluginManager(object):
return plugin.needs_restart or self.has_restart_needing_implementation(plugin) or self.has_restart_needing_hooks(plugin)
def has_restart_needing_implementation(self, plugin):
- if not plugin.implementation:
- return False
-
- return isinstance(plugin.implementation, RestartNeedingPlugin)
+ return self.has_any_of_mixins(plugin, RestartNeedingPlugin)
def has_restart_needing_hooks(self, plugin):
- if not plugin.hooks:
- return False
-
- hooks = plugin.hooks.keys()
- for hook in hooks:
- if self.is_restart_needing_hook(hook):
- return True
- return False
+ return self.has_any_of_hooks(plugin, self.plugin_restart_needing_hooks)
def has_obsolete_hooks(self, plugin):
- if not plugin.hooks:
- return False
-
- hooks = plugin.hooks.keys()
- for hook in hooks:
- if self.is_obsolete_hook(hook):
- return True
- return False
+ return self.has_any_of_hooks(plugin, self.plugin_obsolete_hooks)
def is_restart_needing_hook(self, hook):
- if self.plugin_restart_needing_hooks is None:
- return False
-
- for h in self.plugin_restart_needing_hooks:
- if hook.startswith(h):
- return True
-
- return False
+ return self.hook_matches_hooks(hook, self.plugin_restart_needing_hooks)
def is_obsolete_hook(self, hook):
- if self.plugin_obsolete_hooks is None:
+ return self.hook_matches_hooks(hook, self.plugin_obsolete_hooks)
+
+ @staticmethod
+ def has_any_of_hooks(plugin, *hooks):
+ """
+ Tests if the ``plugin`` contains any of the provided ``hooks``.
+
+ Uses :func:`octoprint.plugin.core.PluginManager.hook_matches_hooks`.
+
+ Args:
+ plugin: plugin to test hooks for
+ *hooks: hooks to test against
+
+ Returns:
+ (bool): True if any of the plugin's hooks match the provided hooks,
+ False otherwise.
+ """
+
+ if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
+ hooks = hooks[0]
+
+ hooks = filter(lambda hook: hook is not None, hooks)
+ if not hooks:
return False
- return hook in self.plugin_obsolete_hooks
+ if not plugin or not plugin.hooks:
+ return False
+
+ plugin_hooks = plugin.hooks.keys()
+
+ return any(map(lambda hook: PluginManager.hook_matches_hooks(hook, *hooks),
+ plugin_hooks))
+
+ @staticmethod
+ def hook_matches_hooks(hook, *hooks):
+ """
+ Tests if ``hook`` matches any of the provided ``hooks`` to test for.
+
+ ``hook`` is expected to be an exact hook name.
+
+ ``hooks`` is expected to be a list containing one or more hook names or
+ patterns. That can be either an exact hook name or an
+ :func:`fnmatch.fnmatch` pattern.
+
+ Args:
+ hook: the hook to test
+ hooks: the hook name patterns to test against
+
+ Returns:
+ (bool): True if the ``hook`` matches any of the ``hooks``, False otherwise.
+
+ """
+
+ if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
+ hooks = hooks[0]
+
+ hooks = filter(lambda hook: hook is not None, hooks)
+ if not hooks:
+ return False
+ if not hook:
+ return False
+
+ return any(map(lambda h: fnmatch.fnmatch(hook, h),
+ hooks))
+
+ @staticmethod
+ def mixins_matching_bases(klass, *bases):
+ result = set()
+ for c in inspect.getmro(klass):
+ if c == klass or c in bases:
+ # ignore the exact class and our bases
+ continue
+ if issubclass(c, bases):
+ result.add(c)
+ return result
+
+ @staticmethod
+ def has_any_of_mixins(plugin, *mixins):
+ """
+ Tests if the ``plugin`` has an implementation implementing any
+ of the provided ``mixins``.
+
+ Args:
+ plugin: plugin for which to check the implementation
+ *mixins: mixins to test against
+
+ Returns:
+ (bool): True if the plugin's implementation implements any of the
+ provided mixins, False otherwise.
+ """
+
+ if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)):
+ mixins = mixins[0]
+
+ mixins = filter(lambda mixin: mixin is not None, mixins)
+ if not mixins:
+ return False
+ if not plugin or not plugin.implementation:
+ return False
+
+ return isinstance(plugin.implementation, tuple(mixins))
def initialize_implementations(self, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
for name, plugin in self.enabled_plugins.items():
@@ -1083,7 +1327,7 @@ class PluginManager(object):
def log_all_plugins(self, show_bundled=True, bundled_str=(" (bundled)", ""), show_location=True,
- location_str=" = {location}", show_enabled=True, enabled_str=(" ", "!"),
+ location_str=" = {location}", show_enabled=True, enabled_str=(" ", "!", "#"),
only_to_handler=None):
all_plugins = self.enabled_plugins.values() + self.disabled_plugins.values()
@@ -1255,7 +1499,8 @@ class PluginManager(object):
def register_message_receiver(self, client):
"""
Registers a ``client`` for receiving plugin messages. The ``client`` needs to be a callable accepting two
- input arguments, ``plugin`` (the sending plugin's identifier) and ``data`` (the message itself).
+ input arguments, ``plugin`` (the sending plugin's identifier) and ``data`` (the message itself), and one
+ optional keyword argument, ``permissions`` (an optional list of permissions to test against).
"""
if client is None:
@@ -1267,20 +1512,25 @@ class PluginManager(object):
Unregisters a ``client`` for receiving plugin messages.
"""
- self.registered_clients.remove(client)
+ try:
+ self.registered_clients.remove(client)
+ except ValueError:
+ # not registered
+ pass
- def send_plugin_message(self, plugin, data):
+ def send_plugin_message(self, plugin, data, permissions=None):
"""
Sends ``data`` in the name of ``plugin`` to all currently registered message receivers by invoking them
- with the two arguments.
+ with the three arguments.
Arguments:
plugin (str): The sending plugin's identifier.
data (object): The message.
+ permissions (list): A list of permissions to test against in the client.
"""
for client in self.registered_clients:
- try: client(plugin, data)
+ try: client(plugin, data, permissions=permissions)
except: self.logger.exception("Exception while sending plugin data to client")
def _sort_hooks(self, hook):
@@ -1426,6 +1676,13 @@ class Plugin(object):
initialization of the implementation.
"""
+ def __init__(self):
+ self._identifier = None
+ self._plugin_name = None
+ self._plugin_version = None
+ self._basefolder = None
+ self._logger = None
+
def initialize(self):
"""
Called by the plugin core after performing all injections. Override this to initialize your implementation.
diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py
index 8edfdf20c..c8b9488cc 100644
--- a/src/octoprint/plugin/types.py
+++ b/src/octoprint/plugin/types.py
@@ -8,9 +8,11 @@ Please note that the plugin implementation types are documented in the section
.. autoclass:: OctoPrintPlugin
:show-inheritance:
+ :members:
.. autoclass:: ReloadNeedingPlugin
:show-inheritance:
+ :members:
"""
@@ -23,6 +25,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
+# noinspection PyCompatibility
from past.builtins import basestring
class OctoPrintPlugin(Plugin):
@@ -74,16 +77,39 @@ class OctoPrintPlugin(Plugin):
The :class:`~octoprint.server.LifecycleManager` instance. Injected by the plugin core system upon initialization
of the implementation.
+ .. attribute:: _user_manager
+
+ The :class:`~octoprint.users.UserManager` instance. Injected by the plugin core system upon initialization
+ of the implementation.
+
+ .. attribute:: _connectivity_checker
+
+ The :class:`~octoprint.util.ConnectivityChecker` instance. Injected by the plugin core system upon initialization
+ of the implementation.
+
.. attribute:: _data_folder
Path to the data folder for the plugin to use for any data it might have to persist. Should always be accessed
through :meth:`get_plugin_data_folder` since that function will also ensure that the data folder actually exists
and if not creating it before returning it. Injected by the plugin core system upon initialization of the
implementation.
-
- .. automethod:: get_plugin_data_folder
"""
+ # noinspection PyMissingConstructor
+ def __init__(self):
+ self._plugin_manager = None
+ self._printer_profile_manager = None
+ self._event_bus = None
+ self._analysis_queue = None
+ self._slicing_manager = None
+ self._file_manager = None
+ self._printer = None
+ self._app_session_manager = None
+ self._plugin_lifecycle_manager = None
+ self._user_manager = None
+ self._connectivity_checker = None
+ self._data_folder = None
+
def get_plugin_data_folder(self):
"""
Retrieves the path to a data folder specifically for the plugin, ensuring it exists and if not creating it
@@ -105,6 +131,16 @@ class ReloadNeedingPlugin(Plugin):
Mixin for plugin types that need a reload of the UI after enabling/disabling them.
"""
+
+class EnvironmentDetectionPlugin(OctoPrintPlugin, RestartNeedingPlugin):
+
+ def get_additional_environment(self):
+ pass
+
+ def on_environment_detected(self, environment, *args, **kwargs):
+ pass
+
+
class StartupPlugin(OctoPrintPlugin, SortablePlugin):
"""
The ``StartupPlugin`` allows hooking into the startup of OctoPrint. It can be used to start up additional services
@@ -592,6 +628,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
See below for details on this.
"""
+ # noinspection PyMethodMayBeStatic,PyUnusedLocal
def will_handle_ui(self, request):
"""
Called by OctoPrint to determine if the mixin implementation will be
@@ -614,6 +651,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
"""
return False
+ # noinspection PyMethodMayBeStatic,PyUnusedLocal
def on_ui_render(self, now, request, render_kwargs):
"""
Called by OctoPrint to retrieve the response to send to the client
@@ -702,6 +740,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
return None
+ # noinspection PyMethodMayBeStatic
def get_ui_additional_key_data_for_cache(self):
"""
Allows to return additional data to use in the cache key.
@@ -713,6 +752,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
"""
return None
+ # noinspection PyMethodMayBeStatic
def get_ui_additional_tracked_files(self):
"""
Allows to return additional files to track for validating existing caches. By default OctoPrint
@@ -725,6 +765,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
"""
return None
+ # noinspection PyMethodMayBeStatic
def get_ui_custom_tracked_files(self):
"""
Allows to define a complete separate set of files to track for (in)validating the cache. If this
@@ -737,16 +778,18 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
"""
return None
+ # noinspection PyMethodMayBeStatic
def get_ui_custom_etag(self):
"""
Allows to use a custom way to calculate the ETag, instead of the default method (hashing
OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value).
Returns:
- basestring: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
+ str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
"""
return None
+ # noinspection PyMethodMayBeStatic
def get_ui_additional_etag(self, default_additional):
"""
Allows to provide a list of additional fields to use for ETag generation.
@@ -762,6 +805,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
"""
return default_additional
+ # noinspection PyMethodMayBeStatic
def get_ui_custom_lastmodified(self):
"""
Allows to calculate the LastModified differently than using the most recent modification
@@ -772,6 +816,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
"""
return None
+ # noinspection PyMethodMayBeStatic
def get_ui_preemptive_caching_enabled(self):
"""
Allows to control whether the view provided by the plugin should be preemptively
@@ -784,6 +829,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
"""
return True
+ # noinspection PyMethodMayBeStatic
def get_ui_data_for_preemptive_caching(self):
"""
Allows defining additional data to be persisted in the preemptive cache configuration, on
@@ -794,6 +840,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
"""
return None
+ # noinspection PyMethodMayBeStatic
def get_ui_additional_request_data_for_preemptive_caching(self):
"""
Allows defining additional request data to persist in the preemptive cache configuration and
@@ -809,6 +856,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
"""
return None
+ # noinspection PyMethodMayBeStatic
def get_ui_preemptive_caching_additional_unless(self):
"""
Allows defining additional reasons for temporarily not adding a preemptive cache record for
@@ -822,6 +870,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
"""
return False
+ # noinspection PyMethodMayBeStatic
def get_ui_custom_template_filter(self, default_template_filter):
"""
Allows to specify a custom template filter to use for filtering the template contained in the
@@ -906,6 +955,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
``WizardPlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`.
"""
+ # noinspection PyMethodMayBeStatic
def is_wizard_required(self):
"""
Allows the plugin to report whether it needs to display a wizard to the
@@ -921,6 +971,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
"""
return False
+ # noinspection PyMethodMayBeStatic
def get_wizard_version(self):
"""
The version of this plugin's wizard. OctoPrint will only display a wizard
@@ -940,6 +991,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
"""
return None
+ # noinspection PyMethodMayBeStatic
def get_wizard_details(self):
"""
Called by OctoPrint when the wizard wrapper dialog is shown. Allows the plugin to return data
@@ -954,6 +1006,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
"""
return dict()
+ # noinspection PyMethodMayBeStatic,PyUnusedLocal
def on_wizard_finish(self, handled):
"""
Called by OctoPrint whenever the user finishes a wizard session.
@@ -972,6 +1025,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
"""
pass
+ # noinspection PyProtectedMember
@classmethod
def is_wizard_ignored(cls, seen_wizards, implementation):
"""
@@ -1122,6 +1176,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
}
"""
+ # noinspection PyMethodMayBeStatic
def get_api_commands(self):
"""
Return a dictionary here with the keys representing the accepted commands and the values being lists of
@@ -1129,12 +1184,14 @@ class SimpleApiPlugin(OctoPrintPlugin):
"""
return None
+ # noinspection PyMethodMayBeStatic
def is_api_adminonly(self):
"""
Return True if the API is only available to users having the admin role.
"""
return False
+ # noinspection PyMethodMayBeStatic
def on_api_command(self, command, data):
"""
Called by OctoPrint upon a POST request to ``/api/plugin/``. ``command`` will contain one of
@@ -1154,6 +1211,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
"""
return None
+ # noinspection PyMethodMayBeStatic
def on_api_get(self, request):
"""
Called by OctoPrint upon a GET request to ``/api/plugin/``. ``request`` will contain the
@@ -1252,6 +1310,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
return f
return decorator
+ # noinspection PyProtectedMember
def get_blueprint(self):
"""
Creates and returns the blueprint for your plugin. Override this if you want to define and handle your blueprint yourself.
@@ -1317,6 +1376,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
template_folder=template_folder
)
+ # noinspection PyMethodMayBeStatic
def is_blueprint_protected(self):
"""
Whether a valid API key is needed to access the blueprint (the default) or not. Note that this only restricts
@@ -1383,18 +1443,21 @@ class SettingsPlugin(OctoPrintPlugin):
Make sure to protect sensitive information stored by your plugin that only logged in administrators (or users)
should have access to via :meth:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths`. OctoPrint will
- return its settings on the REST API even to anonymous clients, but will filter out fields it know are restricted,
+ return its settings on the REST API even to anonymous clients, but will filter out fields it knows are restricted,
therefore you **must** make sure that you specify sensitive information accordingly to limit access as required!
-
- .. attribute:: _settings
-
- The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by
- 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."""
+ # noinspection PyMissingConstructor
+ def __init__(self):
+ self._settings = None
+ """
+ The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by
+ the plugin core system upon initialization of the implementation.
+ """
+
def on_settings_load(self):
"""
Loads the settings for the plugin, called by the Settings API view in order to retrieve all settings from
@@ -1420,6 +1483,8 @@ class SettingsPlugin(OctoPrintPlugin):
"""
from flask_login import current_user
import copy
+
+ from octoprint.access.permissions import Permissions
data = copy.deepcopy(self._settings.get_all_data(merged=True))
if self.config_version_key in data:
@@ -1427,6 +1492,7 @@ class SettingsPlugin(OctoPrintPlugin):
restricted_paths = self.get_settings_restricted_paths()
+ # noinspection PyShadowingNames
def restrict_path_unless(data, path, condition):
if not path:
return
@@ -1464,7 +1530,7 @@ class SettingsPlugin(OctoPrintPlugin):
node[key] = None
conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous,
- admin=lambda: current_user is not None and not current_user.is_anonymous and current_user.is_admin,
+ admin=lambda: current_user is not None and current_user.has_permission(Permissions.SETTINGS),
never=lambda: False)
for level, condition in conditions.items():
@@ -1525,6 +1591,7 @@ class SettingsPlugin(OctoPrintPlugin):
return diff
+ # noinspection PyMethodMayBeStatic
def get_settings_defaults(self):
"""
Retrieves the plugin's default settings with which the plugin's settings manager will be initialized.
@@ -1534,12 +1601,13 @@ class SettingsPlugin(OctoPrintPlugin):
"""
return dict()
+ # noinspection PyMethodMayBeStatic
def get_settings_restricted_paths(self):
"""
Retrieves the list of paths in the plugin's settings which be restricted on the REST API.
- Override this in your plugin's implementation to restrict whether a path should only be returned to logged in
- users & admins, only to admins, or never on the REST API.
+ Override this in your plugin's implementation to restrict whether a path should only be returned to users with
+ the SETTINGS permission, any logged in users, or never on the REST API.
Return a ``dict`` with the keys ``admin``, ``user``, ``never`` mapping to a list of paths (as tuples or lists of
the path elements) for which to restrict access via the REST API accordingly. Paths returned for the ``admin``
@@ -1588,6 +1656,7 @@ class SettingsPlugin(OctoPrintPlugin):
"""
return dict()
+ # noinspection PyMethodMayBeStatic
def get_settings_preprocessors(self):
"""
Retrieves the plugin's preprocessors to use for preprocessing returned or set values prior to returning/setting
@@ -1625,6 +1694,7 @@ class SettingsPlugin(OctoPrintPlugin):
"""
return dict(), dict()
+ # noinspection PyMethodMayBeStatic
def get_settings_version(self):
"""
Retrieves the settings format version of the plugin.
@@ -1639,6 +1709,7 @@ class SettingsPlugin(OctoPrintPlugin):
"""
return None
+ # noinspection PyMethodMayBeStatic
def on_settings_migrate(self, target, current):
"""
Called by OctoPrint if it detects that the installed version of the plugin necessitates a higher settings version
@@ -1725,6 +1796,7 @@ class EventHandlerPlugin(OctoPrintPlugin):
videos rendering etc.
"""
+ # noinspection PyMethodMayBeStatic
def on_event(self, event, payload):
"""
Called by OctoPrint upon processing of a fired event on the platform.
@@ -1743,6 +1815,7 @@ class SlicerPlugin(OctoPrintPlugin):
"""
+ # noinspection PyMethodMayBeStatic
def is_slicer_configured(self):
"""
Unless the return value of this method is ``True``, OctoPrint will not register the slicer within the slicing
@@ -1752,6 +1825,7 @@ class SlicerPlugin(OctoPrintPlugin):
"""
return False
+ # noinspection PyMethodMayBeStatic
def get_slicer_properties(self):
"""
Plugins should override this method to return a ``dict`` containing a bunch of meta data about the implemented slicer.
@@ -1789,6 +1863,48 @@ class SlicerPlugin(OctoPrintPlugin):
destination_extensions=["gco", "gcode", "g"]
)
+ def get_slicer_profiles(self, profile_path):
+ """
+ Fetch all :class:`~octoprint.slicing.SlicingProfile` stored for this slicer.
+
+ For compatibility reasons with existing slicing plugins this method defaults to returning profiles parsed from
+ .profile files in the plugin's ``profile_path``, utilizing the :func:`SlicingPlugin.get_slicer_profile` method
+ of the plugin implementation.
+
+ Arguments:
+ profile_path (str): The base folder where OctoPrint stores this slicer plugin's profiles
+ """
+
+ try:
+ from os import scandir
+ except ImportError:
+ from scandir import scandir
+
+ import octoprint.util
+
+ profiles = dict()
+ for entry in scandir(profile_path):
+ if not entry.name.endswith(".profile") or octoprint.util.is_hidden_path(entry.name):
+ # we are only interested in profiles and no hidden files
+ continue
+
+ profile_name = entry.name[:-len(".profile")]
+ profiles[profile_name] = self.get_slicer_profile(entry.path)
+ return profiles
+
+ # noinspection PyMethodMayBeStatic
+ def get_slicer_profiles_lastmodified(self, profile_path):
+ import os
+ try:
+ from os import scandir
+ except ImportError:
+ from scandir import scandir
+
+ lms = [os.stat(profile_path).st_mtime]
+ lms += [os.stat(entry.path).st_mtime for entry in scandir(profile_path) if entry.name.endswith(".profile")]
+ return max(lms)
+
+ # noinspection PyMethodMayBeStatic
def get_slicer_default_profile(self):
"""
Should return a :class:`~octoprint.slicing.SlicingProfile` containing the default slicing profile to use with
@@ -1800,6 +1916,7 @@ class SlicerPlugin(OctoPrintPlugin):
"""
return None
+ # noinspection PyMethodMayBeStatic
def get_slicer_profile(self, path):
"""
Should return a :class:`~octoprint.slicing.SlicingProfile` parsed from the slicing profile stored at the
@@ -1813,6 +1930,7 @@ class SlicerPlugin(OctoPrintPlugin):
"""
return None
+ # noinspection PyMethodMayBeStatic
def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None):
"""
Should save the provided :class:`~octoprint.slicing.SlicingProfile` to the indicated ``path``, after applying
@@ -1829,6 +1947,7 @@ class SlicerPlugin(OctoPrintPlugin):
"""
pass
+ # noinspection PyMethodMayBeStatic
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None):
"""
Called by OctoPrint to slice ``model_path`` for the indicated ``printer_profile``. If the ``machinecode_path`` is ``None``,
@@ -1885,6 +2004,7 @@ class SlicerPlugin(OctoPrintPlugin):
"""
pass
+ # noinspection PyMethodMayBeStatic
def cancel_slicing(self, machinecode_path):
"""
Cancels the slicing to the indicated file.
@@ -1901,16 +2021,18 @@ class ProgressPlugin(OctoPrintPlugin):
limited to minimally 1% steps.
"""
+ # noinspection PyMethodMayBeStatic
def on_print_progress(self, storage, path, progress):
"""
Called by OctoPrint on minimally 1% increments during a running print job.
- :param string location: Location of the file
+ :param string storage: Location of the file
:param string path: Path of the file
:param int progress: Current progress as a value between 0 and 100
"""
pass
+ # noinspection PyMethodMayBeStatic
def on_slicing_progress(self, slicer, source_location, source_path, destination_location, destination_path, progress):
"""
Called by OctoPrint on minimally 1% increments during a running slicing job.
@@ -1936,6 +2058,7 @@ class AppPlugin(OctoPrintPlugin):
"""
+ # noinspection PyMethodMayBeStatic
def get_additional_apps(self):
return []
diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py
index 7f73efb20..344ad3483 100644
--- a/src/octoprint/plugins/announcements/__init__.py
+++ b/src/octoprint/plugins/announcements/__init__.py
@@ -20,16 +20,21 @@ import flask
from collections import OrderedDict
-from octoprint.server import admin_permission
-from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
+from octoprint.access.permissions import Permissions
+from octoprint.server.util.flask import require_firstrun, with_revalidation_checking, check_etag
+from octoprint.util import utmify
from flask_babel import gettext
+from octoprint import __version__ as OCTOPRINT_VERSION
+
class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.StartupPlugin,
- octoprint.plugin.TemplatePlugin):
+ octoprint.plugin.TemplatePlugin,
+ octoprint.plugin.EventHandlerPlugin):
+ # noinspection PyMissingConstructor
def __init__(self):
self._cached_channel_configs = None
self._cached_channel_configs_mutex = threading.RLock()
@@ -38,6 +43,22 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
self._slugify = Slugify()
self._slugify.safe_chars = "-_."
+ # Additional permissions hook
+
+ def get_additional_permissions(self):
+ return [
+ dict(key="READ",
+ name="Read announcements",
+ description=gettext("Allows to read announcements"),
+ roles=["read"]),
+ dict(key="MANAGE",
+ name="Manage announcement subscriptions",
+ description=gettext("Allows to manage announcement subscriptions. Includes \"Read announcements\" "
+ "permission"),
+ roles=["manage"],
+ permissions=["PLUGIN_ANNOUNCEMENTS_READ"])
+ ]
+
# StartupPlugin
def on_after_startup(self):
@@ -56,27 +77,27 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
description="Important announcements about OctoPrint.",
priority=1,
type="rss",
- url="http://octoprint.org/feeds/important.xml"),
+ url="https://octoprint.org/feeds/important.xml"),
_releases=dict(name="Release Announcements",
description="Announcements of new releases and release candidates of OctoPrint.",
priority=2,
type="rss",
- url="http://octoprint.org/feeds/releases.xml"),
+ url="https://octoprint.org/feeds/releases.xml"),
_blog=dict(name="On the OctoBlog",
description="Development news, community spotlights, OctoPrint On Air episodes and more from the official OctoBlog.",
priority=2,
type="rss",
- url="http://octoprint.org/feeds/octoblog.xml"),
+ url="https://octoprint.org/feeds/octoblog.xml"),
_plugins=dict(name="New Plugins in the Repository",
description="Announcements of new plugins released on the official Plugin Repository.",
priority=2,
type="rss",
- url="http://plugins.octoprint.org/feed.xml"),
+ url="https://plugins.octoprint.org/feed.xml"),
_octopi=dict(name="OctoPi News",
description="News around OctoPi, the Raspberry Pi image including OctoPrint.",
priority=2,
type="rss",
- url="http://octoprint.org/feeds/octopi.xml")),
+ url="https://octoprint.org/feeds/octopi.xml")),
enabled_channels=[],
forced_channels=["_important"],
channel_order=["_important", "_releases", "_blog", "_plugins", "_octopi"],
@@ -123,14 +144,14 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
def get_template_configs(self):
return [
dict(type="settings", name=gettext("Announcements"), template="announcements_settings.jinja2", custom_bindings=True),
- dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.isAdmin")
+ dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.hasPermission(access.permissions.PLUGIN_ANNOUNCEMENTS_ANNOUNCEMENT)")
]
# Blueprint Plugin
@octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"])
- @restricted_access
- @admin_permission.require(403)
+ @require_firstrun
+ @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
def get_channel_data(self):
from octoprint.settings import valid_boolean_trues
@@ -172,6 +193,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
hash = hashlib.sha1()
hash.update(repr(sorted(enabled)))
hash.update(repr(sorted(forced)))
+ hash.update(OCTOPRINT_VERSION)
for channel in sorted(channel_configs.keys()):
hash.update(repr(channel_configs[channel]))
@@ -180,6 +202,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
return hash.hexdigest()
+ # noinspection PyShadowingNames
def condition(lm, etag):
return check_etag(etag)
@@ -188,8 +211,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
unless=lambda: force)(view)()
@octoprint.plugin.BlueprintPlugin.route("/channels/", methods=["POST"])
- @restricted_access
- @admin_permission.require(403)
+ @require_firstrun
+ @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403)
def channel_command(self, channel):
from octoprint.server.util.flask import get_json_command_from_request
from octoprint.server import NO_CONTENT
@@ -206,10 +229,20 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
self._mark_read_until(channel, until)
elif command == "toggle":
+ if not Permissions.PLUGIN_ANNOUNCEMENTS_MANAGE.can():
+ return flask.make_response("Insufficient rights", 403)
self._toggle(channel)
return NO_CONTENT
+ ##~~ EventHandlerPlugin
+
+ def on_event(self, event, payload):
+ from octoprint.events import Events
+ if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False):
+ return
+ self._fetch_all_channels_async()
+
# Internal Tools
def _mark_read_until(self, channel, until):
@@ -266,6 +299,11 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
safe_key = self._slugify(key)
return self._get_channel_configs(force=force).get(safe_key)
+ def _fetch_all_channels_async(self, force=False):
+ thread = threading.Thread(target=self._fetch_all_channels, kwargs=dict(force=force))
+ thread.daemon = True
+ thread.start()
+
def _fetch_all_channels(self, force=False):
"""Fetch all channel feeds from cache or network."""
@@ -298,7 +336,10 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
if data is None:
# cache not allowed or empty, fetch from network
- data = self._get_channel_data_from_network(key, config)
+ if self._connectivity_checker.online:
+ data = self._get_channel_data_from_network(key, config)
+ else:
+ self._logger.info("Looks like we are offline, can't fetch announcements for channel {} from network".format(key))
return data
@@ -369,7 +410,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
summary=_lazy_images(entry["summary"]),
summary_without_images=_strip_images(entry["summary"]),
published=published,
- link=entry["link"],
+ link=utmify(entry["link"], source="octoprint", medium="announcements", content=OCTOPRINT_VERSION),
read=read)
def _get_channel_cache_path(self, key):
@@ -473,3 +514,7 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin you might miss i
"regarding security or other critical issues concerning OctoPrint.")
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = AnnouncementPlugin()
+
+__plugin_hooks__ = {
+ 'octoprint.access.permissions': __plugin_implementation__.get_additional_permissions
+}
diff --git a/src/octoprint/plugins/announcements/static/js/announcements.js b/src/octoprint/plugins/announcements/static/js/announcements.js
index a5af767d0..e4fc58f33 100644
--- a/src/octoprint/plugins/announcements/static/js/announcements.js
+++ b/src/octoprint/plugins/announcements/static/js/announcements.js
@@ -4,6 +4,7 @@ $(function() {
self.loginState = parameters[0];
self.settings = parameters[1];
+ self.access = parameters[2];
self.channels = new ItemListHelper(
"plugin.announcements.channels",
@@ -40,7 +41,7 @@ $(function() {
};
self.toggleButtonCss = function(data) {
- var icon = data.enabled ? "fa fa-circle" : "fa fa-circle-o";
+ var icon = data.enabled ? "fa fa-toggle-on" : "fa fa-toggle-off";
var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled;
@@ -54,8 +55,20 @@ $(function() {
return !data.forced;
};
+ self.cleanedLink = function(data) {
+ // Strips any query parameters from the link and returns it
+ var link = data.link;
+ if (!link) return link;
+
+ var queryPos = link.indexOf("?");
+ if (queryPos !== -1) {
+ link = link.substr(0, queryPos);
+ }
+ return link;
+ };
+
self.markRead = function(channel, until) {
- if (!self.loginState.isAdmin()) return;
+ if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
@@ -77,7 +90,7 @@ $(function() {
};
self.toggleChannel = function(channel) {
- if (!self.loginState.isAdmin()) return;
+ if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_MANAGE)) return;
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
@@ -102,7 +115,7 @@ $(function() {
};
self.retrieveData = function(force) {
- if (!self.loginState.isAdmin()) return;
+ if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
var url = PLUGIN_BASEURL + "announcements/channels";
if (force) {
@@ -120,7 +133,7 @@ $(function() {
};
self.fromResponse = function(data) {
- if (!self.loginState.isAdmin()) return;
+ if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
var currentTab = $("li.active a", self.announcementDialogTabs).attr("href");
@@ -141,7 +154,7 @@ $(function() {
};
self.showAnnouncementDialog = function(channel) {
- if (!self.loginState.isAdmin()) return;
+ if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
// lazy load images that still need lazy-loading
$("#plugin_announcements_dialog_content article img").lazyload();
@@ -178,7 +191,7 @@ $(function() {
};
self.displayAnnouncements = function(channels) {
- if (!self.loginState.isAdmin()) return;
+ if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return;
var displayLimit = self.settings.settings.plugins.announcements.display_limit();
var maxLength = self.settings.settings.plugins.announcements.summary_limit();
@@ -244,7 +257,7 @@ $(function() {
text += "";
if (rest) {
- text += gettext(_.sprintf("... and %(rest)d more.", {rest: rest}));
+ text += "
" + gettext(_.sprintf("... and %(rest)d more.", {rest: rest})) + "
diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py
index 6b7a5cd8b..2b817d541 100644
--- a/src/octoprint/plugins/corewizard/__init__.py
+++ b/src/octoprint/plugins/corewizard/__init__.py
@@ -1,22 +1,21 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
-__author__ = "Gina Häußge "
__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
-
from flask_babel import gettext
+from .subwizards import Subwizards
class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.SettingsPlugin,
- octoprint.plugin.BlueprintPlugin):
+ octoprint.plugin.BlueprintPlugin,
+ Subwizards):
#~~ TemplatePlugin API
@@ -25,8 +24,18 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
names = self._get_subwizard_attrs("_get_", "_wizard_name")
additional = self._get_subwizard_attrs("_get_", "_additional_wizard_template_data")
+ firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
+ firstrun = self._settings.global_get(["server", "firstRun"])
+
+ if not firstrun:
+ required = dict((key, value) for key, value in required.items()
+ if not firstrunonly.get(key, lambda: False)())
+
result = list()
for key, method in required.items():
+ if not callable(method):
+ continue
+
if not method():
continue
@@ -37,7 +46,11 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
if not name:
continue
- config = dict(type="wizard", name=name, template="corewizard_{}_wizard.jinja2".format(key), div="wizard_plugin_corewizard_{}".format(key))
+ config = dict(type="wizard",
+ name=name,
+ template="corewizard_{}_wizard.jinja2".format(key),
+ div="wizard_plugin_corewizard_{}".format(key),
+ suffix="_{}".format(key))
if key in additional:
additional_result = additional[key]()
if additional_result:
@@ -51,7 +64,8 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
def get_assets(self):
if self.is_wizard_required():
return dict(
- js=["js/corewizard.js"]
+ js=["js/corewizard.js"],
+ css=["css/corewizard.css"]
)
else:
return dict()
@@ -59,8 +73,16 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
#~~ 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()))
+ required = self._get_subwizard_attrs("_is_", "_wizard_required")
+ firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
+ firstrun = self._settings.global_get(["server", "firstRun"])
+
+ if not firstrun:
+ required = dict((key, value) for key, value in required.items()
+ if not firstrunonly.get(key, lambda: False)())
+ any_required = any(map(lambda m: m(), required.values()))
+
+ return any_required
def get_wizard_details(self):
result = dict()
@@ -71,87 +93,8 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
return result
- #~~ ACL subwizard
-
- def _is_acl_wizard_required(self):
- return self._user_manager.enabled and not self._user_manager.hasBeenCustomized()
-
- def _get_acl_wizard_details(self):
- return dict(required=self._is_acl_wizard_required())
-
- def _get_acl_wizard_name(self):
- return gettext("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.get_json()
- if data is None:
- data = request.values
-
- if "ac" in data and data["ac"] in valid_boolean_trues and \
- "user" in data.keys() and "pass1" in data.keys() and \
- "pass2" in data.keys() and data["pass1"] == data["pass2"]:
- # configure access control
- self._settings.global_set_boolean(["accessControl", "enabled"], True)
- self._user_manager.enable()
- self._user_manager.addUser(data["user"], data["pass1"], True, ["user", "admin"], overwrite=True)
- elif "ac" in data.keys() and not data["ac"] in valid_boolean_trues:
- # disable access control
- self._settings.global_set_boolean(["accessControl", "enabled"], False)
-
- octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser
- octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader)
-
- self._user_manager.disable()
- self._settings.save()
- return NO_CONTENT
-
- #~~ Webcam subwizard
-
- def _is_webcam_wizard_required(self):
- webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"])
- webcam_stream_url = self._settings.global_get(["webcam", "stream"])
- 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(required=self._is_webcam_wizard_required())
-
- def _get_webcam_wizard_name(self):
- return gettext("Webcam & Timelapse")
-
- #~~ Server commands subwizard
-
- def _is_servercommands_wizard_required(self):
- system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"])
- system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
- server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
-
- return not (system_shutdown_command and system_restart_command and server_restart_command)
-
- def _get_servercommands_wizard_details(self):
- return dict(required=self._is_servercommands_wizard_required())
-
- def _get_servercommands_wizard_name(self):
- return gettext("Server Commands")
-
- #~~ Printer profile subwizard
-
- def _is_printerprofile_wizard_required(self):
- return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1
-
- def _get_printerprofile_wizard_details(self):
- return dict(required=self._is_printerprofile_wizard_required())
-
- def _get_printerprofile_wizard_name(self):
- return gettext("Default Printer Profile")
+ def get_wizard_version(self):
+ return 3
#~~ helpers
diff --git a/src/octoprint/plugins/corewizard/static/css/corewizard.css b/src/octoprint/plugins/corewizard/static/css/corewizard.css
new file mode 100644
index 000000000..2f15349dd
--- /dev/null
+++ b/src/octoprint/plugins/corewizard/static/css/corewizard.css
@@ -0,0 +1,4 @@
+#wizard_plugin_corewizard_pluginblacklist p {
+ line-height: 1.5;
+ margin-bottom: 1.5em;
+}
diff --git a/src/octoprint/plugins/corewizard/static/js/corewizard.js b/src/octoprint/plugins/corewizard/static/js/corewizard.js
index b59b676b2..1c8f41b7d 100644
--- a/src/octoprint/plugins/corewizard/static/js/corewizard.js
+++ b/src/octoprint/plugins/corewizard/static/js/corewizard.js
@@ -125,6 +125,167 @@ $(function() {
self.settingsViewModel = parameters[0];
}
+ function CoreWizardOnlineCheckViewModel(parameters) {
+ var self = this;
+
+ self.settingsViewModel = parameters[0];
+
+ self.setup = ko.observable(false);
+
+ self.decision = ko.observable();
+ self.required = false;
+ self.active = false;
+
+ self.enableOnlineCheck = function() {
+ self.settingsViewModel.server_onlineCheck_enabled(true);
+ self.decision(true);
+ self._sendData();
+ };
+
+ self.disableOnlineCheck = function() {
+ self.settingsViewModel.server_onlineCheck_enabled(false);
+ self.decision(false);
+ self._sendData();
+ };
+
+ self.onBeforeWizardTabChange = function(next, current) {
+ if (!self.required) return true;
+
+ if (!current || !_.startsWith(current, "wizard_plugin_corewizard_onlinecheck_") || self.setup()) {
+ return true;
+ }
+
+ self._showDecisionNeededDialog();
+ return false;
+ };
+
+ self.onBeforeWizardFinish = function() {
+ if (!self.required) return true;
+
+ if (self.setup()) {
+ return true;
+ }
+
+ self._showDecisionNeededDialog();
+ return false;
+ };
+
+ self.onWizardPreventSettingsRefreshDialog = function() {
+ return self.active;
+ };
+
+ self.onWizardDetails = function(response) {
+ self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.onlinecheck && response.corewizard.details.onlinecheck.required;
+ };
+
+ self._showDecisionNeededDialog = function() {
+ showMessageDialog({
+ title: gettext("Please set up the online connectivity check"),
+ message: gettext("You haven't yet decided on whether to enable or disable the online connectivity check. You need to either enable or disable it before continuing.")
+ });
+ };
+
+ self._sendData = function() {
+ var data = {
+ server: {
+ onlineCheck: {
+ enabled: self.settingsViewModel.server_onlineCheck_enabled(),
+ interval: self.settingsViewModel.server_onlineCheck_interval(),
+ host: self.settingsViewModel.server_onlineCheck_host(),
+ port: self.settingsViewModel.server_onlineCheck_port()
+ }
+ }
+ };
+
+ self.active = true;
+ self.settingsViewModel.saveData(data)
+ .done(function() {
+ self.setup(true);
+ self.active = false;
+ });
+ };
+
+ }
+
+ function CoreWizardPluginBlacklistViewModel(parameters) {
+ var self = this;
+
+ self.settingsViewModel = parameters[0];
+
+ self.setup = ko.observable(false);
+
+ self.decision = ko.observable();
+ self.required = false;
+ self.active = false;
+
+ self.enablePluginBlacklist = function() {
+ self.settingsViewModel.server_pluginBlacklist_enabled(true);
+ self.decision(true);
+ self._sendData();
+ };
+
+ self.disablePluginBlacklist = function() {
+ self.settingsViewModel.server_pluginBlacklist_enabled(false);
+ self.decision(false);
+ self._sendData();
+ };
+
+ self.onBeforeWizardTabChange = function(next, current) {
+ if (!self.required) return true;
+
+ if (!current || !_.startsWith(current, "wizard_plugin_corewizard_pluginblacklist_") || self.setup()) {
+ return true;
+ }
+
+ self._showDecisionNeededDialog();
+ return false;
+ };
+
+ self.onBeforeWizardFinish = function() {
+ if (!self.required) return true;
+
+ if (self.setup()) {
+ return true;
+ }
+
+ self._showDecisionNeededDialog();
+ return false;
+ };
+
+ self.onWizardPreventSettingsRefreshDialog = function() {
+ return self.active;
+ };
+
+ self.onWizardDetails = function(response) {
+ self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.pluginblacklist && response.corewizard.details.pluginblacklist.required;
+ };
+
+ self._showDecisionNeededDialog = function() {
+ showMessageDialog({
+ title: gettext("Please set up the plugin blacklist processing"),
+ message: gettext("You haven't yet decided on whether to enable or disable the plugin blacklist processing. You need to either enable or disable it before continuing.")
+ });
+ };
+
+ self._sendData = function() {
+ var data = {
+ server: {
+ pluginBlacklist: {
+ enabled: self.settingsViewModel.server_pluginBlacklist_enabled()
+ }
+ }
+ };
+
+ self.active = true;
+ self.settingsViewModel.saveData(data)
+ .done(function() {
+ self.setup(true);
+ self.active = false;
+ });
+ };
+
+ }
+
function CoreWizardPrinterProfileViewModel(parameters) {
var self = this;
@@ -160,21 +321,29 @@ $(function() {
};
}
- OCTOPRINT_VIEWMODELS.push([
- CoreWizardAclViewModel,
- ["loginStateViewModel"],
- "#wizard_plugin_corewizard_acl"
- ], [
- CoreWizardWebcamViewModel,
- ["settingsViewModel"],
- "#wizard_plugin_corewizard_webcam"
- ], [
- CoreWizardServerCommandsViewModel,
- ["settingsViewModel"],
- "#wizard_plugin_corewizard_servercommands"
- ], [
- CoreWizardPrinterProfileViewModel,
- ["printerProfilesViewModel"],
- "#wizard_plugin_corewizard_printerprofile"
- ]);
+ OCTOPRINT_VIEWMODELS.push({
+ construct: CoreWizardAclViewModel,
+ dependencies: ["loginStateViewModel"],
+ elements: ["#wizard_plugin_corewizard_acl"]
+ }, {
+ construct: CoreWizardWebcamViewModel,
+ dependencies: ["settingsViewModel"],
+ elements: ["#wizard_plugin_corewizard_webcam"]
+ }, {
+ construct: CoreWizardServerCommandsViewModel,
+ dependencies: ["settingsViewModel"],
+ elements: ["#wizard_plugin_corewizard_servercommands"]
+ }, {
+ construct: CoreWizardOnlineCheckViewModel,
+ dependencies: ["settingsViewModel"],
+ elements: ["#wizard_plugin_corewizard_onlinecheck"]
+ }, {
+ construct: CoreWizardPluginBlacklistViewModel,
+ dependencies: ["settingsViewModel"],
+ elements: ["#wizard_plugin_corewizard_pluginblacklist"]
+ }, {
+ construct: CoreWizardPrinterProfileViewModel,
+ dependencies: ["printerProfilesViewModel"],
+ elements: ["#wizard_plugin_corewizard_printerprofile"]
+ });
});
diff --git a/src/octoprint/plugins/corewizard/subwizards.py b/src/octoprint/plugins/corewizard/subwizards.py
new file mode 100644
index 000000000..550b701a2
--- /dev/null
+++ b/src/octoprint/plugins/corewizard/subwizards.py
@@ -0,0 +1,154 @@
+# coding=utf-8
+from __future__ import absolute_import, division, print_function
+
+__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
+
+import sys
+import inspect
+from flask_babel import gettext
+
+
+# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
+class ServerCommandsSubwizard(object):
+ def _is_servercommands_wizard_firstrunonly(self):
+ return True
+
+ def _is_servercommands_wizard_required(self):
+ system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"])
+ system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
+ server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
+
+ return not (system_shutdown_command and system_restart_command and server_restart_command)
+
+ def _get_servercommands_wizard_details(self):
+ return dict(required=self._is_servercommands_wizard_required())
+
+ def _get_servercommands_wizard_name(self):
+ return gettext("Server Commands")
+
+
+# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
+class WebcamSubwizard(object):
+ def _is_webcam_wizard_firstrunonly(self):
+ return True
+
+ def _is_webcam_wizard_required(self):
+ webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"])
+ webcam_stream_url = self._settings.global_get(["webcam", "stream"])
+ 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(required=self._is_webcam_wizard_required())
+
+ def _get_webcam_wizard_name(self):
+ return gettext("Webcam & Timelapse")
+
+
+# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
+class AclSubwizard(object):
+ def _is_acl_wizard_firstrunonly(self):
+ return True
+
+ def _is_acl_wizard_required(self):
+ return self._user_manager.enabled and not self._user_manager.hasBeenCustomized()
+
+ def _get_acl_wizard_details(self):
+ return dict(required=self._is_acl_wizard_required())
+
+ def _get_acl_wizard_name(self):
+ return gettext("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, abort
+ from octoprint.server.api import valid_boolean_trues, NO_CONTENT
+
+ if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.hasBeenCustomized():
+ abort(404)
+
+ data = request.get_json()
+ if data is None:
+ data = request.values
+
+ if "ac" in data and data["ac"] in valid_boolean_trues and \
+ "user" in data.keys() and "pass1" in data.keys() and \
+ "pass2" in data.keys() and data["pass1"] == data["pass2"]:
+ # configure access control
+ self._settings.global_set_boolean(["accessControl", "enabled"], True)
+ self._user_manager.enable()
+ self._user_manager.addUser(data["user"], data["pass1"], True, ["user", "admin"], overwrite=True)
+ elif "ac" in data.keys() and not data["ac"] in valid_boolean_trues:
+ # disable access control
+ self._settings.global_set_boolean(["accessControl", "enabled"], False)
+
+ octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser
+ octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader)
+
+ self._user_manager.disable()
+ self._settings.save()
+ return NO_CONTENT
+
+
+# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
+class OnlineCheckSubwizard(object):
+ def _is_onlinecheck_wizard_firstrunonly(self):
+ return False
+
+ def _is_onlinecheck_wizard_required(self):
+ return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None
+
+ def _get_onlinecheck_wizard_details(self):
+ return dict(required=self._is_onlinecheck_wizard_required())
+
+ def _get_onlinecheck_wizard_name(self):
+ return gettext("Online connectivity check")
+
+ def _get_onlinecheck_additional_wizard_template_data(self):
+ return dict(mandatory=self._is_onlinecheck_wizard_required())
+
+
+# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
+class PluginBlacklistSubwizard(object):
+ def _is_pluginblacklist_wizard_firstrunonly(self):
+ return False
+
+ def _is_pluginblacklist_wizard_required(self):
+ return self._settings.global_get(["server", "pluginBlacklist", "enabled"]) is None
+
+ def _get_pluginblacklist_wizard_details(self):
+ return dict(required=self._is_pluginblacklist_wizard_required())
+
+ def _get_pluginblacklist_wizard_name(self):
+ return gettext("Plugin blacklist")
+
+ def _get_pluginblacklist_additional_wizard_template_data(self):
+ return dict(mandatory=self._is_pluginblacklist_wizard_required())
+
+
+# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
+class PrinterProfileSubwizard(object):
+ def _is_printerprofile_wizard_firstrunonly(self):
+ return True
+
+ def _is_printerprofile_wizard_required(self):
+ return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1
+
+ def _get_printerprofile_wizard_details(self):
+ return dict(required=self._is_printerprofile_wizard_required())
+
+ def _get_printerprofile_wizard_name(self):
+ return gettext("Default Printer Profile")
+
+
+Subwizards = type("Subwizwards",
+ tuple(cls for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass)
+ if clsname.endswith("Subwizard")),
+ dict())
diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2
new file mode 100644
index 000000000..fa4522cd0
--- /dev/null
+++ b/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2
@@ -0,0 +1,47 @@
+
{{ _('Configure the connectivity check') }}
+
+{% include "snippets/settings/server/serverOnlineCheckDescription.jinja2" %}
+
+
{% trans %}
+ If it is disabled OctoPrint will always assume to have a working connection to the internet.
+ If that should not actually be the case, server startups, update checks and the like might take longer.
+{% endtrans %}
+
+
{% trans %}
+ OctoPrint comes preconfigured to perform the connectivity check every 15 minutes. You may change the value here.
+{% endtrans %}
+
+
+
+
{% trans %}
+ OctoPrint comes preconfigured to utilize Google's DNS server 8.8.8.8, port 53 for the connectivity check (if
+ it's enabled). If you have concerns about using that, define the IP and port of a different online server that you
+ trust and that has a high availability.
+{% endtrans %}
+
+
+
+
{% trans %}
+ Finally, please decide on whether to enable or disable the connectivity check. You may change the configuration at
+ any time to a later date through Settings > Server right from within OctoPrint.
+{% endtrans %}
{% trans %}
+ Connectivity check is enabled.
+ {% endtrans %}
+
{% trans %}
+ Connectivity check is disabled.
+ {% endtrans %}
+
diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_pluginblacklist_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_pluginblacklist_wizard.jinja2
new file mode 100644
index 000000000..744bcbc0d
--- /dev/null
+++ b/src/octoprint/plugins/corewizard/templates/corewizard_pluginblacklist_wizard.jinja2
@@ -0,0 +1,31 @@
+
{{ _('Configure plugin blacklist processing') }}
+
+
{% trans %}
+ To protect against known severe issues with certain versions of third party plugins, OctoPrint supports the use
+ of a centralized plugin version blacklist to automatically disable such plugin versions before they can interfere with
+ normal operation, allowing you to uninstall or update them to a newer version.
+{% endtrans %}
+
+
{% trans url="https://plugins.octoprint.org/blacklist/" %}
+ By default, OctoPrint will use the blacklist hosted at plugins.octoprint.org/blacklist.json which you
+ can also take a look at in a more human readable format here.
+{% endtrans %}
+
+
{% trans %}
+ Please decide whether to allow fetch and use of this centralized blacklist starting with the next server start.
+ You may also change your decision at any time through Settings > Server right from within OctoPrint.
+{% endtrans %}
{% trans %}
+ Plugin blacklist processing is enabled.
+ {% endtrans %}
+
{% trans %}
+ Plugin blacklist processing is disabled.
+ {% endtrans %}
+
diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py
index 8713c3778..79bcd31c9 100644
--- a/src/octoprint/plugins/cura/__init__.py
+++ b/src/octoprint/plugins/cura/__init__.py
@@ -31,6 +31,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.WizardPlugin):
+ # noinspection PyMissingConstructor
def __init__(self):
self._logger = logging.getLogger("octoprint.plugins.cura")
self._cura_logger = logging.getLogger("octoprint.plugins.cura.engine")
@@ -80,6 +81,11 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
self._cura_logger.setLevel(logging.DEBUG if self._settings.get_boolean(["debug_logging"]) else logging.CRITICAL)
self._cura_logger.propagate = False
+ engine = self._settings.get(["cura_engine"])
+ if not self._is_engine_configured(cura_engine=engine):
+ self._logger.info(u"Path to CuraEngine has not been configured or does not exist (currently set to %r), "
+ u"Cura will not be selectable for slicing" % engine)
+
##~~ BlueprintPlugin API
@octoprint.plugin.BlueprintPlugin.route("/import", methods=["POST"])
@@ -95,23 +101,23 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
try:
profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path])
except Exception as e:
- self._logger.exception("Error while converting the imported profile")
- return flask.make_response("Something went wrong while converting imported profile: {message}".format(message=str(e)), 500)
+ self._logger.exception(u"Error while converting the imported profile")
+ return flask.make_response(u"Something went wrong while converting imported profile: {message}".format(message=str(e)), 500)
else:
- self._logger.warn("No profile file included for importing, aborting")
- return flask.make_response("No file included", 400)
+ self._logger.warn(u"No profile file included for importing, aborting")
+ return flask.make_response(u"No file included", 400)
if profile_dict is None:
- self._logger.warn("Could not convert profile, aborting")
- return flask.make_response("Could not convert Cura profile", 400)
+ self._logger.warn(u"Could not convert profile, aborting")
+ return flask.make_response(u"Could not convert Cura profile", 400)
name, _ = os.path.splitext(filename)
# default values for name, display name and description
profile_name = _sanitize_name(name)
profile_display_name = name
- profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now()))
+ profile_description = u"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
@@ -136,15 +142,15 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
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)
+ self._logger.warn(u"Profile {profile_name} already exists, aborting".format(**locals()))
+ return flask.make_response(u"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)
+ self._logger.warn(u"Profile {profile_name} could not be set as default, aborting".format(**locals()))
+ return flask.make_response(u"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),
@@ -168,11 +174,18 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
##~~ SettingsPlugin API
def on_settings_save(self, data):
+ old_engine = self._settings.get(["cura_engine"])
old_debug_logging = self._settings.get_boolean(["debug_logging"])
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
+ new_engine = self._settings.get(["cura_engine"])
new_debug_logging = self._settings.get_boolean(["debug_logging"])
+
+ if old_engine != new_engine and not self._is_engine_configured(new_engine):
+ self._logger.info(u"Path to CuraEngine has not been configured or does not exist (currently set to %r), "
+ u"Cura will not be selectable for slicing" % new_engine)
+
if old_debug_logging != new_debug_logging:
if new_debug_logging:
self._cura_logger.setLevel(logging.DEBUG)
@@ -190,11 +203,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
def is_slicer_configured(self):
cura_engine = normalize_path(self._settings.get(["cura_engine"]))
- if self._is_engine_configured(cura_engine=cura_engine):
- return True
- else:
- self._logger.info("Path to CuraEngine has not been configured yet or does not exist (currently set to %r), Cura will not be selectable for slicing" % cura_engine)
- return False
+ return self._is_engine_configured(cura_engine=cura_engine)
def get_slicer_properties(self):
return dict(
@@ -267,7 +276,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
executable = normalize_path(self._settings.get(["cura_engine"]))
if not executable:
- return False, "Path to CuraEngine is not configured "
+ return False, u"Path to CuraEngine is not configured "
working_dir = os.path.dirname(executable)
@@ -454,7 +463,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
try:
profile_dict = yaml.safe_load(f)
except:
- raise IOError("Couldn't read profile from {path}".format(path=path))
+ raise IOError(u"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"])
@@ -476,7 +485,7 @@ def _sanitize_name(name):
return None
if "/" in name or "\\" in name:
- raise ValueError("name must not contain / or \\")
+ raise ValueError(u"name must not contain / or \\")
import string
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
@@ -511,6 +520,7 @@ def _get_usage_from_length(filament_length, filament_diameter):
return usage
+
__plugin_name__ = "CuraEngine (<= 15.04)"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/cura.html"
diff --git a/src/octoprint/plugins/cura/profile.py b/src/octoprint/plugins/cura/profile.py
index c8dd13772..7b74fcdde 100644
--- a/src/octoprint/plugins/cura/profile.py
+++ b/src/octoprint/plugins/cura/profile.py
@@ -8,7 +8,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import re
+# noinspection PyCompatibility
from builtins import range
+# noinspection PyCompatibility
from past.builtins import basestring
class SupportLocationTypes(object):
diff --git a/src/octoprint/plugins/cura/static/js/cura.js b/src/octoprint/plugins/cura/static/js/cura.js
index 87f9d5f64..a435065cb 100644
--- a/src/octoprint/plugins/cura/static/js/cura.js
+++ b/src/octoprint/plugins/cura/static/js/cura.js
@@ -24,6 +24,7 @@ $(function() {
self.profileDescription = ko.observable();
self.profileAllowOverwrite = ko.observable(true);
self.profileMakeDefault = ko.observable(false);
+ self.profileFirst = ko.observable(false);
// make sure to update form data if any of the metadata changes
self.profileName.subscribe(function() { self.copyProfileMetadata(); });
@@ -134,7 +135,10 @@ $(function() {
self.profileDisplayName(undefined);
self.profileDescription(undefined);
self.profileAllowOverwrite(true);
- self.profileMakeDefault(false);
+
+ var firstProfile = self.profiles.items().length === 0;
+ self.profileMakeDefault(firstProfile);
+ self.profileFirst(firstProfile);
};
self.uploadElement.fileupload({
@@ -307,10 +311,9 @@ $(function() {
};
}
- // view model class, parameters for constructor, container to bind to
- OCTOPRINT_VIEWMODELS.push([
- CuraViewModel,
- ["loginStateViewModel", "settingsViewModel", "slicingViewModel"],
- ["#settings_plugin_cura", "#wizard_plugin_cura"]
- ]);
+ OCTOPRINT_VIEWMODELS.push({
+ construct: CuraViewModel,
+ dependencies: ["loginStateViewModel", "settingsViewModel", "slicingViewModel"],
+ elements: ["#settings_plugin_cura", "#wizard_plugin_cura"]
+ });
});
diff --git a/src/octoprint/plugins/cura/templates/cura_settings.jinja2 b/src/octoprint/plugins/cura/templates/cura_settings.jinja2
index d5726f2d5..51a5e31fd 100644
--- a/src/octoprint/plugins/cura/templates/cura_settings.jinja2
+++ b/src/octoprint/plugins/cura/templates/cura_settings.jinja2
@@ -16,7 +16,7 @@
{% include "snippets/settings/cura/profiles.jinja2" %}
-
+
{% trans %}For more information on configuration and usage please see the Plugin's homepage.{% endtrans %}
diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2
index 250c9e237..b2e6a522d 100644
--- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2
+++ b/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2
@@ -2,7 +2,7 @@
+ OctoPi is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+
+ OctoPi is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
";
+
+ var confirm = undefined;
+ var type = "success";
+ if (self.logContents.action.restart) {
+ text += "
" + gettext("A restart is needed for the changes to take effect.") + "
";
+ type = "warning";
+
+ if (self.restartCommandSpec) {
+ var restartClicked = false;
+ confirm = {
+ confirm: true,
+ buttons: [{
+ text: gettext("Restart now"),
+ click: function (notice) {
+ if (restartClicked) return;
+ restartClicked = true;
+ showConfirmationDialog({
+ message: gettext("This will restart your OctoPrint server.
This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."),
+ onproceed: function() {
+ OctoPrint.system.executeCommand("core", "restart")
+ .done(function() {
+ notice.remove();
+ 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.")
+ })
+ });
+ },
+ onclose: function() {
+ restartClicked = false;
+ }
+ });
+ }
+ }]
+ }
+ }
+ } else if (self.logContents.action.refresh) {
+ text += "
" + gettext("A refresh is needed for the changes to take effect.") + "
";
+ type = "warning";
+
+ var refreshClicked = false;
+ confirm = {
+ confirm: true,
+ buttons: [{
+ text: gettext("Reload now"),
+ click: function () {
+ if (refreshClicked) return;
+ refreshClicked = true;
+ location.reload(true);
+ }
+ }]
+ }
+ } else if (self.logContents.action_reconnect) {
+ text += "
" + gettext("A reconnect to the printer is needed for the changes to take effect.") + "
";
+ type = "warning";
+ }
+
+ var options = {
+ title: title,
+ text: text,
+ type: type
+ };
+
+ if (self.logNotification !== undefined) {
+ self.logNotification.remove();
+ }
+
+ if (confirm !== undefined) {
+ options.confirm = confirm;
+ options.hide = false;
+ self.logNotification = PNotify.singleButtonNotify(options);
+ } else {
+ self.logNotification = new PNotify(options);
+ }
};
self._markWorking = function(title, line) {
@@ -800,12 +873,13 @@ $(function() {
};
self._getToggleCommand = function(data) {
- var disable = (data.enabled || data.pending_enable || (data.safe_mode_victim && data.safe_mode_enabled)) && !data.pending_disable;
+ var disable = (data.enabled || (data.safe_mode_victim && !data.forced_disabled) || data.pending_enable)
+ && !data.pending_disable;
return disable ? "disable" : "enable";
};
self.toggleButtonCss = function(data) {
- var icon = self._getToggleCommand(data) == "enable" ? "fa fa-circle-o" : "fa fa-circle";
+ var icon = self._getToggleCommand(data) == "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on";
var disabled = (self.enableToggle(data)) ? "" : " disabled";
return icon + disabled;
@@ -814,7 +888,9 @@ $(function() {
self.toggleButtonTitle = function(data) {
var command = self._getToggleCommand(data);
if (command == "enable") {
- if (data.safe_mode_victim && !data.safe_mode_enabled) {
+ if (data.blacklisted) {
+ return gettext("Blacklisted");
+ } else if (data.safe_mode_victim) {
return gettext("Disabled due to active safe mode");
} else {
return gettext("Enable Plugin");
@@ -999,19 +1075,31 @@ $(function() {
self.settings = self.settingsViewModel.settings;
};
- self.onUserLoggedIn = function(user) {
- if (user.admin) {
+ self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
+ if (self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
self.requestData({eval_notices: true});
} else {
- self.onUserLoggedOut();
+ self._resetNotifications();
}
};
- self.onUserLoggedOut = function() {
+ self.onEventConnectivityChanged = function(payload) {
+ self.requestData({eval_notices: true});
+ };
+
+ self._resetNotifications = function() {
self._closeAllNotifications();
+ self.logContents.action.restart
+ = self.logContents.action.reload
+ = self.logContents.action.reconnect
+ = false;
+ self.logContents.steps = [];
};
self._closeAllNotifications = function() {
+ if (self.logNotification) {
+ self.logNotification.remove();
+ }
if (self.notifications) {
_.each(self.notifications, function(notification) {
notification.remove();
@@ -1020,7 +1108,7 @@ $(function() {
};
self.onServerDisconnect = function() {
- self._closeAllNotifications();
+ self._resetNotifications();
return true;
};
@@ -1028,23 +1116,14 @@ $(function() {
self.workingDialog = $("#settings_plugin_pluginmanager_workingdialog");
self.workingOutput = $("#settings_plugin_pluginmanager_workingdialog_output");
self.repositoryDialog = $("#settings_plugin_pluginmanager_repositorydialog");
-
- $("#settings_plugin_pluginmanager_repositorydialog_list").slimScroll({
- height: "306px",
- size: "5px",
- distance: "0",
- railVisible: true,
- alwaysVisible: true,
- scrollBy: "102px"
- });
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
- if (plugin != "pluginmanager") {
+ if (plugin !== "pluginmanager") {
return;
}
- if (!self.loginState.isAdmin()) {
+ if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) {
return;
}
@@ -1054,157 +1133,37 @@ $(function() {
var messageType = data.type;
- if (messageType == "loglines" && self.working()) {
+ if (messageType === "loglines" && self.working()) {
_.each(data.loglines, function(line) {
self.loglines.push(self._preprocessLine(line));
});
self._scrollWorkingOutputToEnd();
- } else if (messageType == "result") {
- var titleSuccess, textSuccess, textRestart, textReload, titleError, textError;
+ } else if (messageType === "result") {
var action = data.action;
-
var name = "Unknown";
- if (action == "install") {
- var unknown = false;
-
- if (data.hasOwnProperty("plugin")) {
- if (data.plugin == "unknown") {
- unknown = true;
- } else {
- name = data.plugin.name;
- }
- }
-
- if (unknown) {
- titleSuccess = _.sprintf(gettext("Plugin installed"));
- textSuccess = gettext("A plugin was installed successfully, however it was impossible to detect which one. Please Restart OctoPrint to make sure everything will be registered properly");
- textRestart = textSuccess;
- textReload = textSuccess;
- } else if (data.was_reinstalled) {
- titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" reinstalled"), {name: name});
- textSuccess = gettext("The plugin was reinstalled successfully");
- textRestart = gettext("The plugin was reinstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
- textReload = gettext("The plugin was reinstalled successfully, however a reload of the page is needed for that to take effect.");
- } else {
- titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" installed"), {name: name});
- textSuccess = gettext("The plugin was installed successfully");
- textRestart = gettext("The plugin was installed successfully, however a restart of OctoPrint is needed for that to take effect.");
- textReload = gettext("The plugin was installed successfully, however a reload of the page is needed for that to take effect.");
- }
-
- titleError = gettext("Something went wrong");
- var source = "unknown";
- if (data.hasOwnProperty("source")) {
- source = data.source;
- }
- var sourceType = "unknown";
- if (data.hasOwnProperty("source_type")) {
- sourceType = data.source_type;
- }
-
- if (data.hasOwnProperty("reason")) {
- if (data.was_reinstalled) {
- if (sourceType == "path") {
- textError = _.sprintf(gettext("Reinstalling the plugin from file failed: %(reason)s"), {reason: data.reason});
- } else {
- textError = _.sprintf(gettext("Reinstalling the plugin from \"%(source)s\" failed: %(reason)s"), {reason: data.reason, source: source});
- }
- } else {
- if (sourceType == "path") {
- textError = _.sprintf(gettext("Installing the plugin from file failed: %(reason)s"), {reason: data.reason});
- } else {
- textError = _.sprintf(gettext("Installing the plugin from \"%(source)s\" failed: %(reason)s"), {reason: data.reason, source: source});
- }
- }
- } else {
- if (data.was_reinstalled) {
- if (sourceType == "path") {
- textError = gettext("Reinstalling the plugin from file failed, please see the log for details.");
- } else {
- textError = _.sprintf(gettext("Reinstalling the plugin from \"%(source)s\" failed, please see the log for details."), {source: source});
- }
- } else {
- if (sourceType == "path") {
- textError = gettext("Installing the plugin from file failed, please see the log for details.");
- } else {
- textError = _.sprintf(gettext("Installing the plugin from \"%(source)s\" failed, please see the log for details."), {source: source});
- }
- }
- }
-
- } else if (action == "uninstall") {
- if (data.hasOwnProperty("plugin")) {
+ if (data.hasOwnProperty("plugin")) {
+ if (data.plugin !== "unknown") {
name = data.plugin.name;
}
-
- titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" uninstalled"), {name: name});
- textSuccess = gettext("The plugin was uninstalled successfully");
- textRestart = gettext("The plugin was uninstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
- textReload = gettext("The plugin was uninstalled successfully, however a reload of the page is needed for that to take effect.");
-
- titleError = gettext("Something went wrong");
- if (data.hasOwnProperty("reason")) {
- textError = _.sprintf(gettext("Uninstalling the plugin failed: %(reason)s"), {reason: data.reason});
- } else {
- textError = gettext("Uninstalling the plugin failed, please see the log for details.");
- }
-
- } else if (action == "enable") {
- if (data.hasOwnProperty("plugin")) {
- name = data.plugin.name;
- }
-
- titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" enabled"), {name: name});
- textSuccess = gettext("The plugin was enabled successfully.");
- textRestart = gettext("The plugin was enabled successfully, however a restart of OctoPrint is needed for that to take effect.");
- textReload = gettext("The plugin was enabled successfully, however a reload of the page is needed for that to take effect.");
-
- titleError = gettext("Something went wrong");
- if (data.hasOwnProperty("reason")) {
- textError = _.sprintf(gettext("Toggling the plugin failed: %(reason)s"), {reason: data.reason});
- } else {
- textError = gettext("Toggling the plugin failed, please see the log for details.");
- }
-
- } else if (action == "disable") {
- if (data.hasOwnProperty("plugin")) {
- name = data.plugin.name;
- }
-
- titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" disabled"), {name: name});
- textSuccess = gettext("The plugin was disabled successfully.");
- textRestart = gettext("The plugin was disabled successfully, however a restart of OctoPrint is needed for that to take effect.");
- textReload = gettext("The plugin was disabled successfully, however a reload of the page is needed for that to take effect.");
-
- titleError = gettext("Something went wrong");
- if (data.hasOwnProperty("reason")) {
- textError = _.sprintf(gettext("Toggling the plugin failed: %(reason)s"), {reason: data.reason});
- } else {
- textError = gettext("Toggling the plugin failed, please see the log for details.");
- }
-
- } else {
- return;
}
- self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, titleError, textError);
+ self._displayPluginManagementNotification(data, action, name);
self.requestData();
}
};
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
self._preprocessLine = function(line) {
- if (line.stream == "stderr" && line.line.match(self._forcedStdoutLine)) {
+ if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
line.stream = "stdout";
}
return line;
}
}
- // view model class, parameters for constructor, container to bind to
- ADDITIONAL_VIEWMODELS.push([
- PluginManagerViewModel,
- ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel"],
- "#settings_plugin_pluginmanager"
- ]);
+ OCTOPRINT_VIEWMODELS.push({
+ construct: PluginManagerViewModel,
+ dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel", "accessViewModel"],
+ elements: ["#settings_plugin_pluginmanager"]
+ });
});
diff --git a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less
index cd49e51db..b828f87fa 100644
--- a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less
+++ b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less
@@ -23,10 +23,6 @@ table {
}
#settings_plugin_pluginmanager_repositorydialog {
- .slimScrollDiv {
- margin-bottom: 20px;
- }
-
h4 {
position: relative;
@@ -72,23 +68,20 @@ table {
}
#settings_plugin_pluginmanager_repositorydialog_list {
- overflow: hidden;
width: auto;
height: 300px;
+ overflow-x: hidden;
+ overflow-y: scroll;
+ padding-right: 2px;
.entry {
border-bottom: 1px solid #ddd;
padding: 5px;
- padding-right: 10px;
}
}
}
#settings_plugin_pluginmanager_workingdialog_output {
- span {
- display: block;
- }
-
.message {
font-weight: bold;
}
diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2
index 61323ddeb..95e9d9077 100644
--- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2
+++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2
@@ -20,6 +20,13 @@
{% endtrans %}
{% trans %}
+ It looks like OctoPrint has currently no connection to the internet. Due to that it's not possible
+ to install new plugins from the plugin repository or archive URLs.
+{% endtrans %}
+
+ {{ _('Enforce key') }}
+
+ {{ _('If you check this, requests to any of OctoPrint\'s APIs without an API key will be denied instead of handled like an anonymous/not logged in user. This is OctoPrint\'s old default behaviour.') }}
+
+
@@ -14,11 +22,12 @@
- {{ _('API Key') }}
+ {{ _('API Key') }}
-
-
-
+
+
+
+
{{ _('Please note that changes to the API key are applied immediately, without having to "Save" first.') }}
{{ _('G90/G91 overrides relative extruder mode') }} {{ _('Smoothieware') }}
+ {{ _('This is used by the GCODE analysis in the backend and the viewer in the frontend to interpret your sliced files correctly.') }}
-
+
+ {{ _('Terminal Auto Uppercase Blacklist') }}
-
- {{ _('Enable automatic firmware detection') }}
- {% trans %}
- If enabled, OctoPrint will try to figure out your printer's firmware automatically and adjust some communication parameters based on that.
- If that doesn't work out, or you want more granular control, uncheck this and the parameters in question will become visible for you to adjust.
- {% endtrans %}
-
-
+
+ {{ _('Use this to specify the commands that should not have their parameters automatically uppercased in the terminal tab. Just the G or M code, comma separated.') }}