diff --git a/.editorconfig b/.editorconfig index d8d42bbc9..bf65494f2 100644 --- a/.editorconfig +++ b/.editorconfig @@ -11,6 +11,7 @@ trim_trailing_whitespace = true [**.py] indent_style = tab +indent_size = 4 [src/octoprint/static/js/app/**.js] indent_style = space diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE/bug_report.md similarity index 95% rename from .github/ISSUE_TEMPLATE.md rename to .github/ISSUE_TEMPLATE/bug_report.md index c65e40fb2..7ee1a4b4c 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -1,3 +1,9 @@ +--- +name: Bug report +about: Create a report to help improve OctoPrint + +--- + -1. ... -2. ... -3. ... +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.gitignore b/.gitignore index eeaf038e8..856725dd2 100644 --- a/.gitignore +++ b/.gitignore @@ -31,9 +31,12 @@ OctoPrint.egg-info *.codekit venv +venv2 +venv3 venv26 venv27 venv33 venv34 venv35 venv36 +venv37 diff --git a/.travis.yml b/.travis.yml index dd3b081eb..d91ffde6e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,12 +1,22 @@ --- language: python +dist: xenial + +matrix: + include: + - python: '3.7' + env: RUN_FLAKE8=true + python: +- "3.7" +- "3.6" - "2.7" install: - pip install -e .[develop] script: -- nosetests --with-doctest +- test -n "$RUN_FLAKE8" || nosetests --with-doctest +- test -z "$RUN_FLAKE8" || flake8 --ignore=D,E,W,F401 src/ tests setup.py sudo: false git: depth: 250 diff --git a/.versioneer-lookup b/.versioneer-lookup index acbff62a1..1e8c5e63d 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -18,16 +18,16 @@ prerelease HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.3.9 +# maintenance is currently the branch for preparation of maintenance release 1.3.11 # so are any fix/... and improve/... branches -maintenance 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev -fix/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev -improve/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev +maintenance 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev +fix/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev +improve/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev -# staging/maintenance is currently the branch for preparation of 1.3.7rc5 +# staging/maintenance is currently the branch for preparation of 1.3.10rc5 # so is regressionfix/... -staging/maintenance 1.3.7rc5 e5caa3d0bf77ed23f04c1d96ab0fa997d19d2006 pep440-dev -regressionfix/.* 1.3.7rc5 e5caa3d0bf77ed23f04c1d96ab0fa997d19d2006 pep440-dev +staging/maintenance 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b pep440-dev +regressionfix/.* 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b 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 0745d43e0..cde9a5824 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -69,7 +69,7 @@ date of first contribution): * [Philipp Baum](https://github.com/philphilphil) * [Kyle Evans](https://github.com/kevans91) * [Javier Martínez Arrieta](https://github.com/Javierma) - * ["MirceaDan"](https://github.com/ByReaL) + * [Mircea Dan Gheorghe](https://github.com/ByReaL) * [Ovidiu Hossu](https://github.com/MoonshineSG) * [Eyck Jentzsch](https://github.com/eyck) * [Mathias Rangel Wulff](https://github.com/mathiasrw) @@ -91,7 +91,15 @@ date of first contribution): * [Daniele Forsi](https://github.com/dforsi) * [Ganey](https://github.com/ganey) * [Sven Lohrmann](https://github.com/malnvenshorn) + * [Andy Castille](https://github.com/klikini) * [Zachary Nofzinger](https://github.com/ZachNo) + * [Gaston Dombiak](https://github.com/gdombiak) + * [Brad Fisher](https://github.com/bradcfisher) + * [Aldo Hoeben](https://github.com/fieldofview) + * [Henning Groß](https://github.com/hgross) + * [Jubaleth](https://github.com/jubaleth) + * [Matthias Urlichs](https://github.com/smurfix) + * [Daniel Joyce](https://github.com/DanielJoyce) 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 7660f4901..6801292f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,297 @@ # OctoPrint Changelog +## 1.3.10 (2018-12-10) + +### Heads-up for plugin authors regarding the `sarge` dependency + +OctoPrint has updated its `sarge` dependency. The new version 0.1.5 has a small breaking change - the `async` keyword +was renamed to `async_` for compatibility reasons with Python 3.7. This might also affect your plugin if you happen to +use `sarge` somewhere therein. OctoPrint has a workaround for this in place so your plugin will continue to function for +now. However, you should look into updating it to use `async_` instead of `async` if running against OctoPrint 1.3.10+. + +See also [here](https://sarge.readthedocs.io/en/latest/overview.html#id1) for the `sarge` changelog. + +### Improvements + + * [#1504](https://github.com/foosel/OctoPrint/issues/1504) - Added detection of `EMERGENCY_PARSER` firmware capability and if it's present add `M108` to the cancel procedure, to cancel blocking heatups. + * [#2674](https://github.com/foosel/OctoPrint/issues/2674) - Improved error handling when the file OctoPrint is currently printing from becomes unreadable. + * [#2698](https://github.com/foosel/OctoPrint/pull/2698) - Made favicon color match custom theme color. + * [#2717](https://github.com/foosel/OctoPrint/pull/2717) - Various speed ups of the GCODE viewer. + * [#2723](https://github.com/foosel/OctoPrint/pull/2723) - Always allow the file analysis to run, even if the slicer does provide analysis data. Allows plugins implementing the analysis hook to override behaviour in all cases. + * [#2729](https://github.com/foosel/OctoPrint/issues/2729) - Allow additional video formats to appear in the timelapse tab. + * [#2730](https://github.com/foosel/OctoPrint/pull/2730) & [#2739](https://github.com/foosel/OctoPrint/pull/2739) & [#2742](https://github.com/foosel/OctoPrint/pull/2742) - Improved GCODE analysis speed. + * [#2740](https://github.com/foosel/OctoPrint/issues/2740) & [#2859](https://github.com/foosel/OctoPrint/issues/2859) - Make the connection panel reflect the current connection parameters. + * [#2769](https://github.com/foosel/OctoPrint/issues/2769) - Cura Plugin: Improve error handling a profile import fails. + * [#2802](https://github.com/foosel/OctoPrint/pull/2802) - Updated the temperature filters to ignore more sent and received lines belonging to temperature requests/responses that so far weren't covered. + * [#2806](https://github.com/foosel/OctoPrint/pull/2806) - Refactored some unit tests. + * [#2827](https://github.com/foosel/OctoPrint/pull/2827) - Spelling fixes in the documentation. + * [#2839](https://github.com/foosel/OctoPrint/issues/2839) - Recognize position reports that include a space after the axis, as e.g. observed in the firmware of AlfaWise U20 + * [#2854](https://github.com/foosel/OctoPrint/issues/2854) - Auto detect Teacup firmware. + * [#2865](https://github.com/foosel/OctoPrint/pull/2865) - Added `speed` parameter to `extrude` command on the `/api/printer/tool` API endpoint which allows to set the feedrate to use for the extrude per request. + * Improve SD print detection + * Added the Anonymous Usage Tracking Plugin. Tracking will only take place if the plugin is enabled and you’ve decided to opt-in during initial setup (or enabled it manually afterwards, through the corresponding switch in the settings). The tracking data will give insight into how OctoPrint is used, which versions are running and on what kind of hardware OctoPrint gets installed. You can learn about what will get tracked (if you opt-in) on [tracking.octoprint.org](https://tracking.octoprint.org). Please consider helping development by participating in the anonymous usage tracking. + * The OctoPi Support Plugin is now the Pi Support Plugin: + * Always enabled when running on a Raspberry Pi, regardless of whether OctoPi is used or not. + * Now detects undervoltage/overheat issues and displays an alert on the UI if such an issue is found. + * Changed detection method of the Raspberry Pi Model to something a bit more future proof. + * Added the Application Keys Plugin: The new bundled plugin offers an authorization for third party apps that doesn't involve manually copying API keys or using QR codes. Third party client developers are strongly advised to implement this workflow in their apps. Read more [in the documentation](http://docs.octoprint.org/en/maintenance/bundledplugins/appkeys.html). + * Added the Backup & Restore Plugin: The new bundled plugin will allow you to make a backup of your OctoPrint settings, files and list of installed plugins, and to restore from such a backup on the + same or another instance. This should make migration paths from outdated installations to newer ones easier. + * Software Update Plugin: Automatic updates in outdated environments are no longer supported. After repeated issues out in the fields with ancient installations and ancient underlying Python environments, OctoPrint will no longer allow automatic updates of itself or plugins via the Software Update Plugin if a certain set of minimum versions of Python, `pip` and `setuptools` isn't detected. The current minimum versions reflect the environment found on OctoPi 0.14.0: Python 2.7.9, pip 9.0.1, setuptools 5.5.1. See also the [related FAQ entry](https://faq.octoprint.org/unsupported-python-environment). + * OctoPrint will now longer allow itself to be installed on Python versions less than 2.7.3 or higher than 2.7.x, to avoid peope running into issues in unsupported environments. + * Protect/educate against the dangers of opening up OctoPrint on the public internet: + * Detect connections to the UI from external IPs and display a warning in such cases. + * Added explicit warning to the first run wizard. + * Added explicit warning to the documentation. + * Added the ForcedLogin Plugin: Disables anonymous read-only access. To get back the old behaviour you'll have to explicitely disable this plugin. + * Removed printed/visited layer counts from the GCODE viewer since it was confusing people more than helping them. + * Added a warning to the documentation re expensive code in gcode hooks. + * Added the `no_firstrun_access` decorator. + * Only disable autoscroll in the terminal when scrolling up, not when scrolling down. + * Added a new asset type `clientjs` for JS client library components. + * Added new options for the `showConfirmationDialog` UI helper: + * `oncancel`: callback to call when the cancel button is pressed + * `noclose`: don't allow dismissing/closing the dialog without having chosen to proceed or cancel. + * Allow further access restrictions on API and Tornado routes by third party plugins. + * Support using the JS client library with an unset API key. + * Added documentation for `octoprint.util.commandline` module + * More resilience against third party plugins that happily block or kill important startup threads + * Improved backwards compatibility of the `sarge` dependency by monkey patching it to support the old `async` keyword parameter. Plugin authors are still advised to switch to the new `async_` parameter if running against `sarge>=0.1.5`, unmodified plugins should continue to work now however. For reference, OctoPrint 1.3.10 requires `sarge==0.1.5post0`. + * Better detection of ipv6 support by the underlying OS. + * Updated several dependencies to current versions where possible. + * Announcements Plugin: Add documentation. + * Anonymous Usage Tracking: Added elapsed time & reason of print failure to tracking (to be able to distinguish cancelled from errored out prints) + * Anonymous Usage Tracking: Added undervoltage/overheat detection on Pis to tracking (to correlate print failures to power issues, see also [#2878](https://github.com/foosel/OctoPrint/pull/2878)). + * Backup: Exclude `generated`, `logs` and `watched` folders from backup + * Backup: Use base version for version check on restore + * Pi Support plugin: Better wording on the "undervoltage & overheat" popover & added a link to the FAQ entry + * Printer Safety Plugin: Added Ender 3 stock firmware, Micro3D stock firmware and iME firmware to detection + +### Bug fixes + + * [#2629](https://github.com/foosel/OctoPrint/issues/2629) - Cura Plugin: Fixed wrong gcode snippet being used when slicing against a printer profile with multiple extruders. + * [#2696](https://github.com/foosel/OctoPrint/pull/2696) - Fixed a comment. + * [#2697](https://github.com/foosel/OctoPrint/pull/2697) - Fixed documentation regarding unit of `estimatedPrintTime` field in the analysis result. + * [#2705](https://github.com/foosel/OctoPrint/issues/2705) - Fixed internal server error on GET request for files on the printer's SD card. + * [#2706](https://github.com/foosel/OctoPrint/issues/2706) - Fixed a documentation error regarding HTTP status code returned on invalid API key + * [#2712](https://github.com/foosel/OctoPrint/issues/2712) - Fixed updating via commandline (`octoprint plugins softwareupdate:update`). + * [#2749](https://github.com/foosel/OctoPrint/issues/2749) - Fixed empty API key being treated as anonymous API key. + * [#2752](https://github.com/foosel/OctoPrint/issues/2752) - Only reset timeout to shorter "busy" timeout once the busy configuration command has been sent to the printer. + * [#2772](https://github.com/foosel/OctoPrint/issues/2772) & [#2764](https://github.com/foosel/OctoPrint/issues/2764) - Stop sending commands to the printer if a fatal error is reported that results in a `kill()`, even if OctoPrint is configured to keep the connection going on firmware errors. + * [#2774](https://github.com/foosel/OctoPrint/issues/2774) - Fixed autoscroll in the terminal stopping when switching browser windows or tabs. + * [#2780](https://github.com/foosel/OctoPrint/issues/2780) - Fixed error when trying to save timeout settings. + * [#2800](https://github.com/foosel/OctoPrint/pull/2800) - Fixed a conjugation error in the documentation. + * [#2805](https://github.com/foosel/OctoPrint/issues/2805) - Fixed duplicated method name in a unit test. + * [#2846](https://github.com/foosel/OctoPrint/issues/2846) - Removed requirement to have `messages.pot` exist to use `babel_extract` for translating plugins (see also [#2846](https://github.com/foosel/OctoPrint/pull/2847)). + * [#2850](https://github.com/foosel/OctoPrint/issues/2850) - Fixed a race condition in the web socket causing the push connection to fail (see also [#2858](https://github.com/foosel/OctoPrint/pull/2858)). + * [#2852](https://github.com/foosel/OctoPrint/issues/2852) - Fixed issue with zeroconf announcement failing for the second instance of OctoPrint on the same Linux host due to a name conflict. + * [#2872](https://github.com/foosel/OctoPrint/issues/2872) (regression) - Fix Timeout when connecting to printer that doesn't send `start` on connect + * [#2873](https://github.com/foosel/OctoPrint/issues/2873) (regression) - Fix GCODE viewer no longer being able to load files. + * [#2876](https://github.com/foosel/OctoPrint/issues/2876) (regression) - Fix semi functional UI when access control is disabled + * [#2879](https://github.com/foosel/OctoPrint/issues/2879) (regression) - Fix favicon in Firefox + * [#2897](https://github.com/foosel/OctoPrint/issues/2897) (regression) - Improved error resilience of `is_lan_address` so an error during its execution no longer nukes requests + * [#2898](https://github.com/foosel/OctoPrint/issues/2898) (regression) - ForceLogin plugin no longer interferes with websocket messages sent by plugins right on UI load but instead puts them into a (limited) backlog and then sends them out in received order once the user has authenticated on the socket. + * [#2903](https://github.com/foosel/OctoPrint/issues/2903) - Backup plugin: Support for ZIP64 extensions for large zip files + * [#2903](https://github.com/foosel/OctoPrint/issues/2903) - Backup plugin: Better error reporting + * [#2908](https://github.com/foosel/OctoPrint/issues/2908) (regression) - Tracking: Use the file's `path` instead of just the `name` for file name hashing. + * [#2920](https://github.com/foosel/OctoPrint/issues/2920) - Backup plugin: Fix wrong compatibility check logic in plugin install during restore + * Fixed an issue with collision free SD name detection. + * Fixed some JS warnings in the GCODE viewer. + * Fixed wrongly used `.error` instead of the correct `.fail` in the UI's logout handler. + * Fixed the `disable_hotends` snippet in case of a shared nozzle setup. + * Logout socket on UI logout + * Announcements Plugin: Fix an issue with atom feeds. + * Anonymous Usage Tracking: More error resilience for the wizard to possibly work around issues observed with the first RC (for which sadly no information was provided to reproduce and analyse). + * Anonymous Usage Tracking: Fixed homepage link in plugin manager + * Backup: Disable restore on Windows servers where it's not supported thanks to the Windows file system + * Backup: Fix reporting of restore failure due to version mismatch or other cases of an invalid backup + * Backup: Fix feedback in UI during restore, start feedback right on upload of backup + * Printer Safety: Fix localization of warning message + * Software Update Plugin: Fixed the update button being visible although the update is impossible. + * Software Update Plugin: More resilience against invalid data in config + * Software Update Plugin: Fixed version output of CLI update message + +### Special thanks to all the contributors! + +Special thanks to everyone who contributed to this release candidate, especially [@BillyBlaze](https://github.com/BillyBlaze), +[@bradcfisher](https://github.com/bradcfisher), [@eyal0](https://github.com/eyal0), [@fieldOfView](https://github.com/fieldOfView), +[@gdombiak](https://github.com/gdombiak), [@gerfderp](https://github.com/gerfderp), [@hashashin](https://github.com/hashashin) +and [@tedder](https://github.com/tedder) for their PRs. + +### More information + + * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.9...1.3.10) + * Release Candidates: + * [1.3.10rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.10rc1) + * [1.3.10rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.10rc2) + * [1.3.10rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.10rc3) + * [1.3.10rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.10rc4) + * A big **Thank you!** to everyone who reported back on these release candidates this time: [@andrivet](https://github.com/andrivet), [@arminth](https://github.com/arminth), [@autonumous](https://github.com/autonumous), [@benlye](https://github.com/benlye), [@BillyBlaze](https://github.com/BillyBlaze), [@bradcfisher](https://github.com/bradcfisher), [@Charly333](https://github.com/Charly333), [@ChrisHeerschap](https://github.com/ChrisHeerschap), [@Crowlord](https://github.com/Crowlord), [@ctgreybeard](https://github.com/ctgreybeard), [@devildant](https://github.com/devildant), [@dimkin-eu](https://github.com/dimkin-eu), [@DominikPalo](https://github.com/DominikPalo), [@duncanlovett](https://github.com/duncanlovett), [@EddyMI3d](https://github.com/EddyMI3d), [@FanDjango](https://github.com/FanDjango), [@FormerLurker](https://github.com/FormerLurker), [@gdombiak](https://github.com/gdombiak), [@GhostlyCrowd](https://github.com/GhostlyCrowd), [@goeland86](https://github.com/goeland86), [@Goodeid](https://github.com/Goodeid), [@hamster65](https://github.com/hamster65), [@hashashin](https://github.com/hashashin), [@jenilliii](https://github.com/jenilliii), [@JohnOCFII](https://github.com/JohnOCFII), [@kmanley57](https://github.com/kmanley57), [@louispires](https://github.com/louispires), [@markuskruse](https://github.com/markuskruse), [@Nervemanna](https://github.com/Nervemanna), [@nionio6915](https://github.com/nionio6915), [@ntoff](https://github.com/ntoff), [@paukstelis](https://github.com/paukstelis), [@racenviper](https://github.com/racenviper), [@ramsesiden](https://github.com/ramsesiden), [@rtbon](https://github.com/rtbon), [@skohls](https://github.com/skohls), [@stough](https://github.com/stough), [@tech-rat](https://github.com/tech-rat), [@tedder](https://github.com/tedder), [@ThaliaFromPrussia](https://github.com/ThaliaFromPrussia), [@thisiskeithb](https://github.com/thisiskeithb), [@trendelkamp](https://github.com/trendelkamp), [@truglodite](https://github.com/truglodite), [@tteckenburg](https://github.com/tteckenburg), [@varazir](https://github.com/varazir), [@Webstas](https://github.com/Webstas) and [@zeroflow](https://github.com/zeroflow) + +## 1.3.9 (2018-07-25) + +### Still running OctoPrint 1.3.6? Heads-up! + +OctoPrint 1.3.9 includes a couple of dependency updates whose update during switch to 1.3.9 are known to trigger an "update failed" message within OctoPrint's update dialog: + +``` + +[...] +OSError: [Errno 2] No such file or directory: '/home/pi/oprint/local/lib/python2.7/site-packages/python_dateutil-2.6.0-py2.7.egg' +Successfully installed OctoPrint-1.3.9rc4 backports-abc-0.5 frozendict-1.2 markdown-2.6.11 pkginfo-1.4.2 pyserial-3.4 python-dateutil-2.6.1 singledispatch-3.4.0.3 tornado-4.5.3 +The update did not finish successfully. Please consult the log for details. + +``` + +The update did in fact succeed and the issue lies with a change in the underlying update mechanism concerning the dependencies. This problem has been fixed in 1.3.7/1.3.8 and versions prior to 1.3.6 aren't yet affected, so there you won't ever see this message there. If you are still running 1.3.6 though and updating from it, **simply run the update a second time through Settings > Software Update > Check for updates and clicking "Update now" in the reshown update notification**. + +### Running NGINX as reverse proxy? Be sure to configure HTTP protocol version 1.1! + +OctoPrint 1.3.9 updates the internal webserver Tornado from 4.0.2 to 4.5.3. Among many many fixes and improvements this also includes a change (actually a fix) in the websocket implementation that requires you to tell your NGINX to use HTTP 1.1 instead of the default 1.0 to talk to OctoPrint. You can do this by simply adding + +``` +proxy_http_version 1.1; +``` + +to the `location` config. The [configuration examples](https://discourse.octoprint.org/t/reverse-proxy-configuration-examples/1107) have been adjusted accordingly. See also [#2526](https://github.com/foosel/OctoPrint/issues/2526). + +### Disabled IPv6 and now there are issues with the server after the update? Bind to IPv4 addresses only! + +Starting with this release OctoPrint natively supports IPv6 and will attempt to bind to such addresses if it detects support in the underlying OS. If for whatever reason your OS doesn't support IPv6 even though Python's `socket` says otherwise, you can tell OctoPrint to bind to an IPv4 address only either via the `--host` command line parameter or `server.host` in `config.yaml`. Use `127.0.0.1` for localhost only, `0.0.0.0` for all IPv4 addresses or whatever specific IPv4 address you want to bind to. + +### Plugin author and still dependent on the legacy plugin bundling flag? Fix your plugin! + +As [announced with the release of OctoPrint 1.3.6](https://octoprint.org/blog/2017/12/12/new-release-1.3.6/), the legacy plugin bundling flag has now been removed again. [Make sure to check and if necessary fix your plugins](https://octoprint.org/blog/2017/12/01/heads-up-plugin-authors/) if you haven't done that so far! + +### Improvements + + * [#652](https://github.com/foosel/OctoPrint/issues/652) & [#1545](https://github.com/foosel/OctoPrint/issues/1545) - Added name of user who started a job to job info (see also [#2576](https://github.com/foosel/OctoPrint/pull/2576)). + * [#1203](https://github.com/foosel/OctoPrint/issues/1203) & [#1905](https://github.com/foosel/OctoPrint/issues/1905) & [#1797](https://github.com/foosel/OctoPrint/issues/1797) & [#2514](https://github.com/foosel/OctoPrint/issues/2514) - Added support for plugins to override GCODE analysis provider and live print time estimation with their own implementations through two new hooks [`octoprint.filemanager.analysis.factory`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-filemanager-analysis-factory) and [`octoprint.printer.estimation.factory`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-printer-estimation-factory). + * [#1217](https://github.com/foosel/OctoPrint/issues/1217) - Software Update Plugin: Block the UI in general when an update is in progress (even in browser windows that didn't start it and logged in as user) so that no prints can be accidentally started during that. + * [#1513](https://github.com/foosel/OctoPrint/issues/1513) - Option to allow sending `M0`/`M1` to the printer instead of swallowing it. + * [#2318](https://github.com/foosel/OctoPrint/issues/2318) - Gcode Viewer: Visualize "current" print head location with a marker. + * [#2351](https://github.com/foosel/OctoPrint/issues/2351) - Support for binding to IPv6 addresses. OctoPrint will now default to binding to `::` if IPv6 support is detected, and to `0.0.0.0` if not. Both the intermediary server and Tornado are instructed to bind their sockets to both IP versions. Positive IPv6 support detection relies on + * `socket.has_ipv6` being `True` + * `socket.IPPROTO_IPV6` and `socket.IPV6_V6ONLY` being available (or redefined in case of Windows) in order to ensure dual stack binding for the intermediary server) + * [#2379](https://github.com/foosel/OctoPrint/issues/2379) - File and plugin list now use the browser's native scrollbar instead of slimscroll. Slimscroll is still bundled though, in case third party plugins might depend on it. + * [#2487](https://github.com/foosel/OctoPrint/issues/2487) - Improved documentation of system command configuration (see also [#2498](https://github.com/foosel/OctoPrint/pull/2498)). + * [#2495](https://github.com/foosel/OctoPrint/pull/2495) - Removed unneeded filter from a template. + * [#2498](https://github.com/foosel/OctoPrint/pull/2498) - Improved documentation of the `async` flags of custom system commands. + * [#2512](https://github.com/foosel/OctoPrint/issues/2512) - Log files will now contain client IP as provided by first entry in X-Forwarded-For header (or more if `server.reverseProxy.trustDownstream` is configured accordingly). + * [#2518](https://github.com/foosel/OctoPrint/issues/2518) - Display absolute file upload date and time on hover (see also [#2630](https://github.com/foosel/OctoPrint/pull/2630)). + * [#2522](https://github.com/foosel/OctoPrint/issues/2522) - Perform logging to disk asynchronously to avoid slow downs caused by it. + * [#2541](https://github.com/foosel/OctoPrint/pull/2541) - Added link to instructions to reset passwords. Part of solving [#1239](https://github.com/foosel/OctoPrint/issues/1239). + * [#2543](https://github.com/foosel/OctoPrint/pull/2543) - Added `--no-cache-dir` to pip calls to work around `MemoryErrors`. See also [#2535](https://github.com/foosel/OctoPrint/pull/2535) and [pypa/pip#2984](https://github.com/pypa/pip/issues/2984) for more details. + * [#2558](https://github.com/foosel/OctoPrint/issues/2558) - Have the watched folder processor ignore hidden files. + * [#2572](https://github.com/foosel/OctoPrint/issues/2572) - More error resilience in `ItemListHelper` against empty child elements. + * [#2573](https://github.com/foosel/OctoPrint/pull/2573) - Added `M118` to commands to never automatically upper case. + * [#2583](https://github.com/foosel/OctoPrint/issues/2583) - Handle scripts that are part of a job like other lines coming from a job and thus allow them to be kept back using `job_on_hold`. + * [#2597](https://github.com/foosel/OctoPrint/issues/2597) - Disabled animation on cancel print confirmation. + * [#2463](https://github.com/foosel/OctoPrint/issues/2463) - Added documentation for `printingarea` and `dimensions` in `gcodeAnalysis` data model (see also [#2540](https://github.com/foosel/OctoPrint/pull/2540)). + * [#2615](https://github.com/foosel/OctoPrint/issues/2615) - Allowed more granular control over components to be upgraded through the software update plugin in its settings dialog. + * [#2620](https://github.com/foosel/OctoPrint/pull/2620) - Save `ItemListHelper` page sizes to local storage. + * [#2642](https://github.com/foosel/OctoPrint/pull/2642) - Added methods for adding and updating items to `ItemListHelper`. + * [#2644](https://github.com/foosel/OctoPrint/issues/2644) - Detect broken symlinks in configured folders on startup (see also further below). + * [#2648](https://github.com/foosel/OctoPrint/pull/2648) - Allowed class methods as callbacks in view models. + * A new API endpoint [`/api/settings/templates`](http://docs.octoprint.org/en/maintenance/api/settings.html#fetch-template-data) allows (admin only) access to information regarding the loaded templates and their order in the UI. That should allow plugins wishing to offer modification of ordering of tabs, sidebar components and so on to retrieve the data they need for that. + * Have the watched folder processor handle vanished files gracefully. + * Removed [`legacyPluginAssets` flag](https://octoprint.org/blog/2017/12/01/heads-up-plugin-authors/). + * Improved requirement detection in `octoprint_setuptools`, added unit tests for that. + * Bundled `sockjs-tornado` dependency. It hasn't been updated by the author in a while although there exist a number of issues plus patches for them, so we now vendor it. + * Disabled position logging on cancel by default. If you need this, please explicitly enable it, it is causing too many issues in the field with misbehaving firmware. + * Extended URL test API to allow whitelist/blacklist check for the returned content type, used that to verify that the webcam snapshot URL actually returns images. + * Added timeout for position logging on pause/cancel. This should work around firmware which doesn't provide a proper `M114` resport that might be unparseable so we won't get stuck in those cases. + * Migrated file storage metadata to json instead of YAML since it performs way way better. + * Added `missing linenumber` to recognized non-fatal error messages. + * Got rid of some Python 2 only code. + * Added sanity checks for configured folders (see also [#2644](https://github.com/foosel/OctoPrint/issues/2644)): + * on startup: check they are writable, if not revert to defaults + * on settings save: check they are writable, if not return an HTTP 400 + * in the settings dialog: allow quick check of writability via test buttons + * Never send referrers with links + * Confirmation dialog helper now supports an HTML body. + * Sort serial ports naturally (e.g. `tty1`, `tty2`, ..., `tty10` instead of `tty1`, `tty10`, ...) + * Added `paused` and `resumed` action commands, [see here for details](http://docs.octoprint.org/en/maintenance/features/action_commands.html). + * Added two new hooks for firmware information, [`octoprint.comm.firmware.info`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-firmware-info) and [`octoprint.comm.firmware.capabilities`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-firmware-capabilities). + * Added view model list to `OctoPrint.coreui` UI module. + * Improved logging of `FatalStartupError`s. + * Add sanity check for disabled plugin list (see also [#2687 (comment)](https://github.com/foosel/OctoPrint/issues/2687#issuecomment-399797596)). + * Improve logging of exceptions triggered inside the state update worker (see also [#2715](https://github.com/foosel/OctoPrint/issues/2715)). + * Workaround for a potential `pip` issue when updating components through the Software Update plugin. + * Fix resend and timeout handling during an active `job_on_hold`. + * Updated some dependencies: + * Tornado to 4.5. Version 5 sadly has issues with web socket handling when access behind `haproxy`. So far no solution has been found, so we stay at 4.5 for now. + * jQuery to 3.3.1 + * Several other Python dependencies + * Announcement Plugin: Don't reload all notifications if one is marked as read. + * Printer Safety Plugin: Added new detected firmwares: + * Anycubic Mega + * Malyan M200 + * CR-10S + * all Repetier firmware versions prior to 0.92 + * any firmware that reports the `THERMAL_PROTECTION` capability as disabled to thermal protection warning (see also [MarlinFirmware/Marlin#10465](https://github.com/MarlinFirmware/Marlin/pull/10465)) + * Software Update Plugin: Default to `force_base = False` for version checks. + * Virtual Printer Plugin: Allow defining custom `M114` response formats. + +### Bug fixes + + * [#2333](https://github.com/foosel/OctoPrint/issues/2333) (Part 3/3) - Updated to PySerial 3.4 and utilize read and write cancelling to work around disconnect delays. + * [#2355](https://github.com/foosel/OctoPrint/issues/2355) - Fixed non deterministic sorting of files with missing fields (e.g. date for SD card files) in OctoPrint's frontend. + * [#2496](https://github.com/foosel/OctoPrint/issues/2496) - Fixed files API not allowing to walk through the directory tree unless fetching the full listing recursively by making sure that first level children nodes are always provided. + * [#2502](https://github.com/foosel/OctoPrint/pull/2502) - Fixed some invalid HTML + * [#2504](https://github.com/foosel/OctoPrint/pull/2504) & [#2532](https://github.com/foosel/OctoPrint/pull/2532) & [#2552](https://github.com/foosel/OctoPrint/pull/2552) - Fixed various typos + * [#2505](https://github.com/foosel/OctoPrint/issues/2505) - Fixed user switch to `_api` user on use of the global API key inside the browser. + * [#2509](https://github.com/foosel/OctoPrint/issues/2509) - Properly handle a printer reset while printing and don't get stuck in "Cancelling" state + * [#2517](https://github.com/foosel/OctoPrint/issues/2517) - Fixed baudrate negotiation with printers that need a bit of a delay between connection establishment and probing (e.g. Prusa MK3). + * [#2520](https://github.com/foosel/OctoPrint/issues/2520) - Fixed temperature presets being saved as strings instead of numbers. + * [#2533](https://github.com/foosel/OctoPrint/pull/2533) - Fixed API key copy button being enabled and generate button being disabled when no API key is set. + * [#2534](https://github.com/foosel/OctoPrint/issues/2534) - Fixed stale data in API key/user editor. See also [#2604](https://github.com/foosel/OctoPrint/pull/2604). + * [#2539](https://github.com/foosel/OctoPrint/issues/2539) - Made serial and baud rate lists consistent between connection panel and settings (see also [#2606](https://github.com/foosel/OctoPrint/pull/2606)). + * [#2547](https://github.com/foosel/OctoPrint/issues/2547) - Fixed `PrintFailed` being triggered in case of an error while processing the `afterPrintJobDone` GCODE script through introduction of `Resuming` and `Finishing` states. + * [#2549](https://github.com/foosel/OctoPrint/issues/2549) - Fixed "uninstall plugin" icon in Plugin Manager staying clickable even if disabled. + * [#2549](https://github.com/foosel/OctoPrint/issues/2549) - Fixed issue with detection uninstallation of disabled plugins (see also [#2650](https://github.com/foosel/OctoPrint/pull/2650)). + * [#2551](https://github.com/foosel/OctoPrint/issues/2551) - Fixed `0` being allowed for various intervals and timeouts where that values doesn't make sense. + * [#2554](https://github.com/foosel/OctoPrint/pull/2554) - Fixed a JSON example in the docs. + * [#2568](https://github.com/foosel/OctoPrint/pull/2568) - Fixed a dead link in the plugin hooks documentation in the docs. + * [#2579](https://github.com/foosel/OctoPrint/issues/2579) - Fixed print time left of "a couple of seconds" even after the print job has finished. + * [#2581](https://github.com/foosel/OctoPrint/issues/2581) & [#2587](https://github.com/foosel/OctoPrint/issues/2587) - Fixed OctoPrint getting stuck in "Pausing" or "Cancelling" state due to a race condition. + * [#2589](https://github.com/foosel/OctoPrint/issues/2589) - Added missing `typePath` field on API response for files on the printer's SD card. + * [#2591](https://github.com/foosel/OctoPrint/pull/2591) - Fixed markup of some HTML labels. + * [#2595](https://github.com/foosel/OctoPrint/pull/2595) - Fixed some UI appearance issues. + * [#2601](https://github.com/foosel/OctoPrint/issues/2601) - Properly handle relative paths for selection via `printer.select_file`. + * [#2621](https://github.com/foosel/OctoPrint/issues/2621) - Fixed framerate not being read from config for rendering unrendered timelapses. + * [#2625](https://github.com/foosel/OctoPrint/issues/2625) - Fixed incompatibility of OctoPrint's plugin subsystem with Python wheels, which are the default mode of installing plugins from pip version 10.0.0 onward. + * [#2632](https://github.com/foosel/OctoPrint/issues/2632) - Fixed race condition in resend handling on missing `ok`s. + * [#2675](https://github.com/foosel/OctoPrint/issues/2675) - Fixed a possible division by zero on SD upload. + * [#2677](https://github.com/foosel/OctoPrint/issues/2677) (regression) - Fix a deadlock when `job_on_hold` is utilized (causing issues at least with Octolapse) + * [#2683](https://github.com/foosel/OctoPrint/pull/2683) - Fixed two missing spaces in the german translation. + * [#2715](https://github.com/foosel/OctoPrint/issues/2715) (regression) - Fix broken estimator initialization on SD print start and resulting crash of the state update worker. + * [#2719](https://github.com/foosel/OctoPrint/issues/2719) (regression) - Fix live print time estimation + * [#2737](https://github.com/foosel/OctoPrint/issues/2737) (regression) - Fix print button being enabled even though no file is selected. + * [#2738](https://github.com/foosel/OctoPrint/issues/2738) (regression) - Limit the use of the `--no-cache-dir` argument added to `pip` calls to such versions of `pip` that already support it (anything newer than 1.5.6). + * Properly handle absolute paths for recovery data comparison. + * Fixed snapshot test button not resetting on error. + * Fixed decoupling of metadata logs in the file manager. + * Fixed "remember me" and IPv4/IPv6 sessions. This might also solve [#1881](https://github.com/foosel/OctoPrint/issues/1881). + * Removed Repetier resend repetition detection and handling code. It was buggy and introducing issues. + * Fixed script order: `beforePrint*` should always precede any commands from the print job. + * Only perform write tests on directories where necessary. Especially avoid them on page rendition to prevent misconfigured folders from triggering an HTTP 500. (regression) + +### Special thanks to all the contributors! + +Special thanks to everyone who contributed to this release, especially [@benlye](https://github.com/benlye), [@dadosch](https://github.com/dadosch), [@dforsi](https://github.com/dforsi), [@ganey](https://github.com/ganey),[@malnvenshorn](https://github.com/malnvenshorn), [@ntoff](https://github.com/ntoff), [@tedder](https://github.com/tedder) and [@vitormhenrique](https://github.com/vitormhenrique) for their PRs. + +### More information + + * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.8...1.3.9) + * Release Candidates: + * [1.3.9rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.9rc1) + * [1.3.9rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.9rc2) + * [1.3.9rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.9rc3) + * [1.3.9rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.9rc4) + * A big **Thank you!** to everyone who reported back on these release candidates this time: + [arhi](https://github.com/arhi), [b-morgan](https://github.com/b-morgan), [brandstaetter](https://github.com/brandstaetter), [buchnoun](https://github.com/buchnoun), [CapnBry](https://github.com/CapnBry), [chatrat12](https://github.com/chatrat12), [ChrisHeerschap](https://github.com/ChrisHeerschap), [christianlupus](https://github.com/christianlupus), [chrisWhyTea](https://github.com/chrisWhyTea), [Crowlord](https://github.com/Crowlord), [ctgreybeard](https://github.com/ctgreybeard), [Cyberwizzard](https://github.com/Cyberwizzard), [DrJuJu](https://github.com/DrJuJu), [ejjenkins](https://github.com/ejjenkins), [fieldOfView](https://github.com/fieldOfView), [FormerLurker](https://github.com/FormerLurker), [four-of-four](https://github.com/four-of-four), [Galfinite](https://github.com/Galfinite), [gege2b](https://github.com/gege2b), [HFMan](https://github.com/HFMan), [jjlink](https://github.com/jjlink), [jneilliii](https://github.com/jneilliii), [JohnOCFII](https://github.com/JohnOCFII), [jwg3](https://github.com/jwg3), [kazibole](https://github.com/kazibole), [larp-welt](https://github.com/larp-welt), [McFly99](https://github.com/McFly99), [mod38](https://github.com/mod38), [ntoff](https://github.com/ntoff), [OutsourcedGuru](https://github.com/OutsourcedGuru), [paukstelis](https://github.com/paukstelis), [pingywon](https://github.com/pingywon), [pscrespo](https://github.com/pscrespo), [Rapsey](https://github.com/Rapsey), [tech-rat](https://github.com/tech-rat), [tedder](https://github.com/tedder), [thess](https://github.com/thess), [Thisismydigitalself](https://github.com/Thisismydigitalself), [tibmeister](https://github.com/tibmeister) + ## 1.3.8 (2018-04-13) ### Bug fixes @@ -263,7 +555,7 @@ You can find out more about the change, how to know if a plugin is even affected * 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. + * Add `octoprint.access.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. @@ -728,1019 +1020,6 @@ If you are running OctoPi, this does **not** apply to you and you do not need to * [1.3.0rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.0rc2) * [1.3.0rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.0rc3) -## 1.2.18 (2016-11-30) +--- -### Improvements - - * Allow arbitrary frame rates for creating timelapses. Before, the entered fps value was also directly used as frame rate for the actual video, which could cause problems with any frame rates not specified in the MPEG2 standard. Now OctoPrint will use a standard frame rate for the rendered video and render the timelapse stills into the finished movie with the configured frame rate. - * Limited Cura profile importer to `.ini` files and clarified the supported versions - * Add support for the `R` parameter for `M109` and `M190` - -### Bug fixes - - * [#1541](https://github.com/foosel/OctoPrint/issues/1541) - Fix selecting the printer profile to use by default - * [#1543](https://github.com/foosel/OctoPrint/issues/1543) - Fix target temperature propagation from communication layer - * [#1567](https://github.com/foosel/OctoPrint/issues/1567) - Fix issue with restricted settings getting parsed to the wrong data structure in the frontend if loaded anonymously first. - * [#1571](https://github.com/foosel/OctoPrint/issues/1571) - Fix parsing of port number from HTTP Host header for IPv6 addresses - * Fix issue with settings restriction causing internal settings defaults to be changed. - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.2.17...1.2.18) - * Release Candidates: - * [1.2.18rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.18rc1) - -## 1.2.17 (2016-11-08) - -### Improvements - - * Files like `config.yaml` etc will now persist their permissions, with a lower and upper permission bounds for sanitization (e.g. removing executable flags on configuration files but keeping group read/write permissions if found). - * Log full stack trace on socket connection errors when debug logging for `octoprint.server.util.sockjs` is enabled - * ``SettingsPlugin``s may now mark configuration paths as restricted so that they are not returned on the REST API - * Updated LESS.js version - * Improved the `serial.log` logging handler to roll over serial log on new connections to the printer instead of continuously appending to the same file. Please note that `serial.log` is a debugging tool only and should *not* be left enabled unless you are trying to troubleshoot something in your printer communication. - * Split JS/CSS/LESS asset bundles according into asset bundles for core + bundled plugins ("packed_core.{js|css|less}") and third party plugins ("packed_plugins.{js|css|less}"). That will allow the core UI to still function properly even if an installed third party plugin produces invalid JS and therefore causes a parser error for the whole plugin JS file. See [#1544](https://github.com/foosel/OctoPrint/issues/1544) for an example of such a situation. - -### Bug fixes - - * [#1531](https://github.com/foosel/OctoPrint/issues/1531) - Fixed encoding bug in HTTP request processing triggered by content type headers on form data fields - * Fixed forced `config.yaml` save on startup caused by mistakenly assuming that printer parameters were always migrated. - * Fixed issue causing ``remember_me`` cookie not to be deleted properly on logout - * Fixed broken filter toggling on ``ItemListHelper`` class used for various lists throughout the web interface - * Fixed an issue with the preliminary page never reporting that the server is now up if the page generated during preliminary caching had no cache headers set (e.g. because it contained the first run setup wizard) - * Fixed a bug causing the update of OctoPrint to not work under certain circumstances: If 1.2.16 was installed and the settings were *never* saved via the "Settings" dialog's "Save", the update of OctoPrint would fail due to a `KeyError` in the updater. Reason is a renamed property, properly switched to when saving the settings. - * Fixed the logging subsystem to properly clean up after itself. - * Fixed a wrong order in loading JS files on the client introduced in 1.2.17rc2 to make the UI more resilient against broken plugin JS. - * Properly handle empty JS file list from plugins. Solves a 500 on OctoPrint instances without any third party plugins installed generated during web asset bundling introduced in 1.2.17rc2. - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.2.17) - * Release Candidates: - * [1.2.17rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc1) - * [1.2.17rc2](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc2) - * [1.2.17rc3](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc3) - * [1.2.17rc4](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc4) - -## 1.2.16 (2016-09-23) - -### Improvements - - * [#1434](https://github.com/foosel/OctoPrint/issues/1434): Make sure to sanitize any file names in the upload folder that do not match OctoPrint's file name "sanitization standard" automatically when creating a file listing. This should solve issues with UI functionality like selecting a file for printing or deleting a file to not work with files that were uploaded manually to the ``uploads`` folder. As a side note: Please don't do this, use the ``watched`` folder if you want to SCP/FTP/copy files directly to OctoPrint. - * [#1434](https://github.com/foosel/OctoPrint/issues/1434): Allow `[` and `]` in uploaded file names. - * [#1481](https://github.com/foosel/OctoPrint/issues/1481): Bring back non-fuzzy layer time estimates in the GCODE viewer. - * Improved fuzzy print time displays in the frontend. Rounding now takes overall duration into account - durations over a day will be rounded up/down to half days, durations over an hour will be rounded up/down to half hours, durations over 30min will be rounded to 10min segments, durations below 30min will be rounded up or down to the next minute depending on the seconds and finally if we are talking about less than a minute, durations over 30s will return "less than a minute", durations under 30s will return "a couple of seconds". - * Improved intermediary loading page: Don't report server as ready and reload until preliminary caching has been done, IF preliminary caching will be done. - * Added release channels to OctoPrint's bundled Software Update plugin. You will now be able to subscribe to OctoPrint's `maintenance` or `devel` release candidates in addition to stable versions. [Read more about Release Channels on the wiki](https://github.com/foosel/OctoPrint/wiki/Using-Release-Channels). - * Return a "400 Bad Request" instead of a "500 Internal Server Error" if a `multipart/form-data` request (e.g. a file upload) is sent which lacks the `boundary` field. - -### Bug Fixes - - * [#1448](https://github.com/foosel/OctoPrint/issues/1448): Don't "eat" first line of the pause script after a pause triggering `M0` but send it to the printer instead - * [#1477](https://github.com/foosel/OctoPrint/issues/1477): Only report files enqueued for analysis which actually are (as in, don't claim to have queued STL files for GCODE analysis) - * [#1478](https://github.com/foosel/OctoPrint/issues/1478): Don't display inaccurate linear estimate ("6 days remaining") until 30 *minutes* have passed, even if nothing else is available. Potentially related to [#1428](https://github.com/foosel/OctoPrint/issues/1428). - * [#1479](https://github.com/foosel/OctoPrint/issues/1479): Make sure set cookies are post fixed with a port specific suffix and that the path they are set on takes the script root from the request into account. - * [#1483](https://github.com/foosel/OctoPrint/issues/1483): Filenames in file uploads may also now be encoded in ISO-8859-1, as defined in [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2.4). Solves an issue when sending files with non-ASCII-characters in the file name from Slic3r. - * [#1491](https://github.com/foosel/OctoPrint/issues/1491): Fixed generate/delete API key in the user settings - * [#1492](https://github.com/foosel/OctoPrint/issues/1492): Fixed a bug in the software update plugin depending on the presence of the ``prerelease`` flag which is only present when added manually or using a non stable release channel. - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.2.15...1.2.16) - * Release Candidates: - * [1.2.16rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.16rc1) - * [1.2.16rc2](https://github.com/foosel/OctoPrint/releases/tag/1.2.16rc2) - -## 1.2.15 (2016-07-30) - -### Improvements - - * [#1425](https://github.com/foosel/OctoPrint/issues/1425) - Added a compatibility work around for plugins implementing the [`octoprint.comm.transport.serial_factory` hook](http://docs.octoprint.org/en/master/plugins/hooks.html#octoprint-comm-transport-serial-factory) but whose handler's `write` method did not return the number of written bytes (e.g. [GPX plugin including v2.5.2](http://plugins.octoprint.org/plugins/gpx/), [M33 Fio plugin including v1.2](http://plugins.octoprint.org/plugins/m33fio/)). - -### Bug Fixes - - * [#1423](https://github.com/foosel/OctoPrint/issues/1423) - Fixed an issue with certain printers dropping or garbling communication when setting the read timeout of the serial line. Removed the dynamic timeout setting introduced by [#1409](https://github.com/foosel/OctoPrint/issues/1409) to solve this. - * [#1425](https://github.com/foosel/OctoPrint/issues/1425) - Fixed an error when trying to close a printer connection that had not yet been opened and was `None` - * Fixed "Last Modified" header calculation for views where only one source file was present - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.14...1.2.15)) - -## 1.2.14 (2016-07-28) - -### Improvements - - * [#935](https://github.com/foosel/OctoPrint/issues/935) - Support alternative source file types and target extensions in [SlicerPlugins](http://docs.octoprint.org/en/master/plugins/mixins.html#slicerplugin). - * [#1393](https://github.com/foosel/OctoPrint/issues/1393) - Added dedicated sub commands on the job API to pause and resume a print job (instead of only offering a toggle option). - * Better "upload error" message with a list of supported extensions (instead of hardcoded ones) - * Use fuzzy times for print time estimation from GCODE analysis - * Allow M23 "File opened" response with no filename (RepRapPro) - * Allow intermediary startup page to forward query parameters and fragments from initial call to actual web frontend - * More error resilience when rendering templates (e.g. from plugins) - * Make sure that all bytes of a line to send to the printer have actually been sent - * "Tickle" printer when encountering a communication timeout while idle - * Report `CLOSED`/`CLOSED_WITH_ERROR` states as "Offline" in frontend for more consistency with startup `NONE` state which already was reported as "Offline" - * Another attempt at a saner print time estimation: Force linear (way less accurate) estimate if calculation of more accurate version takes too long, sanity check calculated estimate and use linear estimate if it looks wrong, improved threshold values for calculation. Read [the second half of this post on the mailing list](https://groups.google.com/forum/#!msg/octoprint/WWpm1FCUkAs/X3HomTM5DgAJ) on why accurate print time estimation is so difficult to achieve. - * Display print job progress percentage on progress bar. - * Added an indicator for print time left prediction accuracy and explanation of its origin as tooltip. - * Improved visual distinction of "State" sidebar panel info clusters. - -### Bug Fixes - - * [#1385](https://github.com/foosel/OctoPrint/issues/1385) - Send all non-protocol messages from printer to clients. - * [#1388](https://github.com/foosel/OctoPrint/issues/1388) - Track consecutive timeouts even when idle and disconnect from printer when it's not responding any longer. - * [#1391](https://github.com/foosel/OctoPrint/issues/1391) - Only use the first value from the X-Scheme header for the reverse proxy setup. Otherwise there could be problems when multiple reverse proxies were configured chained together, each adding their own header to the mix. - * [#1407](https://github.com/foosel/OctoPrint/issues/1407) - If a file is uploaded with the "print" flag set to true, make sure to clear that flag after the print job has been triggered so that now all following uploaded or selected files will start printing on their own. - * [#1409](https://github.com/foosel/OctoPrint/issues/1409) - Don't report a communication timeout after a heatup triggered by a print from SD. - * Fixed scrolling to freshly uploaded files, also now highlighting the file entry for better visibility. - * Fixed overeager preemptive caching of invalid protocols. - * Fix modal background of update confirmation not vanishing - * Ensure log entries and messages from printer are sent to frontend already converted to utf-8. Otherwise even one line in the log that can't be converted automatically without error can cause updates from the backend to not arrive. - * Report correct printer state including error strings even after disconnecting - * While printing, be sure to read the next line from file and send that if the current line was filtered - * Small fixes in the GCODE analysis - * Small fixes in the documentation - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.13...1.2.14)) - -## 1.2.13 (2016-06-16) - -### Bug Fixes - - * [#1373](https://github.com/foosel/OctoPrint/issues/1373): Don't parse `B:` as bed temperature when it shows up as part of a position report from `M114`. - * [#1374](https://github.com/foosel/OctoPrint/issues/1374): Don't try to perform a passive login when the components we'd need to inform about a change in login state aren't yet available. Solves a bug that lead - among other things - to the Plugin Manager and the Software Update Plugin not showing anything but misleading errors until the user logged out and back in. - * Fixed the temperature graph staying uninitialized until a connection to a printer was established. - * Fixed an error causing issues during frontend startup if the browser doesn't support tracking browser visibility. - * Fixed an error causing issues during frontend startup if the browser doesn't support the capabilities needed for the GCODE viewer. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.12...1.2.13)) - -## 1.2.12 (2016-06-09) - -### Improvements - - * [#1338](https://github.com/foosel/OctoPrint/issues/1338): Threshold configuration fields now include information about how to specify the thresholds. - * Mark unrendered timelapses currently being processed (recording or rendering) in the list and remove action buttons so no accidental double-processing can take place. - * Removed file extension from "rendering" and "rendered" notifications, was misleading when using the [mp4 wrapper script](https://github.com/guysoft/OctoPi/issues/184). - * Added some new events for manipulation of slicing profiles. - * Small fix of the german translation. - -### Bug Fixes - - * [#1314](https://github.com/foosel/OctoPrint/issues/1314): Do not change the extension of `.g` files being uploaded to SD (e.g. `auto0.g`) - * [#1320](https://github.com/foosel/OctoPrint/issues/1320): Allow deletion of *.mp4 timelapse files (see [this wrapper script](https://github.com/guysoft/OctoPi/issues/184)). - * [#1324](https://github.com/foosel/OctoPrint/issues/1324): Make daemonized OctoPrint properly clean up its pid file again (see also [#1330](https://github.com/foosel/OctoPrint/pull/1330)). - * [#1326](https://github.com/foosel/OctoPrint/issues/1326): Do not try to clean up an unrendered timelapse while it is already being deleted (and produce way too much logging output in the process). - * [#1343](https://github.com/foosel/OctoPrint/issues/1343): Events are now processed in the order they are fired in, making e.g. the "timelapse rendering" message always appear before "timelapse failed" and hence not stay on forever in case of a failed timelapse. - * [#1344](https://github.com/foosel/OctoPrint/issues/1344): `ProgressPlugin`s now get also notified about a progress of 0%. - * [#1357](https://github.com/foosel/OctoPrint/issues/1357): Fixed wrongly named method call on editing access control options for a user, causing that to not work properly. - * [#1361](https://github.com/foosel/OctoPrint/issues/1361): Properly reload profile list for currently selected slicer in the slicing dialog on change of profiles. - * [#1364](https://github.com/foosel/OctoPrint/issues/1364): Fixed a race condition that could cause the UI to not initialize correctly due to 401 errors, leaving it in an unusable state until a reload. - * Fixed concurrent message pushing to the frontend being able to break push messages for the session by forcing synchronization of SockJS message sending. - * Do not require admin rights for connecting/disconnecting, like it was in 1.1.x (note that this is supposed to become configurable behaviour once [#1110](https://github.com/foosel/OctoPrint/issues/1110) gets implemented) - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.11...1.2.12)) - -## 1.2.11 (2016-05-04) - -### Important Announcement - -Due to a recent change in the financial situation of the project, the funding of OctoPrint is at stake. If you love OctoPrint and want to see its development continue at the pace of the past two years, please read on about its current funding situation and how you can help: ["I need your support"](http://octoprint.org/blog/2016/04/13/i-need-your-support/). - -### Improvements - - * Added option to treat resend requests as `ok` for such firmwares that do not send an `ok` after requesting a resend. If you printer communication gets stalled after a resend request from the firmware, try checking this option. - * Added an "About" dialog to properly inform about OctoPrint's license, contributors and supporters. - * Added a announcement plugin that utilizes the RSS feeds of the [OctoPrint Blog](http://octoprint.org/blog/) and the [plugin repository](http://plugins.octoprint.org) to display news to the user. By default only the "important announcement" category is enabled. This category will only be used for very rare situations such as making you aware of critical updates or important news. You can enable further categories (with more announcements to be expected) in the plugin's settings dialog. - -### Bug Fixes - - * [#1300](https://github.com/foosel/OctoPrint/issues/1300) - Removed possibility to accidentally disabling local file list by first limiting view to files from SD and then disabling SD support. - * [#1315](https://github.com/foosel/OctoPrint/issues/1315) - Fixed broken post roll on z-based timelapses. - * Fixed CSS data binding syntax on the download link in the files list - * Changed control distance from jQuery data into a knockout observerable and observerableArray - * Allow an unauthorized user to logout from a logedin interface state - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.10...1.2.11)) - -## 1.2.10 (2016-03-16) - -### Improvements - - * Improved performance of console output during plugin installation/deinstallation - * Slight performance improvements in the communication layer - * Log small log excerpt to `octoprint.log` upon encountering a communication error. - * Changed wording in "firmware error" notifications to better reflect that there was an error while communicating with the printer, since the error condition can also be triggered by serial errors while trying to establish a connection to the printer or when already connected. - * Support downloading ".mp4" timelapse files. You'll need a [custom wrapper script for timelapse rendering](https://github.com/guysoft/OctoPi/issues/184) for this to be relevant to you. See also [#1255](https://github.com/foosel/OctoPrint/pull/1255) - * The communication layer will now wait up to 10s after clicking disconnect in order to send any left-over lines from its buffers. - * Moved less commonly used configuration options in Serial settings into "Advanced options" roll-out. - -### Bug Fixes - - * [#1224](https://github.com/foosel/OctoPrint/issues/1224) - Fixed an issue introduced by the fix for [#1196](https://github.com/foosel/OctoPrint/issues/1196) that had the "Upload to SD" button stop working correctly. - * [#1226](https://github.com/foosel/OctoPrint/issues/1226) - Fixed an issue causing an error on disconnect after or cancelling of an SD print, caused by the unsuccessful attempt to record print recovery data for the file on the printer's SD card. - * [#1268](https://github.com/foosel/OctoPrint/issues/1268) - Only add bed temperature line to temperature management specific start gcode in CuraEngine invocation if a bed temperature is actually set in the slicing profile. - * [#1271](https://github.com/foosel/OctoPrint/issues/1271) - If a communication timeout occurs during an active resend request, OctoPrint will now not send an `M105` with an increased line number anymore but repeat the last resent command instead. - * [#1272](https://github.com/foosel/OctoPrint/issues/1272) - Don't add an extra `ok` for `M28` response. - * [#1273](https://github.com/foosel/OctoPrint/issues/1273) - Add an extra `ok` for `M29` response, but only if configured such in "Settings" > "Serial" > "Advanced options" > "Generate additional ok for M29" - * [#1274](https://github.com/foosel/OctoPrint/issues/1274) - Trigger `M20` only once after finishing uploading to SD - * [#1275](https://github.com/foosel/OctoPrint/issues/1275) - Prevent `M105` "cascade" due to communication timeouts - * Fixed wrong tracking of extruder heating up for `M109 Tn` commands in multi-extruder setups. - * Fixed start of SD file uploads not sending an `M110`. - * Fixed job data not being reset when disconnecting while printing. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.9...1.2.10)) - -## 1.2.9 (2016-02-10) - -### Improvements - - * [#318](https://github.com/foosel/OctoPrint/issues/318) - Snapshots for timelapses are now named in a non-colliding, job-based way, allowing a new timelapse to start while the other is still being rendered (although printing with an active timelapse rendering job is not recommended and will be solved with a proper render job queue in a later version). Timelapses that were not successfully rendered are kept for 7 days (configurable, although not via the UI so far) and can be manually rendered or deleted through a new UI component within the timelapse tab that shows up if unrendered timelapses are detected. - * [#485](https://github.com/foosel/OctoPrint/issues/485) - "Timelapse rendering" notification is now persistent, even across reloads/client switches. That should make it easier to see that a rendering job is currently in progress. - * [#939](https://github.com/foosel/OctoPrint/issues/939) - Updated to Knockout 3.4.0 - * [#1204](https://github.com/foosel/OctoPrint/issues/1204) - Display total print time as estimated by GCODE viewer on GCODE viewer tab. That will allow access to an estimate even if the server hadn't yet calculated that when a print started. Note that due to slightly different implementation server and client side the resulting estimate might differ. - * OctoPrint now serves an intermediary page upon start that informs the user about the server still starting up. Once the server is detected as running, the page automatically switches to the standard interface. - * OctoPrint now displays a link to the release notes of an updated component in the update notification, the update confirmation and the version overview in the settings dialog. Please always make sure to at least skim over the release notes for new OctoPrint releases, they might contain important information that you need to know before updating. - * Improved initial page loading speeds by introducing a preemptive cache. OctoPrint will now record how you access it and on server start pre-render the page so it's ideally available in the server-side cache when you try to access it. - * Initialize login user name and password with an empty string and clear both on successful login (see [#1175](https://github.com/foosel/OctoPrint/pull/1175)). - * Added a "Refresh" button to the file list for people who modify the stored files externally (doing this is not encouraged however due to reasons of book keeping, e.g. metadata tracking etc). - * "Save" button on settings dialog is now disabled while background tasks (getting or receiving config data from the backend) are in progress. - * Improved performance of terminal tab on lower powered clients. Adaptive rate limiting now ensures the server backs off with log updates if the client can't process them fast enough. If the client is really slow, log updates get disabled automatically during printing. This behaviour can be disabled with override buttons in the terminal tab's advanced options if necessary. - * Added option to ignore any unhandled errors reported by the firmware and another option to only cancel ongoing prints on unhandled errors from the firmware (instead of instant disconnect that so far was the default). - * Made version compatibility check PEP440 compliant (important for plugin authors). - * Do not hiccup on manually sent `M28` commands. - * Persist print recovery data on print failures (origin and name of printed file, position in file when print was aborted, time and date of print failure). Currently this data isn't used anywhere, but it [can be accessed from plugins in order to add recovery functionality](https://github.com/foosel/OctoPrint-PrintRecoveryPoc) to OctoPrint. - * Small performance improvements in update checks. - * The file upload dialog will now only display files having an extension that's supported for upload (if the browser supports it, also see [#1196](https://github.com/foosel/OctoPrint/issues/1196)). - -### Bug Fixes - - * [#1007](https://github.com/foosel/OctoPrint/issues/1007) - Don't enable the "Print" button if no print job is selected. - * [#1181](https://github.com/foosel/OctoPrint/issues/1181) - Properly slugify UTF-8 only file names. - * [#1196](https://github.com/foosel/OctoPrint/issues/1196) - Do not show drag-n-drop overlay if server is offline. - * [#1208](https://github.com/foosel/OctoPrint/issues/1208) - Fixed `retraction_combing` profile setting being incorrectly used by bundled Cura plugin (see [#1209](https://github.com/foosel/OctoPrint/pull/1209)) - * Fixed OctoPrint compatibility check in the plugin manager, could report `False` for development versions against certain versions of Python's `setuptools` (thanks to @ignaworm who stumbled over this). - * Fixed a missing parameter in `PluginSettings.remove` call (see [#1177](https://github.com/foosel/OctoPrint/pull/1177)). - * Docs: Fixed the example for a custom `M114` control to also match negative coordinates. - * Reset scroll position in settings dialog properly when re-opening it or switching tabs. - * Fixed an issue that prevented system menu entries that were added to a so far empty system menu make the menu show up. - * Fixed an issue that made requests to restricted resources fail even though the first run wizard had been completed successfully. - * Fixed an issue where an unknown command or the suppression of a command could cause the communication to stall until a communication timeout was triggered. - * Strip [unwanted ANSI characters](https://github.com/pypa/pip/issues/3418) from output produced by pip versions 8.0.0, 8.0.1 and 8.0.3 that prevents our plugin installation detection from working correctly. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.8...1.2.9)) - -## 1.2.8 (2015-12-07) - -### Notes for Upgraders - -#### A bug in 1.2.7 prevents directly updating to 1.2.8, here's what to do - -A bug in OctoPrint 1.2.7 (fixed in 1.2.8) prevents updating OctoPrint to version -1.2.8. If you try to perform the update, you will simply be told that "the update -was successful", but the update won't actually have taken place. To solve this -hen-egg-problem, a plugin has been made available that fixes said bug (through -monkey patching). - -The plugin is called "Updatefix 1.2.7" and can be found -[in the plugin repository](http://plugins.octoprint.org/plugins/updatefix127/) -and [on Github](https://github.com/OctoPrint/OctoPrint-Updatefix-1.2.7/). - -Before attempting to update your installation from version 1.2.7 to version 1.2.8, -please install the plugin via your plugin manager and restart your server. Note that -you will only see it in the Plugin Manager if you need it, since it's only compatible with -OctoPrint version 1.2.7. After you installed the plugin and restarted your server -you can update as usual. The plugin will self-uninstall once it detects that it's -running under OctoPrint 1.2.8. After the self-uninstall another restart of your server -will be triggered (if you have setup your server's restart command, defaults to -`sudo service octoprint restart` on OctoPi) in order to really get rid of any -left-overs, so don't be alarmed when that happens, it is intentional. - -**If you cannot or don't want to use the plugin**, alternatively you can switch -OctoPrint to "Commit" based tracking via the settings of the Software Update plugin, -update, then switch back to "Release" based tracking (see [this screenshot](https://i.imgur.com/wvkgiGJ.png)). - -#### Bed temperatures are now only displayed if printer profile has a heated bed configured - -This release fixes a [bug](https://github.com/foosel/OctoPrint/issues/1125) -that caused bed temperature display and controls to be available even if the -selected printer profile didn't have a heated bed configured. - -If your printer does have a heated bed but you are not seeing its temperature -in the "Temperature" tab after updating to 1.2.8, please make sure to check -the "Heated Bed" option in your printer profile (under Settings > Printer Profiles) -as shown [in this short GIF](http://i.imgur.com/wp1j9bs.gif). - -### Improvements - - * Version numbering now follows [PEP440](https://www.python.org/dev/peps/pep-0440/). - * Prepared some things for publishing OctoPrint on [PyPi](https://pypi.python.org/pypi) - in the future. - * [BlueprintPlugin mixin](http://docs.octoprint.org/en/master/plugins/mixins.html#blueprintplugin) - now has an `errorhandler` decorator that serves the same purpose as - [Flask's](http://flask.pocoo.org/docs/0.10/patterns/errorpages/#error-handlers) - ([#1059](https://github.com/foosel/OctoPrint/pull/1059)) - * Interpret `M25` in a GCODE file that is being streamed from OctoPrint as - indication to pause, like `M0` and `M1`. - * Cache rendered page and translation files indefinitely. That should - significantly improve performance on reloads of the web interface. - * Added the string "unknown command" to the list of ignored printer errors. - This should help with general firmware compatibility in case a firmware - lacks features. - * Added the strings "cannot open" and "cannot enter" to the list of ignored - printer errors. Those are errors that Marlin may report if there is an issue - with the printer's SD card. - * The "CuraEngine" plugin now makes it more obvious that it only targets - CuraEngine versions up to and including 15.04 and also links to the plugin's - homepage with more information right within the settings dialog. - * Browser tab visibility is now tracked by the web interface, disabling the - webcam and the GCODE viewer if the tab containing OctoPrint is not active. - That should reduce the amount of resource utilized by the web interface on - the client when it is not actively monitored. Might also help to mitigate - [#1065](https://github.com/foosel/OctoPrint/issues/1065), the final verdict - on that one is still out though. - * The printer log in the terminal tab will now be cut off after 3000 lines - even if autoscroll is disabled. If the limit is reached, no more log lines - will be added to the client's buffer. That ensures that the log will not - scroll and the current log excerpt will stay put while also not causing - the browser to run into memory errors due to trying to buffer an endless - amount of log lines. - * Increased timeout of "waiting for restart" after an update from 20 to 60sec - (20sec turned out to be too little for OctoPi for whatever reason). - * Added a couple of unit tests - -### Bug Fixes - - * [#1120](https://github.com/foosel/OctoPrint/issues/1120) - Made the watchdog - that monitors and handles the `watched` folder more resilient towards errors. - * [#1125](https://github.com/foosel/OctoPrint/issues/1125) - Fixed OctoPrint - displaying bed temperature and controls and allowing the sending of GCODE - commands targeting the bed (`M140`, `M190`) if the printer profile doesn't - have a heated bed configured. - * Fixed an issue that stopped the software updater working for OctoPrint. The - updater reports success updating, but no update has actually taken place. A - fix can be applied for this issue to OctoPrint version 1.2.7 via - [the Updatefix 1.2.7 plugin](https://github.com/OctoPrint/OctoPrint-Updatefix-1.2.7). - For more information please refer to the [Important information for people updating from version 1.2.7](#important-information-for-people-updating-from-version-127) - above. - * Fix: Current filename in job data should never be prefixed with `/` - * Only persist plugin settings that differ from the defaults. This way the - `config.yaml` won't be filled with lots of redundant data. It's the - responsibility of the plugin authors to responsibly handle changes in default - settings of their plugins and add data migration where necessary. - * Fixed a documentation bug ([#1067](https://github.com/foosel/OctoPrint/pull/1067)) - * Fixed a conflict with bootstrap-responsive, e.g. when using the - [ScreenSquish Plugin](http://plugins.octoprint.org/plugins/screensquish/) - ([#1103](https://github.com/foosel/OctoPrint/pull/1067)) - * Fixed OctoPrint still sending SD card related commands to the printer even - if SD card support is disabled (e.g. `M21`). - * Hidden files are no longer visible to the template engine, neither as (GCODE) - scripts nor as interface templates. - * The hostname and URL prefix via which the OctoPrint web interface is accessed - is now part of the cache key. Without that being the case the cache could - be created referring to something like `/octoprint/prefix/api/` for its API - endpoint (if accessed via `http://somehost:someport/octoprint/prefix/` first - time), which would then cause the interface to not work if accessed later - via another route (e.g. `http://someotherhost/`). - * Fixed a JavaScript error on finishing streaming of a file to SD. - * Fixed version reporting on detached HEADs (when the branch detection - reported "HEAD" instead of "(detached" - * Fixed some path checks for systems with symlinked paths - ([#1051](https://github.com/foosel/OctoPrint/pull/1051)) - * Fixed a bug causing the "Server Offline" overlay to pop _under_ the - "Please reload" overlay, which could lead to "Connection refused" browser - messages when clicking "Reload now" in the wrong moment. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.7...1.2.8)) - -## 1.2.7 (2015-10-20) - -### Improvements - - * [#1062](https://github.com/foosel/OctoPrint/issues/1062) - Plugin Manager - now has a configuration dialog that among other things allows defining the - used `pip` command if auto detection proves to be insufficient here. - * Allow defining additional `pip` parameters in Plugin Manager. That might - make `sudo`-less installation of plugins possible in situations where it's - tricky otherwise. - * Improved timelapse processing (backported from `devel` branch): - * Individually captured frames cannot "overtake" each other anymore through - usage of a capture queue. - * Notifications will now be shown when the capturing of the timelapse's - post roll happens, including an approximation of how long that will take. - * Usage of `requests` instead of `urllib` for fetching the snapshot, - appears to also have [positive effects on webcam compatibility](https://github.com/foosel/OctoPrint/issues/1078). - * Some more defensive escaping for various settings in the UI (e.g. webcam URL) - * Switch to more error resilient saving of configuration files and other files - modified during runtime (save to temporary file & move). Should reduce risk - of file corruption. - * Downloading GCODE and STL files should now set more fitting `Content-Type` - headers (`text/plain` and `application/sla`) for better client side support - for "Open with" like usage scenarios. - * Selecting z-triggered timelapse mode will now inform about that not working - when printing from SD card. - * Software Update Plugin: Removed "The web interface will now be reloaded" - notification after successful update since that became obsolete with - introduction of the "Reload Now" overlay. - * Updated required version of `psutil` and `netifaces` dependencies. - -### Bug Fixes - - * [#1057](https://github.com/foosel/OctoPrint/issues/1057) - Better error - resilience of the Software Update plugin against broken/incomplete update - configurations. - * [#1075](https://github.com/foosel/OctoPrint/issues/1075) - Fixed support - of `sudo` for installing plugins, but added big visible warning about it - as it's **not** recommended. - * [#1077](https://github.com/foosel/OctoPrint/issues/1077) - Do not hiccup - on [UTF-8 BOMs](https://en.wikipedia.org/wiki/Byte_order_mark) (or other - BOMs for that matter) at the beginning of GCODE files. - * Fixed an issue that caused user sessions to not be properly associated, - leading to Sessions getting duplicated, wrongly saved etc. - * Fixed internal server error (HTTP 500) response on REST API calls with - unset `Content-Type` header. - * Fixed an issue leading to drag-and-drop file uploads to trigger frontend - processing in various other file upload widgets. - * Fixed a documentation error. - * Fixed caching behaviour on GCODE/STL downloads, was setting the `ETag` - header improperly. - * Fixed GCODE viewer not properly detecting change of currently visualized - file on Windows systems. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.6...1.2.7)) - -## 1.2.6 (2015-09-02) - -### Improvements - - * Added support for version reporting on detached checkouts - (see [#1041](https://github.com/foosel/OctoPrint/pull/1041)) - -### Bug Fixes - - * Pinned requirement for [psutil](https://pypi.python.org/pypi/psutil) - dependency to version 3.1.1 of that library due to an issue when - installing version 3.2.0 of that library released on 2015-09-02 through - a `python setup.py install` on OctoPrint. Also pinned all other requirements - to definitive versions that definitely work while at it to keep that from - happening again. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.5...1.2.6)) - -## 1.2.5 (2015-08-31) - -### Improvements - - * [#986](https://github.com/foosel/OctoPrint/issues/986) - Added tooltip for - "additional data" button in file list. - * [#1028](https://github.com/foosel/OctoPrint/issues/1028) - Hint about why - timelapse configuration is disabled. - * New central configuration option for commands to restart OctoPrint and to - restart and shut down the system OctoPrint is running on. This allows plugins - (like the Software Update Plugin or the Plugin Manager) and core functionality - to perform these common administrative tasks without the user needing to define - everything redundantly. - * Settings dialog now visualizes when settings are saving and when they being - retrieved. Also the Send/Cancel buttons are disabled while settings are saving - to prevent duplicated requests and concurrent retrieval of the settings by - multiple viewmodels is disabled as well. - * Better protection against rendering errors from templates provided by third - party plugins. - * Better protection against corrupting the configuration by using a temporary - file as intermediate buffer. - * Added warning to UI regarding Z timelapses and spiralized objects. - * Better compatibility with Repetier firmware: - * Added "Format Error" to whitelisted recoverable communication errors - (see also [#1032](https://github.com/foosel/OctoPrint/pull/1032)). - * Added option to ignore repeated resend requests for the same line (see - also discussion in [#1015](https://github.com/foosel/OctoPrint/pull/1015)). - * Software Update Plugin: - * Adjusted to utilize new centralized restart commands (see above). - * Allow configuration of checkout folder and version tracking type via - Plugin Configuration. - * Display message to user if OctoPrint's checkout folder is not configured - or a non-release version is running and version tracking against releases - is enabled. - * Clear version cache when a change in the check configuration is detected. - * Mark check configurations for which an update is not possible. - * Made disk space running low a bit more obvious through visual warning on - configurable thresholds. - -### Bug Fixes - - * [#985](https://github.com/foosel/OctoPrint/issues/985) - Do not hiccup on - unset `Content-Type` part headers for multipart file uploads. - * [#1001](https://github.com/foosel/OctoPrint/issues/1001) - Fixed connection - tab not unfolding properly (see also [#1002](https://github.com/foosel/OctoPrint/pull/1002)). - * [#1012](https://github.com/foosel/OctoPrint/issues/1012) - All API - responses now set no-cache headers, making the Edge browser behave a bit better - * [#1019](https://github.com/foosel/OctoPrint/issues/1019) - Better error - handling of problems when trying to write the webassets cache. - * [#1021](https://github.com/foosel/OctoPrint/issues/1021) - Properly handle - serial close on Macs. - * [#1031](https://github.com/foosel/OctoPrint/issues/1031) - Special - handling of `M112` (emergency stop) command: - * Jump send queue - * In case the printer's firmware doesn't understand it yet, at least - shutdown all of the heaters - * Disconnect - * Properly reset job progress to 0% when restarting a previously completed - printjob (see [#998](https://github.com/foosel/OctoPrint/pull/998)). - * Report an update as failed if the `pip` command returns a return code that - indicates failure. - * Fixed sorting of templates: could only be sorted by name, individual - configurations were ignored (see [#1022](https://github.com/foosel/OctoPrint/pull/1022)). - * Fixed positioning of custom context menus: were offset due to changes in - overall positioning settings (see [#1023](https://github.com/foosel/OctoPrint/pull/1023)). - * Software Update: Don't use display version for comparison of git commit - hashs. - * Fixed temperature parsing for multi extruder setups. - * Fixed nested vertical and horizontal custom control layouts. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.4...1.2.5)) - -## 1.2.4 (2015-07-23) - -### Improvements - - * `RepeatedTimer` now defaults to `daemon` set to `True`. This makes sure - plugins using it don't have to remember to set that flag themselves in - order for the server to properly shut down when timers are still active. - * Fixed a typo in the docs about `logging.yaml` (top level element is - `loggers`, not `logger`). - * Support for plugins with external dependencies (`dependency_links` in - setuptools), interesting for plugin authors who need to depend on Python - libraries that are (not yet) available on PyPI. - * Better resilience against errors within plugins. - -### Bug Fixes - - * Do not cache web page when running for the first time, to avoid caching - the first run dialog popup along side with it. This should solve issues - people were having when configuring OctoPrint for the first time, then - reloading the page without clearing the cache, being again prompted with - the dialog with no chance to clear it. - * Fix/workaround for occasional white panes in settings dialog on Safari 8, - which appears to have an issue with fixed positioning. - * Fixed form field truncation in upload requests that could lead to problems - when trying to import Cura profiles with names longer than 28 characters. - * Fixed webcam rotation for timelapse rendering. - * Fixed user settings not reaching the editor in the frontend. - * Notifications that are in process of being closed don't open again on - mouse over (that was actually more of an unwanted feature). - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.3...1.2.4)) - -## 1.2.3 (2015-07-09) - -### Improvements - - * New option to actively poll the watched folder. This should make it work also - if it is mounted on a filesystem that doesn't allow getting notifications - about added files through notification by the operating system (e.g. - network shares). - * Better resilience against senseless temperature/SD-status-polling intervals - (such as 0). - * Log exceptions during writing to the serial port to `octoprint.log`. - -### Bug Fixes - - * [#961](https://github.com/foosel/OctoPrint/pull/961) - Fixed a JavaScript error that caused an error to be logged when "enter" was pressed in file or plugin search. - * [#962](https://github.com/foosel/OctoPrint/pull/962) - ``url(...)``s in packed CSS and LESS files should now be rewritten properly too to refer to correct paths - * Update notifications were not vanishing properly after updating: - * Only use version cache for update notifications if the OctoPrint version still is the same to make sure the cache gets invalidated after an external update of OctoPrint. - * Do not persist version information when saving settings of the Software Update plugin - * Always delete files from the ``watched`` folder after importing then. Using file preprocessor plugins could lead to the files staying there. - * Fixed an encoding problem causing OctoPrint's Plugin Manager and Software Update plugins to choke on UTF-8 characters in the update output. - * Fixed sorting by file size in file list - * More resilience against missing plugin assets: - * Asset existence will now be checked before they get included - in the assets to bundle by webassets, logging a warning if a - file isn't present. - * Monkey-patched webassets filter chain to not die when a file - doesn't exist, but to log an error instead and just return - an empty file instead. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.2...1.2.3)) - -## 1.2.2 (2015-06-30) - -### Bug Fixes - -* Fixed an admin-only security issue introduced in 1.2.0, updating is strongly advised. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.1...1.2.2)) - -## 1.2.1 (2015-06-30) - -### Improvements - -* More flexibility when interpreting compatibility data from plugin repository. If compatibility information is provided - only as a version number it's prefixed with `>=` for the check (so stating a compatibility of only - `1.2.0` will now make the plugin compatible to OctoPrint 1.2.0+, not only 1.2.0). Alternatively the compatibility - information may now contain stuff like `>=1.2,<1.3` in which case the plugin will only be shown as compatible - to OctoPrint versions 1.2.0 and up but not 1.3.0 or anything above that. See also - [the requirement specification format of the `pkg_resources` package](https://pythonhosted.org/setuptools/pkg_resources.html#requirements-parsing). -* Only print the commands of configured event handlers to the log when a new `debug` flag is present in the config - (see [the docs](http://docs.octoprint.org/en/master/configuration/config_yaml.html#events)). Reduces risk of disclosing sensitive data when sharing log files. - -### Bug Fixes - -* [#956](https://github.com/foosel/OctoPrint/issues/956) - Fixed server crash when trying to configure a default - slicing profile for a still unconfigured slicer. -* [#957](https://github.com/foosel/OctoPrint/issues/957) - Increased maximum allowed body size for plugin archive uploads. -* Bugs without tickets: - * Clean exit on `SIGTERM`, calling the shutdown functions provided by plugins. - * Don't disconnect on `volume.init` errors from the firmware. - * `touch` uploaded files on local file storage to ensure proper "uploaded date" even for files that are just moved - from other locations of the file system (e.g. when being added from the `watched` folder). - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.0...1.2.1)) - -## 1.2.0 (2015-06-25) - -### Note for Upgraders - - * The [Cura integration](https://github.com/daid/Cura) has changed in such a way that OctoPrint now calls the - [CuraEngine](https://github.com/Ultimaker/CuraEngine) directly instead of depending on the full Cura installation. See - [the wiki](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) for instructions on how to change your setup to - accommodate the new integration. - -### New Features - -* OctoPrint now has a [plugin system](http://docs.octoprint.org/en/master/plugins/index.html) which allows extending its - core functionality. - * Plugins may be installed through the new and bundled [Plugin Manager Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager) - available in OctoPrint's settings. This Plugin Manager also allows browsing and easy installation of plugins - registered on the official [OctoPrint Plugin Repository](http://plugins.octoprint.org). - * For interested developers there is a [tutorial available in the documentation](http://docs.octoprint.org/en/master/plugins/gettingstarted.html) - and also a [cookiecutter template](https://github.com/OctoPrint/cookiecutter-octoprint-plugin) to quickly bootstrap - new plugins. -* Added internationalization of UI. Translations of OctoPrint are being crowd sourced via [Transifex](https://www.transifex.com/projects/p/octoprint/). - Language Packs for both the core application as well as installed plugins can be uploaded through a new management - dialog in Settings > Appearance > Language Packs. A translation into German is included, further language packs - will soon be made available. -* Printer Profiles: Printer properties like print volume, extruder offsets etc are now managed via Printer Profiles. A - connection to a printer will always have a printer profile associated. -* File management now supports STL files as first class citizens (including UI adjustments to allow management of - uploaded STL files including removal and reslicing) and also allows folders (not yet supported by UI). STL files - can be downloaded like GCODE files. -* Slicing has been greatly improved: - * It now allows for a definition of slicing profiles to use for slicing plus overrides which can be defined per slicing - job (defining overrides is not yet part of the UI but it's on the roadmap). - * A new slicing dialog has been added which allows (re-)slicing uploaded STL files (which are now displayed in the file list - as well). The slicing profile and printer profile to use can be specified here as well as the file name to which to - slice to and the action to take after slicing has been completed (none, selecting the sliced GCODE for printing or - starting to print it directly) - * The slicing API allows positioning the model to slice on the print bed (Note: this is not yet available in the UI). - * Slicers themselves are integrated into the system via ``SlicingPlugins``. - * Bundled [Cura Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) allows slicing through CuraEngine up - to and including 15.04. Existing Cura slicing profiles can be imported through the web interface. -* New file list: Pagination is gone, no more (mobile incompatible) pop overs, instead scrollable and with instant - search -* You can now define a folder (default: `~/.octoprint/watched`) to be watched for newly added GCODE (or -- if slicing - support is enabled -- STL) files to automatically add. -* New type of API key: [App Session Keys](http://docs.octoprint.org/en/master/api/apps.html) for trusted applications -* OctoPrint now supports `action:...` commands received via debug messages (`// action:...`) from the printer. Currently supported are - - `action:pause`: Pauses the current job in OctoPrint - - `action:resume`: Resumes the current job in OctoPrint - - `action:disconnect`: Disconnects OctoPrint from the printer - Plugins can add supported commands by [hooking](http://docs.octoprint.org/en/master/plugins/hooks.html) into the - ``octoprint.comm.protocol.action`` hook -* Mousing over the webcam image in the control tab enables key control mode, allowing you to quickly move the axis of your - printer with your computer's keyboard ([#610](https://github.com/foosel/OctoPrint/pull/610)): - - arrow keys: X and Y axes - - W, S / PageUp, PageDown: Z axes - - Home: Home X and Y axes - - End: Home Z axes - - 1, 2, 3, 4: change step size used (0.1, 1, 10, 100mm) -* Controls for adjusting feed and flow rate factor added to Controls ([#362](https://github.com/foosel/OctoPrint/issues/362)) -* Custom controls now also support slider controls -* Custom controls now support a row layout -* Users can now define custom GCODE scripts to run upon starting/pausing/resuming/success/failure of a print or for - custom controls ([#457](https://github.com/foosel/OctoPrint/issues/457), [#347](https://github.com/foosel/OctoPrint/issues/347)) -* Bundled [Discovery Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery) allows discovery of OctoPrint - instances via SSDP/UPNP and optionally also via ZeroConf/Bonjour/Avahi. -* Bundled [Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update) takes care of notifying - about new OctoPrint releases and also allows updating if configured as such. Plugins may register themselves with the - update notification and application process through a new hook ["octoprint.plugin.softwareupdate.check_config"](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update#octoprintpluginsoftwareupdatecheck_config). - -### Improvements - -* Logging is now configurable via config file -* Added last print time to additional GCODE file information -* Better error handling for capture issues during timelapse creation & more robust handling of missing images during - timelapse creation -* Start counting the layers at 1 instead of 0 in the GCODE viewer -* Upgraded [Font Awesome](https://fortawesome.github.io/Font-Awesome/) to version 3.2.1 -* Better error reporting for timelapse rendering and system commands -* Custom control can now be defined so that they show a Confirm dialog with configurable text before executing - ([#532](https://github.com/foosel/OctoPrint/issues/532) and [#590](https://github.com/foosel/OctoPrint/pull/590)) -* Serial communication: Also interpret lines starting with "!!" as errors -* Added deletion of pyc files to the `python setup.py clean` command -* Settings now show a QRCode for the API Key ([#637](https://github.com/foosel/OctoPrint/pull/637)) -* Username in UI is no longer enclosed in scare quotes ([#595](https://github.com/foosel/OctoPrint/pull/595)) -* Username in login dialog is not automatically capitalized on mobile devices anymore ([#639](https://github.com/foosel/OctoPrint/pull/639)) -* "Slicing Done" and "Streaming Done" notifications now have a green background ([#558](https://github.com/foosel/OctoPrint/issues/558)) -* Files that are currently in use, be it for slicing, printing or whatever, are now tracked and can not be deleted as - long as they are in use -* Settings in UI get refreshed when opening settings dialog -* New event "SettingsUpdated" -* "Print time left" is now not displayed until it becomes somewhat stable. Display in web interface now also happens - in a fuzzy way instead of the format hh:mm:ss, to not suggest a high accuracy anymore where the can't be one. Additionally - OctoPrint will use data from prior prints to enhance the initial print time estimation. -* Added handler for uncaught exceptions to make sure those get logged, should make the logs even more useful for analysing - bug reports -* The server now tracks the modification date of the configuration file and reloads it prior to saving the config if - it has been changed during runtime by external editing, hence no config settings added manually while the server - was running should be overwritten anymore. -* Display a "Please Reload" overlay when a new server version or a change in installed plugins is detected after a - reconnect to the server. -* Better handling of errors on the websocket - no more logging of the full stack trace to the log, only a warning - message for now. -* Daemonized OctoPrint now cleans up its pidfile when receiving a TERM signal ([#711](https://github.com/foosel/OctoPrint/issues/711)) -* Added serial types for OpenBSD ([#551](https://github.com/foosel/OctoPrint/pull/551)) -* Improved behaviour of terminal: - * Disabling autoscrolling now also stops cutting off the log while it's enabled, effectively preventing log lines from - being modified at all ([#735](https://github.com/foosel/OctoPrint/issues/735)) - * Applying filters displays ``[...]`` where lines where removed and doesn't cause scrolling on filtered lines - anymore ([#286](https://github.com/foosel/OctoPrint/issues/286)) - * Added a link to scroll to the end of the terminal log (useful for when autoscroll is disabled) - * Added a link to select all current contents of the terminal log for easy copy-pasting - * Added a display of how many lines are displayed, how many are filtered and how many are available in total -* Frame rate for timelapses can now be configured per timelapse ([#782](https://github.com/foosel/OctoPrint/pull/782)) -* Added an option to specify the amount of encoding threads for FFMPEG ([#785](https://github.com/foosel/OctoPrint/pull/785)) -* "Disconnected" screen now is not shown directly after a close of the socket, instead the client first tries to - directly reconnect once, and only if that doesn't work displays the dialog. Should reduce short popups of the dialog - due to shaky network connections and/or weird browser behaviour when downloading things from the UI. -* Development dependencies can now be installed with ``pip -e .[develop]`` -* White and transparent colors ;) are supported for the navigation bar ([#789](https://github.com/foosel/OctoPrint/pull/789)) -* Drag-n-drop overlay for file uploads now uses the full available screen space, improving usability on high resolution - displays ([#187](https://github.com/foosel/OctoPrint/issues/187)) -* OctoPrint server should no longer hang when big changes in the system time happen, e.g. after first contact to an - NTP server on a Raspberry Pi image. Achieved through monkey patching Tornado with - [this PR](https://github.com/tornadoweb/tornado/pull/1290). -* Serial ports matching ``/dev/ttyAMA*`` are not anymore listed by default (this was the reason for a lot of people - running into problems while attempting to connect to their printer on their Raspberry Pis, on which ``/dev/ttyAMA0`` - is the OS's serial console by default). Added configuration of additional ports to the Serial Connection section in - the Settings to make it easier for those people who do indeed have their printer connected to ``/dev/ttyAMA0``. -* Better behaviour of the settings dialog on low-width devices, navigation and content also now scroll independently - from each other (see also [#823](https://github.com/foosel/OctoPrint/pull/823)) -* Renamed "Temperature Timeout" and "SD Status Timeout" in Settings to "Temperature Interval" and "SD Status Interval" - to better reflect what those values are actually used for. -* Added support for rectangular printer beds with the origin in the center ([#682](https://github.com/foosel/OctoPrint/issues/682) - and [#852](https://github.com/foosel/OctoPrint/pull/852)). Printer profiles now contain a new settings ``volume.origin`` - which can either be ``lowerleft`` or ``center``. For circular beds only ``center`` is supported. -* Made baudrate detection a bit more solid, still can't perform wonders. -* Only show configuration options for additional extruders if more than one is available, and don't include offset - configuration for first nozzle which acts as reference for the other offsets ([#677](https://github.com/foosel/OctoPrint/issues/677)). -* Cut off of the temperature graph is now not based on the number of data points any more but on the actual time of the - data points. Anything older than ``n`` minutes will be cut off, with ``n`` defaulting to 30min. This value can be - changed under "Temperatures" in the Settings ([#343](https://github.com/foosel/OctoPrint/issues/343)). -* High-DPI support for the GCode viewer ([#837](https://github.com/foosel/OctoPrint/issues/837)). -* Stop websocket connections from multiplying ([#888](https://github.com/foosel/OctoPrint/pull/888)). -* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and - [#906](https://github.com/foosel/OctoPrint/pull/906)) -* System commands now be set to a) run asynchronized by setting their `async` property to `true` and b) to ignore their - result by setting their `ignore` property to `true`. -* Various improvements of newly introduced features over the course of development: - * File management: The new implementation will migrate metadata from the old one upon first startup after upgrade from - version 1.1.x to 1.2.x. That should speed up initial startup. - * File management: GCODE Analysis backlog processing has been throttled to not take up too many resources on system - startup. Freshly uploaded files should still be analyzed at full speed. - * Plugins: SettingsPlugins may track versions of configuration format stored in `config.yaml`, including a custom - migration method getting called when a mismatch between the currently stored configuration format version and the one - reported by the plugin as current is detected. - * Plugins: Plugins may now have a folder for plugin related data whose path can be retrieved from the plugin itself - via its new method [`get_plugin_data_folder`](http://docs.octoprint.org/en/master/modules/plugin.html#octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder). - * Plugin Manager: Don't allow plugin management actions (like installing/uninstalling or enabling/disabling) while the - printer is printing (see also unreproduced issue [#936](https://github.com/foosel/OctoPrint/issues/936)). - * Plugin Manager: More options to try to match up installed plugin packages with discovered plugins. - * Plugin Manager: Display a more friendly message if after the installation of a plugin it could not be correctly - identifier. - * Software Update: Enforce refreshing of available updates after any changes in enabled plugins. - -### Bug Fixes - -* [#435](https://github.com/foosel/OctoPrint/issues/435) - Always interpret negative duration (e.g. for print time left) - as 0 -* [#516](https://github.com/foosel/OctoPrint/issues/516) - Also require API key even if ACL is disabled. -* [#556](https://github.com/foosel/OctoPrint/issues/556) - Allow login of the same user from multiple browsers without - side effects -* [#612](https://github.com/foosel/OctoPrint/issues/612) - Fixed GCODE viewer in zoomed out browsers -* [#633](https://github.com/foosel/OctoPrint/issues/633) - Correctly interpret temperature lines from multi extruder - setups under Smoothieware -* [#680](https://github.com/foosel/OctoPrint/issues/680) - Don't accidentally include a newline from the MIME headers - in the parsed multipart data from file uploads -* [#709](https://github.com/foosel/OctoPrint/issues/709) - Properly initialize time estimation for SD card transfers too -* [#715](https://github.com/foosel/OctoPrint/issues/715) - Fixed an error where Event Triggers of type command caused - and exception to be raised due to a misnamed attribute in the code -* [#717](https://github.com/foosel/OctoPrint/issues/717) - Use ``shutil.move`` instead of ``os.rename`` to avoid cross - device renaming issues -* [#752](https://github.com/foosel/OctoPrint/pull/752) - Fix error in event handlers sending multiple gcode commands. -* [#780](https://github.com/foosel/OctoPrint/issues/780) - Always (re)set file position in SD files to 0 so that reprints - work correctly -* [#784](https://github.com/foosel/OctoPrint/pull/784) - Also include ``requirements.txt`` in files packed up for - ``python setup.py sdist`` -* [#330](https://github.com/foosel/OctoPrint/issues/330) - Ping pong sending to fix potential acknowledgement errors. - Also affects [#166](https://github.com/foosel/OctoPrint/issues/166), [#470](https://github.com/foosel/OctoPrint/issues/470) - and [#490](https://github.com/foosel/OctoPrint/issues/490). A big thank you to all people involved in these tickets - in getting to the ground of this. -* [#825](https://github.com/foosel/OctoPrint/issues/825) - Fixed "please visualize" button of large GCODE files -* Various fixes of bugs in newly introduced features and improvements: - * [#625](https://github.com/foosel/OctoPrint/pull/625) - Newly added GCODE files were not being added to the analysis - queue - * [#664](https://github.com/foosel/OctoPrint/issues/664) - Fixed jog controls again - * [#677](https://github.com/foosel/OctoPrint/issues/677) - Fixed extruder offsets not being properly editable in - printer profiles - * [#678](https://github.com/foosel/OctoPrint/issues/678) - SockJS endpoints is now referenced by relative URL - using ``url_for``, should solve any issues with IE11. - * [#683](https://github.com/foosel/OctoPrint/issues/683) - Fixed heated bed option not being properly displayed in - printer profiles - * [#685](https://github.com/foosel/OctoPrint/issues/685) - Quoted file name for Timelapse creation to not make - command hiccup on ``~`` in file name - * [#709](https://github.com/foosel/OctoPrint/issues/709) - Fixed file sending to SD card - * [#714](https://github.com/foosel/OctoPrint/issues/714) - Fixed type validation of printer profiles - * Heating up the heated bed (if present) was not properly configured in CuraEngine plugin - * [#720](https://github.com/foosel/OctoPrint/issues/720) - Fixed translation files not being properly copied over - during install - * [#724](https://github.com/foosel/OctoPrint/issues/724) - Fixed timelapse deletion for timelapses with non-ascii - characters in their name - * [#726](https://github.com/foosel/OctoPrint/issues/726) - Fixed ``babel_refresh`` command - * [#759](https://github.com/foosel/OctoPrint/pull/759) - Properly initialize counter for template plugins of type - "generic" - * [#775](https://github.com/foosel/OctoPrint/pull/775) - Error messages in javascript console show the proper name - of the objects - * [#795](https://github.com/foosel/OctoPrint/issues/795) - Allow adding slicing profiles for unconfigured slicers - * [#809](https://github.com/foosel/OctoPrint/issues/809) - Added proper form validation to printer profile editor - * [#824](https://github.com/foosel/OctoPrint/issues/824) - Settings getting lost when switching between panes in - the settings dialog (fix provided by [#879](https://github.com/foosel/OctoPrint/pull/879)) - * [#892](https://github.com/foosel/OctoPrint/issues/892) - Preselected baudrate is now properly used for auto detected - serial ports - * [#909](https://github.com/foosel/OctoPrint/issues/909) - Fixed Z-Timelapse for Z changes on ``G1`` moves. - * Fixed another instance of a missing `branch` field in version dicts generated by versioneer (compare - [#634](https://github.com/foosel/OctoPrint/pull/634)). Caused an issue when installing from source archive - downloaded from Github. - * [#931](https://github.com/foosel/OctoPrint/issues/931) - Adjusted `octoprint_setuptools` to be compatible to older - versions of setuptools potentially site-wide installed on hosts. - * [#942](https://github.com/foosel/OctoPrint/issues/942) - Settings can now be saved again after installing a new - plugin. Plugins must not use `super` anymore to call parent implementation of `SettingsPlugin.on_settings_save` but - should instead switch to `SettingsPlugin.on_settings_save(self, ...)`. Settings API will capture related - `TypeErrors` and log a big warning to the log file indicating which plugin caused the problem and needs to be - updated. Also updated all bundled plugins accordingly. - * Software Update: Don't persist more check data than necessary in the configuration. Solves an issue where persisted - information overrode updated check configuration reported by plugins, leading to a "an update is available" loop. - An auto-migration function was added that should remove the redundant data. -* Various fixes without tickets: - * GCODE viewer now doesn't stumble over completely extrusionless GCODE files - * Do not deliver the API key on settings API unless user has admin rights - * Don't hiccup on slic3r filament_diameter comments in GCODE generated for multi extruder setups - * Color code successful or failed print results directly in file list, not just after a reload - * Changing Timelapse post roll activates save button - * Timelapse post roll is loaded properly from config - * Handling of files on the printer's SD card contained in folders now works correctly - * Don't display a "Disconnected" screen when trying to download a timelapse in Firefox - * Fixed handling of SD card files in folders - * Fixed refreshing of timelapse file list upon finished rendering of a new one - * Fixed ``/api/printer`` which wasn't adapter yet to new internal offset data model - * Made initial connection to printer a bit more responsive: Having to wait for the first serial timeout before sending - the first ``M105`` even when not waiting for seeing a "start" caused unnecessary wait times for reaching the - "Operational" state. - * Log cancelled prints only once (thanks to @imrahil for the headsup) - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.1.2...1.2.0) - * Release Candidates: - * [RC1](https://github.com/foosel/OctoPrint/releases/tag/1.2.0-rc1) - * [RC2](https://github.com/foosel/OctoPrint/releases/tag/1.2.0-rc2) - * [RC3](https://github.com/foosel/OctoPrint/releases/tag/1.2.0-rc3) - -## 1.1.2 (2015-03-23) - -### Improvements - -* Added deletion of `*.pyc` files to `python setup.py clean` command, should help tremendously when switching branches (backported - from [9e014eb](https://github.com/foosel/OctoPrint/commit/9e014eba1feffde11ed0601d9c911b8cac9f3fb0)) -* Increased default communication and connection timeouts -* [#706](https://github.com/foosel/OctoPrint/issues/706) - Do not truncate error reported from printer - -### Bug Fixes - -* [#539](https://github.com/foosel/OctoPrint/issues/539) - Limit maximum number of tools, sanity check tool numbers in - GCODE files against upper limit and refuse to create 10000 tools due to weird slicers. (backported from `devel`) -* [#634](https://github.com/foosel/OctoPrint/pull/634) - Fixed missing `branch` fields in version dicts generated - by versioneer -* [#679](https://github.com/foosel/OctoPrint/issues/679) - Fix error where API state is requested and printer is offline - (backport of [619fe9a](https://github.com/foosel/OctoPrint/commit/619fe9a0e78826bd1524b235a910156439bcb6d7)). -* [#719](https://github.com/foosel/OctoPrint/issues/719) - Properly center print bed in GCODE viewer -* [#780](https://github.com/foosel/OctoPrint/issues/780) - Always (re)set file position in SD files to 0 so that reprints - work correctly (backported from ``devel``) -* [#801](https://github.com/foosel/OctoPrint/issues/801) - Fixed setting of bed temperature offset -* [IRC] - Don't hiccup on slic3r ``filament_diameter`` comments generated for multi extruder setups -* [ML] - Fixed relative URL to SockJS endpoint, wasn't yet using the proper base url -* [unreported] & [#698](https://github.com/foosel/OctoPrint/issues/698) - Generated URLs now take X-Forwarded-Host header - sent by proxies into account for included host and port, also fixed [#698](https://github.com/foosel/OctoPrint/issues/698) - introduced by this -* [unreported] Fixed a bug causing gcodeInterpreter to hiccup on GCODES containing invalid coordinates such as Xnan or - Yinf (backported from `devel`) -* Small fixes for timelapse creation: - - [#344](https://github.com/foosel/OctoPrint/issues/344) - Made timelapses capable of coping with missing captures in between by decrementing the image counter again if there - was an error fetching the latest image from the snapshot URL (backport of [1a7a468](https://github.com/foosel/OctoPrint/commit/1a7a468eb65fdf2a13b4c7a7723280e822c9c34b) - and [bf9d5ef](https://github.com/foosel/OctoPrint/commit/bf9d5efe43a1e57aacd8512125082ddca06b4efc)) - - [#693](https://github.com/foosel/OctoPrint/issues/693) - Try not to capture an image if image counter is still unset - - [unreported] Synchronize image counter decrementing as well as incrementing to prevent rare race conditions when generating the - image file names - -([Commits](https://github.com/foosel/OctoPrint/compare/1.1.1...1.1.2)) - -## 1.1.1 (2014-10-27) - -### Improvements - -* The API is now enabled by default and the API key -- if not yet set -- will be automatically generated on first - server start and written back into ``config.yaml`` -* Event subscriptions are now enabled by default (it was an accident that they weren't) -* Generate the key used for session hashing individually for each server instance -* Generate the salt used for hashing user passwords individually for each server instance - -### Bug Fixes - -* [#580](https://github.com/foosel/OctoPrint/issues/580) - Properly unset job data when instructed so by callers -* [#604](https://github.com/foosel/OctoPrint/issues/604) - Properly initialize settings basedir on server startup -* [IRC] Also allow downloading .g files via Tornado - -([Commits](https://github.com/foosel/OctoPrint/compare/1.1.0...1.1.1)) - -## 1.1.0 (2014-09-03) - -### New Features - -* New REST API, including User API Keys additionally to the global API key. Please note that **this will break existing - API clients** as it replaces the old API (same endpoint). You can find the documentation of the new API at - [docs.octoprint.org](http://docs.octoprint.org/en/1.1.0/api/index.html). -* New Event structure allows more flexibility regarding payload data, configuration files will be migrated automatically. - You can find the documentation of the new event format and its usage at [docs.octoprint.org](http://docs.octoprint.org/en/1.1.0/events/index.html). -* Support for multi extruder setups. With this OctoPrint now in theory supports an unlimited amount of extruders, however - for now it's artificially limited to 9. -* Log files can be accessed from within the browser via the Settings dialog ([#361](https://github.com/foosel/OctoPrint/pull/361)) -* Timelapses can now have a post-roll duration configured which will be rendered into the video too to not let it - end so abruptly ([#384](https://github.com/foosel/OctoPrint/issues/384)) -* The terminal tab now has a command history ([#388](https://github.com/foosel/OctoPrint/pull/388)) - -### Improvements - -* Stopping the application via Ctrl-C produces a less scary message ([#277](https://github.com/foosel/OctoPrint/pull/277)) -* Webcam stream is disabled when control tab is not in focus, reduces bandwidth ([#316](https://github.com/foosel/OctoPrint/issues/316)) -* M and G commands entered in Terminal tab are automatically converted to uppercase -* GCODE viewer now only loads automatically if GCODE file size is beneath certain threshold (different ones for desktop - and mobile devices), only actually loads file if user acknowledges that this might be too much for his browser -* Added time needed for printing file to PrintDone event's payload ([#333](https://github.com/foosel/OctoPrint/issues/333)) -* Also provide the filename (basename without the path) in print events -* Support for circular beds in the GCODE viewer ([#407](https://github.com/foosel/OctoPrint/pull/407)) -* The dimensions of the print bed can now be configured via the Settings ([#396](https://github.com/foosel/OctoPrint/pull/396)) -* Target temperature reporting format of Repetier Firmware is now supported as well ([360](https://github.com/foosel/OctoPrint/issues/360)) -* Version tracking now based on git tagging and [versioneer](https://github.com/warner/python-versioneer/). Version number, - git commit and branch get reported in the format `--g ( branch)`, - e.g. `1.2.0-dev-172-ga48b5de (devel branch)`. -* Made "Center viewport on model" and "Zoom in on model" in the GCODE viewer automatically deselect and de-apply if - viewport gets manipulated by the user ([#398](https://github.com/foosel/OctoPrint/issues/398)) -* GCODE viewer now interprets inverted axes for printer control and mirrors print bed accordingly ([#431](https://github.com/foosel/OctoPrint/issues/431)) -* Added `clean` command to `setup.py`, removes old build artifacts (mostly interesting for developers) -* Added version resource on API which reports application and API version -* Made the navbar static instead of fixed to improve usability on mobile devices ([#257](https://github.com/foosel/OctoPrint/issues/257)) -* Switch to password field upon enter in username field, submit login form upon enter in password field -* Changed default path to OctoPrint executable in included init-script to `/usr/local/bin/octoprint` (the default when - installing via `python setup.py install`) - -### Bug Fixes - -* Properly calculate time deltas (forgot to factor in days) -* [#35](https://github.com/foosel/OctoPrint/issues/35) - GCODE viewer has been modularized, options are now functional -* [#337](https://github.com/foosel/OctoPrint/issues/337) - Also recognize `--iknowwhatimdoing` when running as daemon -* [#357](https://github.com/foosel/OctoPrint/issues/357) - Do not run GCODE analyzer when a print is ongoing -* [#381](https://github.com/foosel/OctoPrint/issues/381) - Only list those SD files that have an ASCII filename -* Fixed a race condition that could occur when pressing "Print" (File not opened yet, but attempt to read from it) -* [#398](https://github.com/foosel/OctoPrint/issues/398) - Fixed interfering options in GCODE viewer -* [#399](https://github.com/foosel/OctoPrint/issues/399) & [360](https://github.com/foosel/OctoPrint/issues/360) - Leave - bed temperature unset when not detected (instead of dying a horrible death) -* [#492](https://github.com/foosel/OctoPrint/issues/492) - Fixed a race condition which could lead to an attempt to read - from an already closed serial port, causing an error to be displayed to the user -* [#257](https://github.com/foosel/OctoPrint/issues/257) - Logging in on mobile devices should now work -* [#476](https://github.com/foosel/OctoPrint/issues/476) - Also update the metadata correctly when an analysis finishes -* Various fixes of bugs in newly introduced features and improvements: - - [#314](https://github.com/foosel/OctoPrint/issues/314) - Use G28 for homing (G1 was copy and paste error) - - [#317](https://github.com/foosel/OctoPrint/issues/317) - Fixed "load and print" function - - [#326](https://github.com/foosel/OctoPrint/issues/326) - Fixed refresh of SD file list - - [#338](https://github.com/foosel/OctoPrint/issues/338) - Refetch file list when deleting a file - - [#339](https://github.com/foosel/OctoPrint/issues/339) - More error resilience when handling temperature offset data from the backend - - [#345](https://github.com/foosel/OctoPrint/issues/345) - Also recognize such temperature reports that do not contain a `T:` but a `T0:` - - [#377](https://github.com/foosel/OctoPrint/pull/377) - URLs in API examples fixed - - [#378](https://github.com/foosel/OctoPrint/pull/378) - Fixed crash of API call when `getStartTime()` returns None - - [#379](https://github.com/foosel/OctoPrint/pull/379) - Corrected response code for connection success - - [#414](https://github.com/foosel/OctoPrint/pull/414) - Fix style attribute for Actual column header - -([Commits](https://github.com/foosel/OctoPrint/compare/1.0.0...1.1.0)) - -## 1.0.0 (2014-06-22) - -First release with new versioning scheme. +For even older changes, please refer to [the Github releases page](https://github.com/foosel/OctoPrint/releases). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 861215f4d..675b60b4d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,7 +27,7 @@ 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. -![Ticket flow chart](https://i.imgur.com/SmU7iCJ.png) +![Ticket flow chart](https://i.imgur.com/cw19qHX.png) - **[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) @@ -36,14 +36,14 @@ nothing but ticket management. - 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 - [community forum at discourse.octoprint.org](https://discourse.octoprint.org) for + [community forum at community.octoprint.org](https://community.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`). + changes to the plugin system, please get in touch on the + [community forum at community.octoprint.org](https://community.octoprint.org/c/development). - 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 [community forum at discourse.octoprint.org](https://discourse.octoprint.org) instead. + Consult the [community forum at community.octoprint.org](https://community.octoprint.org/c/support) 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. @@ -53,7 +53,7 @@ into one ticket: One ticket per bug, request, brainstorming thread please. > 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 +> `[Request]` 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. @@ -75,7 +75,7 @@ following section *completely* and also follow the instructions in the **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). + [community forum](https://community.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 @@ -126,7 +126,7 @@ following section *completely* and also follow the instructions in the 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) +If in doubt about any of the above - get in touch on the [community forum](https://community.octoprint.org) instead of opening a ticket here. If you are actually running into a bug, we'll figure it out together there. @@ -153,7 +153,7 @@ plugins and not unofficial OctoPrint versions). Do not seek support here ("I need help with ...", "I have a question ..."), that belongs on the community forum at -discourse.octoprint.org, NOT here. +community.octoprint.org, NOT here. Mark requests with a "[Request]" prefix in the title please. For bug reports fully fill out the bug reporting template (if you don't know @@ -275,11 +275,11 @@ all requested information or your ticket will be closed. ### Where can I find which version and branch I'm on? -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). +Please refer to [this FAQ entry](https://community.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? -Please refer to [this FAQ entry](https://discourse.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299/1). +Please refer to [this FAQ entry](https://community.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299/1). ### Where can I find my browser's error console? @@ -301,7 +301,8 @@ the documentation. the discussion going on how best to solve *this* in OctoPrint's plugin system - maybe that's the actual PR you have been waiting for to contribute :) 2. If you plan to make **any large or otherwise disruptive changes to the - code or appearance, please open a "Brainstorming" ticket first** so + code or appearance, please get in touch on the + [forums](https://community.octoprint.org/c/development)** first so that we can determine if it's a good time for your specific pull request. It might be that we're currently in the process of making heavy changes to the code locations you'd target as well, or your @@ -311,7 +312,8 @@ the documentation. 3. Create your pull request **from a custom branch** on your end (e.g. `dev/myNewFeature`)[1]. 4. Create your pull request **only against the `maintenance` or `devel` branch**: - * if it's a bug fix for a bug in the current stable version: `maintenance` branch + * if it's a bug fix for a bug in the current stable version, an improvement of existing functionality or a + *small* new feature (e.g. a new hook, a new config flag, ...): `maintenance` branch * otherwise: `devel` branch 5. Create **one pull request per feature/bug fix**. 6. Make sure there are **only relevant changes** included in your PR. No @@ -472,7 +474,9 @@ the local version identifier to allow for an exact determination of the active c * 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 + * 2018-03-29: "Where to find version numbers" is now located on the FAQ + * 2018-10-18: Allow PRs against `maintenance` branch for improvements and small + new features, suggest getting in touch on the forum for larger changes ## Footnotes * [1] - If you are wondering why, the problem is that anything that you add diff --git a/README.md b/README.md index b44dfe19e..1758d00ff 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,21 @@ # OctoPrint -[![GitHub version](https://badge.fury.io/gh/foosel%2FOctoPrint.svg)](https://badge.fury.io/gh/foosel%2FOctoPrint) + +![GitHub release](https://img.shields.io/github/release/foosel/OctoPrint.svg?colorB=brightgreen) +[![Travis build status](https://img.shields.io/travis/foosel/OctoPrint.svg)](https://travis-ci.org/foosel/OctoPrint) +[![Discourse topics](https://img.shields.io/discourse/https/community.octoprint.org/users.svg)](https://community.octoprint.org) +[![IRC](https://img.shields.io/badge/chat-on%20irc-brightgreen.svg)](https://chat.octoprint.org) +[![Twitter Follow](https://img.shields.io/twitter/follow/OctoPrint3d.svg?style=social&label=Follow)](https://twitter.com/OctoPrint3d) + 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](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 community forum is available at [community.octoprint.org](https://community.octoprint.org/?utm_source=github&utm_medium=readme). + +The official IRC channel is [#octoprint on freenode](https://chat.octoprint.org). Its logs can be found [here](https://freenode.logbot.info/octoprint). The FAQ can be accessed by following [faq.octoprint.org](https://faq.octoprint.org/?utm_source=github&utm_medium=readme). @@ -24,7 +32,7 @@ You are currently looking at the source code repository of OctoPrint. If you alr (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 join -[the community forum at discourse.octoprint.org](https://discourse.octoprint.org) where there are other active users who might be +[the community forum at community.octoprint.org](https://community.octoprint.org) where there are other active users who might be able to help you with any questions you might have. ## Contributing @@ -32,7 +40,7 @@ able to help you with any questions you might have. Contributions of all kinds are welcome, not only in the form of code but also with regards to the [official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), debugging help in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on -[the community forum at discourse.octoprint.org](https://discourse.octoprint.org) +[the community forum at community.octoprint.org](https://community.octoprint.org) and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme). If you think something is bad about OctoPrint or its documentation the way it is, please help @@ -53,7 +61,7 @@ which is a custom SD card image that includes OctoPrint plus dependencies. The generic steps that should basically be done regardless of operating system and runtime environment are the following (as *regular user*, please keep your hands *off* of the `sudo` command here!) - this assumes -you already have Python 2.7, pip and virtualenv set up on your system: +you already have Python 2.7, 3.6 or 3.7, pip and virtualenv set up on your system: 1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git` 2. Change into the OctoPrint folder: `cd OctoPrint` @@ -75,7 +83,7 @@ OctoPrint via `pip`: You should do this every time after pulling from the repository, since the dependencies may have changed. -OctoPrint currently only supports Python 2.7. +OctoPrint currently supports Python 2.7, 3.6 and 3.7. ## Usage diff --git a/SUPPORTERS.md b/SUPPORTERS.md index 6159d8f79..aae0022bb 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -1,58 +1,57 @@ # Supporters Development of this version of OctoPrint wouldn't have been possible without -[financial support by the community](http://octoprint.org/support-octoprint/) - +[the financial support by the community](https://octoprint.org/support-octoprint/) - thanks to everyone who contributed! ## Patreon Patrons + * Andre Bubel * Andrew Moorby * Arnljot Arntsen * Boris Hussein * Brad Jackson - * Brian E. Tyler * Christian Petropolis + * Christian Wolf * COLLE+McVOY * D Brian Kimmel * DeltaMaker 3D Printers * E3D BigBox + * Eric Betts + * Eric Slape * Ernesto Martinez - * F. Kunsmann * Frank Sander - * Gary Deen - * günter weber - * James Seigel - * Jeff Moe + * George Robles + * Jared Go * Jeff Renfer * Jefferson Hunt * Jeremiah Avery + * Joseph Payne * Josh Daniels + * Joshua Wills + * Justin Kaufman * Kaile Riser * Kale Stedman * Kazuhiro Ogura - * Kodama Inc. + * LA 3D Printer Repair + * Lewis Newby * LulzBot® * Makespace Madrid * Mark Walker - * Martin Beattie * Michael Aumock * Miles Flavel - * mitchell hirsch - * Mohammed khorakiwala - * Noe Ruiz + * Mosaic Manufacturing * Patrick McGinnis - * Peter Schmehl + * Prof Yuh Wen Chen * Randy C. Will * Robert Gusek * Roger Strolz - * Roy Cortes * Samer Najia * Simon Hallam * Stefan Krister - * Stephane Schittly * Sven Mueller - * Symbiotic Devices * Thomas Hatley + * Timothy D Hoogland * Trent Shumay -and 1233 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! \ No newline at end of file +and 1446 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! \ No newline at end of file diff --git a/docs/api/apps.rst b/docs/api/apps.rst deleted file mode 100644 index 46ee73c8c..000000000 --- a/docs/api/apps.rst +++ /dev/null @@ -1,170 +0,0 @@ -.. _sec-api-apps: - -**** -Apps -**** - -.. contents:: - -.. _sec-api-apps-sessionkey: - -Session Keys -============ - -OctoPrint offers a special API key type for apps to use, the so called App Session Key. These keys have a time based -validity and are generated by OctoPrint for requesting apps. - -Obtaining those keys is based on a handshake procedure backed by cryptographic signatures using RSA. OctoPrint needs to -be aware of apps and their associated public keys (this can be achieved either via entries in ``config.yaml`` or by -installing app specific plugins which implement the ``AppPlugin`` type). - -Apps can be registered within OctoPrint via ``config.yaml`` by adding them to the ``api`` > ``apps`` section, using the -application's id concatenated with its version as key, with the public key provided as item ``pubkey`` (stripped of the -``BEGIN RSA PUBLIC KEY`` and ``END RSA PUBLIC KEY`` separators and also newlines) and optionally also whether the app is -enabled or not (defaults to enabled, so can be left out if it's not to be set to disabled explicitly). - -Example: - -.. sourcecode:: yaml - - api: - apps: - "com.example.my_octoprint_app:0.9": - pubkey: MEgCQQDYkr5Fv/YXK5ZL1uwRN4A61IagZaYLGqJ5JJGFo8wDrmpAMRqE9kK4+5hIDblC5DzfEr5oP7OA3tRO48Rf5yInAgMBAAE= - enabled: false - "com.example.my_octoprint_app:1.0": - pubkey: MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4osvb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE= - -In the example, the app ``com.example.my_octoprint_app`` in version 0.9 has been disabled (e.g. due to the key having -leaked) whereas version 1.0 is fully registered with OctoPrint and may verify app session keys. - - -.. _sec-api-apps-sessionkey-workflow: - -Workflow --------- - -Apps perform the handshake by first requesting a temporary key with very limited validity, -then sending a message back to OctoPrint containing their id, version, the temporary key and a signature created with their -private key over these three pieces of data. OctoPrint then tries to verify the signature and if successful unlocks the -key to be used as a fully recognized API key. - -For performing the handshake a special API exists within OctoPrint for which no API key is needed which is described below. - -.. _sec-api-apps-sessionkey-get: - -Obtaining a temporary session key ---------------------------------- - -.. http:get:: /apps/auth - - Retrieve a temporary session key with a minimum validity. It can only be used as a proper API key after having been - :ref:`verified `. - - Returns the temporary session key and the timestamp until it's valid. - - **Example**: - - .. sourcecode:: http - - GET /apps/auth HTTP/1.1 - Host: example.com - - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - { - "unverifiedKey": "F43A844750F74AD080FE9F438D47B33C", - "validUntil": 1416220357.011 - } - - :statuscode 200: No error - -.. _sec-api-apps-sessionkey-verify: - -Verifying a temporary session key ---------------------------------- - -.. http:post:: /apps/auth - - Verify a formerly :ref:`retrieved ` temporary session key by providing credentials and a - cryptographic signature over these credentials and the temporary key. - - Returns the now verified session key and the new validity. - - **Example**: - - .. sourcecode:: http - - POST /apps/auth HTTP/1.1 - Host: example.com - Content-Type: application/json - - { - "appid": "com.example.my_octoprint_app", - "appversion": "1.0", - "key": "F43A844750F74AD080FE9F438D47B33C", - "_sig": "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w==" - } - - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - { - "key": "F43A844750F74AD080FE9F438D47B33C", - "validUntil": 1416227497.011 - } - -.. _sec-api-apps-sessionkey-signature: - -Creating the signature ----------------------- - -The signature is created by concatenating the ``appid``, ``appversion`` and ``key`` fields, separated by a ``:`` (colon), -signing the result with the app's private key using SHA-1 and then BASE64-encoding the result, stripping newlines. - -Example for signature generation using Python and the `Python RSA library `_: - -.. sourcecode:: python - - import base64 - import rsa - - appid = "com.example.my_octoprint_app" - version = "1.0" - unverified_key = "F43A844750F74AD080FE9F438D47B33C" - message_to_sign = appid + ":" + version + ":" + unverified_key - // => "com.example.my_octoprint_app:1.0:F43A844750F74AD080FE9F438D47B33C" - - private_key = rsa.PrivateKey.load_pkcs1("...") - signature = base64.encodestring(rsa.sign(message_to_sign, private_key, "SHA-1")).replace("\n", "") - // => "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w==" - - -.. _sec-api-apps-sessionkey-testing: - -Testing your implementation ---------------------------- - -If you want to use app session keys, here is the key pair with which the above examples were created, in order for you -to verify your signature implementation:: - - -----BEGIN RSA PRIVATE KEY----- - MIIBPQIBAAJBAIhZ+Ls1zxtyd9kkm0DprhHIwL6woGUw5vbk5U00Hgva/ROIY7va - NUpHiiy9vijO2VtFbkaR2JjRPYslx8Ni+QkCAwEAAQJARK4lFo+FEcs3yR2iQjEy - p+yaAbNQJ4hZXlVvltLAYICzOM3kyKx53/eKU59NjskLz9q6QxfleymYPWAgl4NW - fQIjAJVH8MjwNcaAquTM9z2OiFi3OC8WgaKOi5W/T+r2+B70wG8CHwDp08dqOZ/u - xcBiy4Wzpcme9bckqoVuS3gWMm+YqgcCIwCMFU07kkY0NyumtzxPdIA4F/7OGSWf - IHqWFEfvasAddHlbAh8A5UgkB3Zf7Bt+7aFSBnlvve6FWm/XDPL12xYztYgrAiIa - W3miN6FjIm+8TDowrk+nyYXG2GZefeY7QXOjYr6tlDn0 - -----END RSA PRIVATE KEY----- - - -----BEGIN RSA PUBLIC KEY----- - MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4os - vb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE= - -----END RSA PUBLIC KEY----- - diff --git a/docs/api/connection.rst b/docs/api/connection.rst index 721e92cac..2a0037b9a 100644 --- a/docs/api/connection.rst +++ b/docs/api/connection.rst @@ -59,7 +59,7 @@ Issue a connection command Issue a connection command. Currently available command are: connect - Instructs OctoPrint to connect to the printer. Additional parameters are: + Instructs OctoPrint to connect or, if already connected, reconnect to the printer. Additional parameters are: * ``port``: Optional, specific port to connect to. If not set the current ``portPreference`` will be used, or if no preference is available auto detection will be attempted. diff --git a/docs/api/general.rst b/docs/api/general.rst index 4232a96c9..edc54ed78 100644 --- a/docs/api/general.rst +++ b/docs/api/general.rst @@ -12,8 +12,11 @@ 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 `. -Users are able to generate and revoke their custom API key via the "Change password" dialog. +configured one, a user specific one if "Access Control" is enabled or an app and user specific one as generated +by the authorization workflow implemented by the bundled :ref:`Application Keys Plugin ` (since 1.3.10). + +Clients are advised to implement the :ref:`Application Keys Plugin workflow ` first and +fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used. The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g. @@ -23,7 +26,7 @@ The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g. Host: example.com X-Api-Key: abcdef... -If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`401`. +If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`403`. For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g. @@ -120,3 +123,94 @@ If CORS is not enabled you will get errors like the following:: XMLHttpRequest cannot load http://localhost:8081/api/files. No 'Access-Control-Allow-Origin' header is present on the requested resource. +.. _sec-api-general-login: + +Login +===== + +.. http:post:: /api/login + + Creates a login session or retrieves information about the currently existing session ("passive login"). + + Can be used in one of two ways: to login a user via username and password and create a persistent session (usually + from a UI in the browser), or to retrieve information about the active user (from an existing session or an API key) + via the ``passive`` flag. + + Will return a :http:statuscode:`200` with a :ref:`login response ` on successful + login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`401` in + case of a username/password mismatch or unknown user and a :http:statuscode:`403` in case of a deactivated account. + + :json passive: If present, performs a passive login only, returning information about the current user that's + active either through an existing session or the used API key + :json user: (active login only) Username + :json pass: (active login only) Password + :json remember: (active login only) Whether to set a "remember me" cookie on the session + :status 200: Successful login + :status 401: Username/password mismatch or unknown user + :status 403: Deactivated account + +.. _sec-api-general-logout: + +Logout +====== + +.. http:post:: /api/logout + + Ends the current login session of the current user. + + Only makes sense in the context of browser based workflows. + + Will return a :http:statuscode:`204`. + + :status 204: No error + +.. _sec-api-general-datamodel: + +Data model +========== + +.. _sec-api-general-datamodel-login: + +Login response +-------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``name`` + - 1 + - string + - the user's name/id + * - ``active`` + - 1 + - boolean + - Whether the user's account is active or not + * - ``admin`` + - 1 + - boolean + - Whether the user has admin rights or not + * - ``user`` + - 1 + - boolean + - Whether the user has user rights or not (always ``true``) + * - ``apikey`` + - 1 + - string or None + - The user's API key, if set + * - ``settings`` + - 1 + - dict + - The user's settings, if any + * - ``session`` + - 1 + - string + - The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API `. + * - ``_is_external_client`` + - 1 + - boolean + - Whether the client that made the request got detected as external from the local network or not. diff --git a/docs/api/printer.rst b/docs/api/printer.rst index 98f4ccbff..1c8483a55 100644 --- a/docs/api/printer.rst +++ b/docs/api/printer.rst @@ -219,7 +219,7 @@ Issue a print head command axes values are relative amounts) or to absolute position (provided axes values are coordinates) * ``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. + interpreted as an integer signifying the speed in mm/min, to append to the command. home Homes the print head in all of the given axes. Additional parameters are: @@ -362,6 +362,8 @@ Issue a tool command Extrudes the given amount of filament from the currently selected tool. Additional parameters: * ``amount``: The amount of filament to extrude in mm. May be negative to retract. + * ``speed``: Optional. Speed at which to extrude. If not provided, maximum speed for E axis from printer + profile will be used. Otherwise interpreted as an integer signifying the speed in mm/min, to append to the command. flowrate Changes the flow rate factor to apply to extrusion of the tool. diff --git a/docs/api/push.rst b/docs/api/push.rst index 7d8813867..87e40bf5d 100644 --- a/docs/api/push.rst +++ b/docs/api/push.rst @@ -47,23 +47,41 @@ Clients must ignore any unknown messages. The data model of the attached payloads is described further below. -OctoPrint's SockJS socket also accepts one command from the client to the server, -the ``throttle`` command. Usually, OctoPrint will push the general state update -in the ``current`` message twice per second. For some clients that might still -be too fast, so they can signal a different factor to OctoPrint utilizing the -``throttle`` message. OctoPrint expects a single integer here which represents -the multiplier for the base rate limit of one message every 500ms. A value of -1 hence will produce the default behaviour of getting every update. A value of -2 will set the rate limit to maximally one message every 1s, 3 to maximally one -message every 1.5s and so on. +OctoPrint's SockJS socket also accepts two commands from the client to the server. -Example for a ``throttle`` client-server-message: + * ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an + existing user session with the socket. That is of special importance to receive + any kind of messages if the bundled :ref:`Forcelogin Plugin ` is enabled + (as it is by default), since it will prevent any kind of status messages to be sent to connected unauthenticated + clients. -.. sourcecode:: javascript + The ``auth`` message expects the user id of the user to authenticate followed by ``:`` and a session key to be + obtained from the successful payload of a :ref:`(passive or active) login via the API `. - { - "throttle": 2 - } + Example for a ``auth`` client-server-message: + + .. sourcecode:: javascript + + { + "auth": "someuser:LGZ0trf8By" + } + + * ``throttle``: Usually, OctoPrint will push the general state update + in the ``current`` message twice per second. For some clients that might still + be too fast, so they can signal a different factor to OctoPrint utilizing the + ``throttle`` message. OctoPrint expects a single integer here which represents + the multiplier for the base rate limit of one message every 500ms. A value of + 1 hence will produce the default behaviour of getting every update. A value of + 2 will set the rate limit to maximally one message every 1s, 3 to maximally one + message every 1.5s and so on. + + Example for a ``throttle`` client-server-message: + + .. sourcecode:: javascript + + { + "throttle": 2 + } .. _sec-api-push-datamodel: diff --git a/docs/api/settings.rst b/docs/api/settings.rst index 466cb839a..b4597ef94 100644 --- a/docs/api/settings.rst +++ b/docs/api/settings.rst @@ -86,6 +86,266 @@ Regenerate the system wide API key :status 200: No error :status 403: No admin rights +.. _sec-api-settings-fetchtemplaatedata: + +Fetch template data +=================== + +.. http:get:: /api/settings/templates + + Fetch data (currently only the sorting order) of all registered template components in the system. + + Use this to get a full list of the identifiers of all UI components provided either by core OctoPrint or any + currently active plugins. + + Example: + + .. sourcecode:: http + + GET /api/settings/templates HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "order": { + "about": [ + { + "id": "about", + "name": "About OctoPrint" + }, + { + "id": "supporters", + "name": "Supporters" + }, + { + "id": "authors", + "name": "Authors" + }, + { + "id": "changelog", + "name": "Changelog" + }, + { + "id": "license", + "name": "OctoPrint License" + }, + { + "id": "thirdparty", + "name": "Third Party Licenses" + }, + { + "id": "plugin_pluginmanager", + "name": "Plugin Licenses", + "plugin_id": "pluginmanager", + "plugin_name": "Plugin Manager" + } + ], + "generic": [ + { + "id": "plugin_announcements", + "name": "plugin_announcements", + "plugin_id": "announcements", + "plugin_name": "Announcement Plugin" + } + ], + "navbar": [ + { + "id": "settings", + "name": "settings" + }, + { + "id": "systemmenu", + "name": "systemmenu" + }, + { + "id": "plugin_announcements", + "name": "plugin_announcements", + "plugin_id": "announcements", + "plugin_name": "Announcement Plugin" + }, + { + "id": "login", + "name": "login" + } + ], + "plugin_pluginmanager_about_thirdparty": [], + "settings": [ + { + "id": "section_printer", + "name": "Printer" + }, + { + "id": "serial", + "name": "Serial Connection" + }, + { + "id": "printerprofiles", + "name": "Printer Profiles" + }, + { + "id": "temperatures", + "name": "Temperatures" + }, + { + "id": "terminalfilters", + "name": "Terminal Filters" + }, + { + "id": "gcodescripts", + "name": "GCODE Scripts" + }, + { + "id": "section_features", + "name": "Features" + }, + { + "id": "features", + "name": "Features" + }, + { + "id": "webcam", + "name": "Webcam & Timelapse" + }, + { + "id": "accesscontrol", + "name": "Access Control" + }, + { + "id": "gcodevisualizer", + "name": "GCODE Visualizer" + }, + { + "id": "api", + "name": "API" + }, + { + "id": "section_octoprint", + "name": "OctoPrint" + }, + { + "id": "server", + "name": "Server" + }, + { + "id": "folders", + "name": "Folders" + }, + { + "id": "appearance", + "name": "Appearance" + }, + { + "id": "plugin_logging", + "name": "Logging", + "plugin_id": "logging", + "plugin_name": "Logging" + }, + { + "id": "plugin_pluginmanager", + "name": "Plugin Manager", + "plugin_id": "pluginmanager", + "plugin_name": "Plugin Manager" + }, + { + "id": "plugin_softwareupdate", + "name": "Software Update", + "plugin_id": "softwareupdate", + "plugin_name": "Software Update" + }, + { + "id": "plugin_announcements", + "name": "Announcements", + "plugin_id": "announcements", + "plugin_name": "Announcement Plugin" + }, + { + "id": "section_plugins", + "name": "Plugins" + }, + { + "id": "plugin_action_command_prompt", + "name": "Action Command Prompt", + "plugin_id": "action_command_prompt", + "plugin_name": "Action Command Prompt Support" + }, + { + "id": "plugin_curalegacy", + "name": "Cura Legacy", + "plugin_id": "curalegacy", + "plugin_name": "Cura Legacy" + } + ], + "sidebar": [ + { + "id": "plugin_printer_safety_check", + "name": "Printer Safety Warning", + "plugin_id": "printer_safety_check", + "plugin_name": "Printer Safety Check" + }, + { + "id": "connection", + "name": "Connection" + }, + { + "id": "state", + "name": "State" + }, + { + "id": "files", + "name": "Files" + } + ], + "tab": [ + { + "id": "temperature", + "name": "Temperature" + }, + { + "id": "control", + "name": "Control" + }, + { + "id": "gcodeviewer", + "name": "GCode Viewer" + }, + { + "id": "terminal", + "name": "Terminal" + }, + { + "id": "timelapse", + "name": "Timelapse" + } + ], + "usersettings": [ + { + "id": "access", + "name": "Access" + }, + { + "id": "interface", + "name": "Interface" + } + ], + "wizard": [] + } + } + + Requires admin rights. + + .. warning:: + + This API endpoint is in beta. Things might change. If you happen to want to develop against it, you should drop + me an email to make sure I can give you a heads-up when something changes in an backwards incompatible way. + + :status 200: No error + :status 403: No admin rights + .. _sec-api-settings-datamodel: Data model @@ -136,7 +396,7 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted: - * - ``feature.sdSupport`` - - * - ``feature.sdReleativePath`` + * - ``feature.sdRelativePath`` - * - ``feature.sdAlwaysAvailable`` - diff --git a/docs/api/slicing.rst b/docs/api/slicing.rst index 129653171..c49cb4cd5 100644 --- a/docs/api/slicing.rst +++ b/docs/api/slicing.rst @@ -42,22 +42,22 @@ List All Slicers and Slicing Profiles Content-Type: application/json { - "cura": { - "key": "cura", - "displayName": "CuraEngine", + "curalegacy": { + "key": "curalegacy", + "displayName": "Cura Legacy", "default": true, "profiles": { "high_quality": { "key": "high_quality", "displayName": "High Quality", "default": false, - "resource": "http://example.com/api/slicing/cura/profiles/high_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality" }, "medium_quality": { "key": "medium_quality", "displayName": "Medium Quality", "default": true, - "resource": "http://example.com/api/slicing/cura/profiles/medium_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality" } } } @@ -81,7 +81,7 @@ List Slicing Profiles of a Specific Slicer .. sourcecode:: http - GET /api/slicing/cura/profiles HTTP/1.1 + GET /api/slicing/curalegacy/profiles HTTP/1.1 Host: example.com X-Api-Key: abcdef... @@ -95,13 +95,13 @@ List Slicing Profiles of a Specific Slicer "key": "high_quality", "displayName": "High Quality", "default": false, - "resource": "http://example.com/api/slicing/cura/profiles/high_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality" }, "medium_quality": { "key": "medium_quality", "displayName": "Medium Quality", "default": true, - "resource": "http://example.com/api/slicing/cura/profiles/medium_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality" } } @@ -125,7 +125,7 @@ Retrieve Specific Profile .. sourcecode:: http - GET /api/slicing/cura/profiles/quick_test HTTP/1.1 + GET /api/slicing/curalegacy/profiles/quick_test HTTP/1.1 Host: example.com X-Api-Key: abcdef... @@ -137,7 +137,7 @@ Retrieve Specific Profile { "displayName": "Just a test", "description": "This is just a test", - "resource": "http://example.com/api/slicing/cura/profiles/quick_test", + "resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test", "data": { "bottom_layer_speed": 20.0, "bottom_thickness": 0.3, @@ -174,14 +174,14 @@ Add Slicing Profile .. sourcecode:: http - PUT /api/slicing/cura/profiles/quick_test HTTP/1.1 + PUT /api/slicing/curalegacy/profiles/quick_test HTTP/1.1 Host: example.com X-Api-Key: abcdef... Content-Type: application/json { "displayName": "Just a test", - "description": "This is just a test to show how to create a cura profile with a different layer height and skirt count", + "description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count", "data": { "layer_height": 0.2, "skirt_line_count": 3 @@ -197,8 +197,8 @@ Add Slicing Profile { "displayName": "Just a test", - "description": "This is just a test to show how to create a cura profile with a different layer height and skirt count", - "resource": "http://example.com/api/slicing/cura/profiles/quick_test" + "description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count", + "resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test" } :param slicer: The identifying key of the slicer for which to add the profile diff --git a/docs/api/system.rst b/docs/api/system.rst index b39e0a1ad..c3df02e9a 100644 --- a/docs/api/system.rst +++ b/docs/api/system.rst @@ -38,30 +38,21 @@ List all registered system commands { "action": "shutdown", "name": "Shutdown", - "command": "sudo shutdown -h now", "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", "resource": "http://example.com/api/system/commands/core/shutdown" }, { "action": "reboot", "name": "Reboot", - "command": "sudo reboot", "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", "resource": "http://example.com/api/system/commands/core/reboot" }, { "action": "restart", "name": "Restart OctoPrint", - "command": "sudo service octoprint restart", "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", "resource": "http://example.com/api/system/commands/core/restart" } @@ -99,30 +90,21 @@ 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.

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, + "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).", "source": "core", "resource": "http://example.com/api/system/commands/core/shutdown" }, { "action": "reboot", "name": "Reboot", - "command": "sudo reboot", - "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, + "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).", "source": "core", "resource": "http://example.com/api/system/commands/core/reboot" }, { "action": "restart", "name": "Restart OctoPrint", - "command": "sudo service octoprint restart", - "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, + "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).", "source": "core", "resource": "http://example.com/api/system/commands/core/restart" } @@ -184,18 +166,60 @@ List all response - Description * - ``core`` - 0..n - - List of :ref:`command definitions ` + - List of :ref:`client command definitions ` - List of all core commands defined. * - ``custom`` - 0..n - - List of :ref:`command definitions ` + - List of :ref:`client command definitions ` - List of all custom commands defined in ``config.yaml``. +.. _sec-api-client-system-commands-definiton: + +Client command definitions +-------------------------- + +A restricted form of the full :ref:`command definition `. +For exposing via the API. + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``name`` + - 1 + - string + - The name of the command to display in the System menu. + * - ``action`` + - 1 + - string + - An identifier to refer to the command programmatically. The special ``action`` string + ``divider`` signifies a divider in the menu. + * - ``confirm`` + - 0..1 + - string + - If present and set, this text will be displayed to the user in a confirmation dialog + they have to acknowledge in order to really execute the command. + * - ``source`` + - 1 + - string + - Source of the command definition, currently either ``core`` (for system actions defined by + OctoPrint itself) or ``custom`` (for custom system commands defined by the user through ``config.yaml``). + * - ``resource`` + - 1 + - string + - The URL of the command to use for executing it. + .. _sec-api-system-commands-definiton: Command definition ------------------ +The full command definition is not available via the API. + .. list-table:: :widths: 15 5 10 30 :header-rows: 1 diff --git a/docs/api/version.rst b/docs/api/version.rst index 47b0c56e0..9716139c4 100644 --- a/docs/api/version.rst +++ b/docs/api/version.rst @@ -7,7 +7,8 @@ Version information .. http:get:: /api/version Retrieve information regarding server and API version. Returns a JSON object with two keys, ``api`` containing - the API version, ``server`` containing the server version. + the API version, ``server`` containing the server version, ``text`` containing the server version including + the prefix ``OctoPrint `` (to determine that this is indeed a genuine OctoPrint instance). **Example Request** @@ -26,7 +27,8 @@ Version information { "api": "0.1", - "server": "1.1.0" + "server": "1.3.10", + "text": "OctoPrint 1.3.10" } :statuscode 200: No error diff --git a/docs/bundledplugins/announcements.rst b/docs/bundledplugins/announcements.rst new file mode 100644 index 000000000..44dfe63e1 --- /dev/null +++ b/docs/bundledplugins/announcements.rst @@ -0,0 +1,67 @@ +.. _sec-bundledplugins-announcements: + +Announcement Plugin +=================== + +The OctoPrint Announcement Plugin comes bundled with OctoPrint (starting with 1.2.11). + +It displays announcements fetched from OctoPrint's websites, such as important updates, release announcements, new +plugins and similar. Through some manual configuration via ``config.yaml`` it also allows adding additional channels +via RSS or Atom feed URLs. + +.. _fig-bundledplugins-announcements-example1: +.. figure:: ../images/bundledplugins-announcements-example1.png + :align: center + :alt: Example notification + + An example notification from the Announcement Plugin. + +.. _fig-bundledplugins-announcements-example2: +.. figure:: ../images/bundledplugins-announcements-example2.png + :align: center + :alt: Announcement reader + + The Announcement Plugin's reader dialog. + +.. _fig-bundledplugins-announcements-settings: +.. figure:: ../images/bundledplugins-announcements-settings.png + :align: center + :alt: Announcement settings + + The Announcement Plugin's settings dialog. + +.. _sec-bundledplugins-announcements-configuration: + +Configuring the plugin +---------------------- + +The plugin allows enabling and disabling the preconfigured announcement channels via its settings dialog. + +On top of that it's possible to add additional announcement channels (as RSS or Atom feed URLs) or change the +configuration of the existing channels through ``config.yaml``. + +The available configuration keys are: + + * ``channels``: Configured announcement channels. A mapping from a unique identifier to a configuration structure + that follows this format: + + * ``name``: Name of the channel, used e.g. in the title of the displayed notifications. + * ``description``: Description of the channel. + * ``priority``: ``1`` for high priority announcements (red notification), ``2`` for regular ones (yellow notification). + * ``type``: Currently unused. + * ``url``: URL for the feed acting as notification source, must be RSS or Atom format. + + * ``enabled_channels``: List of identifiers of enabled channels. + * ``forced_channels``: List of identifiers of channels that cannot be disabled (currently only ``_important`` which is used sparingly). + * ``channel_order``: List of channel identifiers in the order they should appear in the UI. + * ``ttl``: Time to live of the channel cache in minutes (default: 6 hours). + * ``display_limit``: Limit of items to display per channel (default: 3). + * ``summary_limit``: Limit of characters to display from each channel entry (default: 300). + +.. _sec-bundledplugins-announcements-sourcecode: + +Source code +----------- + +The source of the Announcement plugin is bundled with OctoPrint and can be found in +its source repository under ``src/octoprint/plugins/announcements``. diff --git a/docs/bundledplugins/appkeys.rst b/docs/bundledplugins/appkeys.rst new file mode 100644 index 000000000..9d696dac2 --- /dev/null +++ b/docs/bundledplugins/appkeys.rst @@ -0,0 +1,543 @@ +.. _sec-bundledplugins-appkeys: + +Application Keys Plugin +======================= + +The OctoPrint Application Keys Plugin comes bundled with OctoPrint (starting with version 1.3.10). + +It implements a workflow for third party apps or clients to obtain an application specific API key from OctoPrint to interact with it +on a user's behalf, via confirmation of the user through OctoPrint's web interface. Existing keys can be managed +on a per-user base as well as globally by administrators. + +.. _fig-bundledplugins-appkeys-confirmation: +.. figure:: ../images/bundledplugins-appkeys-confirmation_prompt.png + :align: center + :alt: Confirmation + + The plugin's confirmation generated for a new application key request. + +.. _fig-bundledplugins-appkeys-user_settings: +.. figure:: ../images/bundledplugins-appkeys-user_settings.png + :align: center + :alt: Key management via user settings + + Users can manage the application specific API keys registered to their account via their user settings. + +.. _fig-bundledplugins-appkeys-settings: +.. figure:: ../images/bundledplugins-appkeys-settings.png + :align: center + :alt: Global key management via settings + + Administrators can manage all application specific API keys registered to any user. + +.. _sec-bundledplugins-appkeys-workflow: + +Workflow +-------- + +The workflow to receive an API key for a third party client/an app via the Application Keys Plugin should consist +of the following steps: + + 1. The User opens the App and gets prompted to enter or select an instance URL. Optionally (recommended!) the User also + enters their username which is also their user ID into the App. + 2. The App :ref:`probes for workflow support ` on the Server. If this request + doesn't get an HTTP :http:statuscode:`204` the App needs to direct the user to an alternative manual workflow + (copy-paste API key) and abort this one. Otherwise it proceeds to the next step. + 3. The App sends a :ref:`key request ` to the Server to start the + authorization process. + 4. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the + App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`. + 5. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202` + signals that no decision has been made yet. + 6. The User either accepts or denies the access request which makes the Webinterface send a + :ref:`decision request ` to the Server. + 7. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached + :ref:`API key response `. If they deny it, the App will receive + an HTTP :http:statuscode:`404`. + + +.. mermaid:: + + sequenceDiagram + participant User + participant App + participant Webinterface + participant Server + + note over User, Server: Step 1, 2 & 3 + + User->>App: enters URL of instance to connect to and optional user_id + + App->>Server: GET /plugin/appkeys/probe + + alt Workflow unsupported + + Server->>App: 404 + App->>User: alternative workflow, copy-paste key manually + + else Workflow supported + + App->>Server: POST /plugin/appkeys/request, (app_name, user_id) + + note over User, Server: Step 4 + + Server-->>Webinterface: plugin message for "appkeys" w/ (app_name, user_token, user_id) + Webinterface-->>User: Display confirmation dialog + Server->>App: 201, Location: /plugin/appkeys/request/ + + note over User, Server: Step 5 + + loop Poll for decision + App->>Server: GET /plugin/appkeys/request/ + Server->>App: 202 + end + + note over User, Server: Step 6 & 7 + + alt User accepts + + User-->>Webinterface: Allow access + Webinterface->>Server: POST /plugin/appkeys/decision/, (True) + Server->>Webinterface: 204 + App->>Server: GET /plugin/appkeys/request/ + Server->>App: 200, api_key + + else User denies + + User-->>Webinterface: Deny access + Webinterface->>Server: POST /plugin/appkeys/decision/, (False) + Server->>Webinterface: 204 + App->>Server: GET /plugin/appkeys/request/ + Server->>App: 404 + + end + + end + +.. _sec-bundledplugins-appkeys-api: + +API +--- + +.. _sec-bundledplugins-appkeys-api-probe: + +Probe for workflow support +.......................... + +.. http:get:: /plugin/appkeys/probe + + Probes for support of the workflow. + + Normally returns an HTTP :http:statuscode:`204`, indicating workflow availability. If a different status code is returned + (usually an HTTP :http:statuscode:`404`), the plugin is disabled or not installed. Fall back to manual api key exchange. + + :status 204: the workflow is supported + +.. _sec-bundledplugins-appkeys-api-startauthprocess: + +Start authorization process +........................... + +.. http:post:: /plugin/appkeys/request + + Starts the authorization process. + + Expects a :ref:`Key request ` as request body. + + The ``app`` parameter should be a human readable identifier to use + for the application requesting access. It will be displayed to the user. Internally it will be used case insensitively, + so ``My App`` and ``my APP`` are considered the same application identifiers. + + The optional ``user`` parameter should be used to limit the authorization process to a specified user. If the parameter + is left unset, any user will be able to complete the authorization process and grant access to the app with their + account. E.g. if a user ``me`` starts the process in an app, the app should request that name from the user and use + it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me`` + is logged in on. + + :json app: application identifier to use for the request, case insensitive + :json user: optional user id to restrict the decision to the specified user + :status 201: authorization process started, polling URL to query can be found in ``Location`` header + +.. _sec-bundledplugins-appkeys-api-polldecision: + +Poll for decision on existing request +..................................... + +.. http:get:: /plugin/appkeys/request/ + + Endpoint generated per authorization request to poll for the result. + + Returns an HTTP :http:statuscode:`202` while no decision has been made yet, an HTTP :http:statuscode:`200` and + a :ref:`Key response ` if access has been granted and an + HTTP :http:statuscode:`404` if the request has been denied or timed out. + + .. note:: + + The request will be considered stale and deleted internally if the polling endpoint for it isn't called + for more than 5s. + + :status 200: access granted, API key in response body + :status 202: no decision has been made yet, continue polling + :status 404: access denied or request timed out + +.. _sec-bundledplugins-appkeys-api-decide: + +Decide on existing request +.......................... + +.. http:post:: /plugin/appkeys/decision/ + + Endpoint to decide on the authorization request. + + Expects a :ref:`Decision request ` as request body. + + Returns an HTTP :http:statuscode:`204` on success. + + :json decision: boolean value to indicate whether to confirm (``True``) or deny (``False``) access + :status 204: success + +.. _sec-bundledplugins-appkeys-api-fetchlist: + +Fetch list of existing application keys +....................................... + +.. http:get:: /api/plugin/appkeys + + Fetches a list of existing application keys and pending requests registered in the system for the current user. + + If the additional optional parameter ``all`` is provided and the user has administrator rights, fetches a list + of *all** application keys and pending requests registered in the system for any user. + + Returns a :http:statuscode:`200` with a :ref:`List response ` in the + body upon success. + + :query all: Fetch all application keys and pending requests from all users. Requires administrator rights. + +.. _sec-bundledplugins-appkeys-api-issuecommand: + +Issue an application key command +................................ + +.. http:post:: /api/plugin/appkeys + + Application key commands allow revoking existing application keys and manually generating new ones. The available + commands are: + + revoke + Revokes an existing application key. Must belong to the user issuing the command, unless the user has admin rights + in which case they make revoke any application key in the system. Expects the key in question as parameter ``key``. + + generate + Generates a new application key for the user, using the application identifier provided as parameter ``app``. + + Upon success, a status code of :http:statuscode:`204` and an empty body is returned. + + Requires user rights. + + **Example revoke request** + + Revokes the (fictional) key ``aabbccddeeff112233445566``. + + .. sourcecode:: http + + POST /api/plugin/appkeys HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "revoke", + "key": "aabbccddeeff112233445566" + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content + + **Example generate request** + + Generates a new key for application identifier "My awesome application 1.0". + + .. sourcecode:: http + + POST /api/plugin/appkeys HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "generate", + "key": "My awesome application 1.0" + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content + + :json string command: The command to issue, either ``revoke`` or ``generate`` + :json string key: ``revoke`` command: The key to revoke + :json string app: ``generate`` command: Application identifier for which to generate a key + :statuscode 204: No error + :statuscode 400: Invalid or missing parameter + +.. _sec-bundledplugins-appkey-datamodel: + +Data model +---------- + +.. _sec-bundledplugins-appkey-datamodel-keyrequest: + +Key request +........... + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``app`` + - 1 + - str + - Application identifier to use for the request + * - ``user`` + - 0..1 + - str + - User identifier/name to restrict the request to + +.. _sec-bundledplugins-appkey-datamodel-keyresponse: + +Key response +............ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``apikey`` + - 1 + - str + - the API key generated for the application + +.. _sec-bundledplugins-appkey-datamodel-decisionrequest: + +Decision request +................ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``decision`` + - 1 + - boolean + - ``True`` if the access request it to be granted, ``False`` otherwise + +.. _sec-bundledplugins-appkey-datamodel-listreponse: + +List response +............. + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``keys`` + - 1 + - list of :ref:`key list entries ` + - Keys registered in the system + * - ``pending`` + - 1 + - list of :ref:`pending list entries ` + - Currently pending authorization requests + +.. _sec-bundledplugins-appkey-datamodel-keylistentry: + +Key list entry +.............. + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``api_key`` + - 1 + - str + - API key + * - ``app_id`` + - 1 + - str + - Application identifier + * - ``user_id`` + - 1 + - str + - User ID of the key's owner + +.. _sec-bundledplugins-appkey-datamodel-pendinglistentry: + +Pending list entry +.................. + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``app_id`` + - 1 + - str + - Application identifier + * - ``user_id`` + - 0..1 + - str + - optional: User ID of user who can grant or deny request + * - ``user_token`` + - 1 + - str + - Token to grant or deny request + +.. _sec-bundledplugins-appkeys-jsclientlib: + +JavaScript Client Library +------------------------- + +.. js:function:: OctoPrintClient.plugins.appkeys.getKeys(opts) + + Retrieves registered keys and pending requests for the current user. + + See :ref:`Fetch list of existing application keys ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.getAllKeys(opts) + + Retrieves registered keys and pending requests for all users. + + Needs administrator rights. + + See :ref:`Fetch list of existing application keys ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.generateKey(app, opts) + + Generates a key for the given ``app`` and the current user. + + See :ref:`Issue an application key command ` for details. + + :param string app: Application identifier + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.revokeKey(key, opts) + + Revokes the given ``key``. The key must belong to the current user, or the current user must have administrator + rights. + + See :ref:`Issue an application key command ` for details. + + :param string key: Key to revoke + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.decide(token, decision, opts) + + Decides on an existing authorization request. + + See :ref:`Decide on existing request ` for more details. + + :param string token: User token for which to make the decision, as pushed to the client via the socket. + :param boolean decision: Whether to grant access (``true``) or not (``false``). + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.probe(opts) + + Probes for workflow support. + + See :ref:`Probe for workflow support ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.request(app, opts) + + Starts a new authorization request for the provided ``app`` identifier. + + See :ref:`Start authorization process ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.requestForUser(app, user, opts) + + Starts a new authorization request for the provided ``app`` and ``user`` identifiers. + + See :ref:`Start authorization process ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.checkDecision(token, opts) + + Polls for a decision on an existing authorization request identified by ``token``. + + See :ref:`Poll for decision on existing request ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.authenticate(app, user, opts) + + Convenience function that probes for support, issues a request and then automatically starts polling for a decision + on the returned polling endpoint every 1s, until either a positive or negative decision is returned. On success the + returned promise is resolved with the generated API key as argument. If anything goes wrong or there is no support + for the workflow, the promise is rejected. + + **Example usage** + + .. sourcecode:: javascript + + OctoPrint.plugins.appkeys.authenticate("My App", "some_user") + .done(function(api_key) { + console.log("Got our API key:", api_key); + }) + .fail(function() { + console.log("No API key for us"); + }) + + :param string app: Application identifier + :param string user: Optional user identifier + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. _sec-bundledplugins-appkeys-sourcecode: + +Source code +----------- + +The source of the Application Keys plugin is bundled with OctoPrint and can be found in +its source repository under ``src/octoprint/plugins/appkeys``. diff --git a/docs/bundledplugins/backup.rst b/docs/bundledplugins/backup.rst new file mode 100644 index 000000000..350d40508 --- /dev/null +++ b/docs/bundledplugins/backup.rst @@ -0,0 +1,70 @@ +.. _sec-bundledplugins-backup: + +Backup Plugin +============= + +The OctoPrint Backup Plugin comes bundled with OctoPrint (starting with 1.3.10). + +It allows the creation and restoration of backups of OctoPrint's settings, data and installed plugins [#]_. + +This allows easy migration +to newly setup instances as well as making regular backups to prevent data loss. + +.. _fig-bundledplugins-backup-settings: +.. figure:: ../images/bundledplugins-backup-settings.png + :align: center + :alt: OctoPrint Backup Plugin + + The plugin's settings panel with existing backups, the backup creation and restore sections. + +As long as plugins adhere to the standard of storing their data and settings in OctoPrint's plugin data folders, their +data will be part of the backup. Note that the backups made by the Backup Plugin will *not* be part of any backups - +you'll need to persist the resulting zip files yourself! + +.. _sec-bundledplugins-backup-cli: + +Command line usage +------------------ + +The Backup Plugin implements a command line interface that allows creation and restoration of backups. +It adds two new commands, ``backup:backup`` and ``backup_restore``. + +.. code-block:: none + + $ octoprint plugins backup:backup --help + Initializing settings & plugin subsystem... + Usage: octoprint plugins backup:backup [OPTIONS] + + Creates a new backup. + + Options: + --exclude TEXT Identifiers of data folders to exclude, e.g. 'uploads' to + exclude uploads or 'timelapse' to exclude timelapses. + --help Show this message and exit. + + $ octoprint plugins backup:restore --help + Initializing settings & plugin subsystem... + Usage: octoprint plugins backup:restore [OPTIONS] PATH + + Restores an existing backup from the backup zip provided as argument. + + OctoPrint does not need to run for this to proceed. + + Options: + --help Show this message and exit. + +.. note:: + + The ``backup:backup`` command can be useful in combination with a cronjob to create backups in regular intervals. + +.. _sec-bundledplugins-backup-sourcecode: + +Source code +----------- + +The source of the Backup plugin is bundled with OctoPrint and can be found in +its source repository under ``src/octoprint/plugins/backup``. + +.. [#] Note that only those plugins that are available on `OctoPrint's official plugin repository `_ + can be automatically restored. If you have plugins installed that are not available on there you'll get their + names and - if available - homepage URL displayed after restore in order to be able to manually reinstall them. diff --git a/docs/bundledplugins/cura.rst b/docs/bundledplugins/cura.rst deleted file mode 100644 index d365e9ac3..000000000 --- a/docs/bundledplugins/cura.rst +++ /dev/null @@ -1,138 +0,0 @@ -.. _sec-bundledplugins-cura: - -Cura -==== - -The Cura Plugin allows slicing of STL files uploaded to OctoPrint directly via -the `CuraEngine `_ **up to and -including version 15.04.x** and supersedes the slicing support integrated into -OctoPrint so far. It comes bundled with OctoPrint starting with version 1.2.0. - -.. note:: - - Versions of CuraEngine later than 15.04.x have changed their calling - parameters in such a way that the current implementation of OctoPrint's Cura plugin - is not compatible to it. For this reason, please use only CuraEngine versions up to - and including 15.04 for now, as available in the ``legacy`` branch of the CuraEngine - repository on Github. - -The plugin offers a settings module that allows configuring the path to the -CuraEngine executable to use, as well as importing and managing slicing -profiles to be used. Please note that the Cura Plugin will use the printer -parameters you configured within OctoPrint (meaning bed size and extruder -count and offsets) for slicing. - -.. _sec-bundledplugins-cura-firststeps: - -First Steps ------------ - -Before you can slice from within OctoPrint, you'll need to - - #. :ref:`Install CuraEngine ` - #. :ref:`Configure the path to CuraEngine within OctoPrint ` - #. :ref:`Export a slicing profile from Cura and import it within OctoPrint ` - -.. note:: - - OctoPi 0.12.0 and later ships with steps 1 and 2 already done, you only need to - supply one or more slicing profiles to get going :) - -.. _sec-bundledplugins-cura-installing: - -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 `__. - -If you previously used the `old variant of the Cura integration `_, -you probably still have a fully functional binary lying around in the -installation folder of the full install of Cura you used then -- just put the -path to that in the plugin settings. - -.. _sec-bundledplugins-cura-installing-raspbian: - -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 - 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. - -Raspbian Jessie -~~~~~~~~~~~~~~~ - -Building on Raspbian Jessie is as easy as:: - - sudo apt-get -y install gcc-4.7 g++-4.7 - git clone -b legacy https://github.com/Ultimaker/CuraEngine.git - cd CuraEngine - make - -After this has completed, you'll find your shiny new build of CuraEngine in -the `build` folder (full path for above example: -``~/CuraEngine/build/CuraEngine``). - -Raspbian Wheezy -~~~~~~~~~~~~~~~ - -You'll need to install a new version of gcc and g++ and patch CuraEngine's -Makefile (see `this post `_) -in order for the compilation to work on current Raspbian builds (e.g. OctoPi):: - - sudo apt-get -y install gcc-4.7 g++-4.7 - git clone -b legacy https://github.com/Ultimaker/CuraEngine.git - cd CuraEngine - wget http://bit.ly/curaengine_makefile_patch -O CuraEngine.patch - patch < CuraEngine.patch - make CXX=g++-4.7 - -After this has completed, you'll find your shiny new build of CuraEngine in -the `build` folder (full path for above example: -``~/CuraEngine/build/CuraEngine``). - -.. _sec-bundledplugins-cura-configuring: - -Configuring the plugin ----------------------- - -The Cura plugin needs to be configured with the full path to your copy of the -CuraEngine executable that it's supposed to use. You can do this either via -the Cura plugin settings dialog or by manually configuring the path to the -executable via ``config.yaml``, example: - -.. code-block:: yaml - - plugins: - cura: - cura_engine: /path/to/CuraEngine - -.. _sec-bundledplugins-cura-profiles: - -Using Cura Profiles -------------------- - -The Cura Plugin supports importing your existing profiles for Cura **up to and -including Cura 15.04.x**. Newer Cura releases (e.g. 15.06 or 2.x) use a different -internal format that will *not* work with the current version of the Cura Plugin. - -You can find downloads of Cura 15.04.x for Windows, Mac and Linux `on Ultimaker's download page `_. - -In order to export a slicing profile from the Cura desktop UI, open it, -set up your profile, then click on "File" and there on "Save Profile". You can -import the .ini-file this creates via the "Import Profile" button in the -Cura Settings within OctoPrint. - -.. _sec-bundledplugins-cura-sourcecode: - -Source code ------------ - -The source of the Cura plugin is bundled with OctoPrint and can be found in -its source repository under ``src/octoprint/plugins/cura``. diff --git a/docs/bundledplugins/forcelogin.rst b/docs/bundledplugins/forcelogin.rst new file mode 100644 index 000000000..e5214f79f --- /dev/null +++ b/docs/bundledplugins/forcelogin.rst @@ -0,0 +1,35 @@ +.. _sec-bundledplugins-forcelogin: + +ForceLogin Plugin +================= + +The ForceLogin Plugin comes bundled with OctoPrint (starting with version 1.3.10). It removes the anonymous +read-only access that up until 1.3.10 was standard when accessing OctoPrint instances without being logged in and +instead forces users to log in if they want to get any kind of information from OctoPrint. + +.. _fig-bundledplugins-forcelogin: +.. figure:: ../images/bundledplugins-forcelogin-dialog.png + :align: center + :alt: Forced login dialog + + OctoPrint's new forced login dialog. + +.. warning:: + + Keep in mind that **OctoPrint does not manage your webcam**, it merely embeds it. If you have a webcam, + it will still be accessible to users who are not logged in under its (guessable) URL. If you need to restrict + access to your webcam, you'll need to find a way to do so directly on the webcam server which - again - + is not OctoPrint itself. + +.. note:: + + If you want back the old behaviour of allowing anonymous read-only access to your OctoPrint instance, disable + the ForceLogin Plugin in OctoPrint's plugin manager. + +.. _sec-bundledplugins-forcelogin-sourcecode: + +Source code +----------- + +The source of the ForceLogin plugin is bundled with OctoPrint and can be found in +its source repository under ``src/octoprint/plugins/forcelogin``. diff --git a/docs/bundledplugins/index.rst b/docs/bundledplugins/index.rst index 26a520699..07ae6682b 100644 --- a/docs/bundledplugins/index.rst +++ b/docs/bundledplugins/index.rst @@ -8,8 +8,11 @@ Bundled Plugins :maxdepth: 2 action_command_prompt.rst - cura.rst + announcements.rst + appkeys.rst + backup.rst discovery.rst + forcelogin.rst logging.rst pluginmanager.rst printer_safety_check.rst diff --git a/docs/bundledplugins/pluginmanager.rst b/docs/bundledplugins/pluginmanager.rst index dacb3f8ca..2ec1babbb 100644 --- a/docs/bundledplugins/pluginmanager.rst +++ b/docs/bundledplugins/pluginmanager.rst @@ -82,6 +82,45 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``: - hidden - plugins +.. _sec-bundledplugins-pluginmanager-events: + +Events +------ + +plugin_pluginmanager_install_plugin + A plugin was installed. + + Payload: + + * ``id``: the identifier of the installed plugin + * ``version``: the version of the installed plugin + * ``source``: source from which the plugin was installed, can be an URL or a path in the local file system + * ``source_type``: type of source from which the plugin was installed, can be ``url`` or ``path`` + +plugin_pluginmanager_uninstall_plugin + A plugin was uninstalled. + + Payload: + + * ``id``: the identifier of the uninstalled plugin + * ``version``: the version of the uninstalled plugin + +plugin_pluginmanager_enable_plugin + A plugin was enabled. + + Payload: + + * ``id``: the identifier of the enabled plugin + * ``version``: the version of the enabled plugin + +plugin_pluginmanager_disabled_plugin + A plugin was disabled. + + Payload: + + * ``id``: the identifier of the disabled plugin + * ``version``: the version of the disabled plugin + .. _sec-bundledplugins-pluginmanager-hooks: Hooks diff --git a/docs/bundledplugins/printer_safety_check.rst b/docs/bundledplugins/printer_safety_check.rst index 89974de48..320de9053 100644 --- a/docs/bundledplugins/printer_safety_check.rst +++ b/docs/bundledplugins/printer_safety_check.rst @@ -16,17 +16,12 @@ such identification. An example of a warning generated by the Printer Safety Check -Currently the following firmwares produce this warning: - - * Anet A8 stock firmware +Please refer to the `entry on the "unsafe firmware" warning in OctoPrint's FAQ `_ +for a list of currently identified printers. If you know of further printers/printer firmwares that need to be added here, please `get in touch on the forum and provide their response to an M115 `_. -.. 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 @@ -34,6 +29,20 @@ If you know of further printers/printer firmwares that need to be added here, pl unexpectedly and with `catastrophic `_ `results `_. +.. _sec-bundledplugins-printer_safety_check-events: + +Events +------ + +warning + A printer safety warning was triggered. + + Payload: + + * ``check_type``: type of check that was triggered (e.g. ``m115``, ``received`` or ``cap``) + * ``check_name``: name of check that was triggered (e.g. ``aneta8``) + * ``warning_type``: type of warning that was triggered (e.g. ``firmware-unsafe``) + .. _sec-bundledplugins-printer_safety_check-source: Source Code diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index de4896b6d..1ba0daf84 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -325,6 +325,29 @@ The same, but tracking all commits pushed to branch ``devel`` (thus allowing branch: devel pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip' +.. _sec-bundledplugins-softwareupdate-events: + +Events +------ + +plugin_softwareupdate_update_succeeded + An update succeeded. + + Payload: + + * ``target``: update target + * ``from_version``: version from which was updated + * ``to_version``: version to which was updated + +plugin_softwareupdate_update_failed + An update failed. + + Payload: + + * ``target``: update target + * ``from_version``: version from which was updated + * ``to_version``: version to which was updated + .. _sec-bundledplugins-softwareupdate-hooks: Hooks @@ -362,8 +385,8 @@ octoprint.plugin.softwareupdate.check_config .. code-block:: python - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals def get_update_information(*args, **kwargs): return dict( diff --git a/docs/conf.py b/docs/conf.py index 3827b54fa..9de6f2608 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + # # OctoPrint documentation build configuration file, created by # sphinx-quickstart on Mon Dec 02 17:08:50 2013. @@ -49,8 +51,8 @@ source_suffix = '.rst' master_doc = 'index' # General information about the project. -project = u'OctoPrint' -copyright = u'%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else u'%d, Gina Häußge' % year_since +project = 'OctoPrint' +copyright = '%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else '%d, Gina Häußge' % year_since # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -207,8 +209,8 @@ htmlhelp_basename = 'OctoPrintdoc' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). #latex_documents = [ -# ('index', 'OctoPrint.tex', u'OctoPrint Documentation', -# u'Gina Häußge', 'manual'), +# ('index', 'OctoPrint.tex', 'OctoPrint Documentation', +# 'Gina Häußge', 'manual'), #] # The name of an image file (relative to this directory) to place at the top of @@ -237,8 +239,8 @@ htmlhelp_basename = 'OctoPrintdoc' # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - ('index', 'octoprint', u'OctoPrint Documentation', - [u'Gina Häußge'], 1) + ('index', 'octoprint', 'OctoPrint Documentation', + ['Gina Häußge'], 1) ] # If true, show URL addresses after external links. @@ -251,8 +253,8 @@ man_pages = [ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'OctoPrint', u'OctoPrint Documentation', - u'Gina Häußge', 'OctoPrint', 'One line description of project.', + ('index', 'OctoPrint', 'OctoPrint Documentation', + 'Gina Häußge', 'OctoPrint', 'One line description of project.', 'Miscellaneous'), ] diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index b387af622..2266cc0a7 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -29,7 +29,7 @@ Use the following settings to enable access control: # The user manager implementation to use for accessing user information. Currently only a filebased # user manager is implemented which stores configured accounts in a YAML file (Default: users.yaml # in the default configuration folder, see below) - userManager: octoprint.users.FilebasedUserManager + userManager: octoprint.access.users.FilebasedUserManager # The YAML user file to use. If left out defaults to users.yaml in the default configuration folder. userFile: /path/to/users.yaml @@ -81,7 +81,8 @@ Settings for the REST API: # Whether to allow cross origin access to the API or not allowCrossOrigin: false - # Additional app api keys, see REST API > Apps in the docs + # Additional app api keys, see REST API > Apps in the docs. + # Deprecated since 1.3.11, to be removed in 1.4.0! apps: "some.app.identifier:some_version": pubkey: @@ -209,7 +210,7 @@ appearance or to modify the order and presence of the various UI components: tab: - plugin_helloworld - OctoPrint will then turn this into the order ``plugin_helloworld``, ``temperature``, ``control``, ``gcodeviewer``, + OctoPrint will then display the tabs in the order ``plugin_helloworld``, ``temperature``, ``control``, ``gcodeviewer``, ``terminal``, ``timelapse`` plus any other plugins. @@ -562,6 +563,9 @@ Use the following settings to enable or disable OctoPrint features: - M117 - M118 + # whether G90/G91 also influence absolute/relative mode of extruders + g90InfluencesExtruder: false + .. _sec-configuration-config_yaml-folder: Folder @@ -617,15 +621,16 @@ Settings pertaining to the server side GCODE analysis implementation. .. code-block:: yaml - # Maximum number of extruders to support/to sanity check for - maxExtruders: 10 + gcodeAnalysis: + # Maximum number of extruders to support/to sanity check for + maxExtruders: 10 - # Pause between each processed GCODE line in normal priority mode, seconds - throttle_normalprio: 0.01 + # Pause between each processed GCODE line in normal priority mode, seconds + throttle_normalprio: 0.01 - # Pause between each processed GCODE line in high priority mode (e.g. on fresh - # uploads), seconds - throttle_highprio: 0.0 + # Pause between each processed GCODE line in high priority mode (e.g. on fresh + # uploads), seconds + throttle_highprio: 0.0 .. _sec-configuration-config_yaml-gcodeviewer: @@ -636,16 +641,17 @@ Settings pertaining to the built in GCODE Viewer. .. code-block:: yaml - # Whether to enable the GCODE viewer in the UI - enabled: true + gcodeViewer: + # Whether to enable the GCODE viewer in the UI + enabled: true - # Maximum size a GCODE file may have on mobile devices to automatically be loaded - # into the viewer, defaults to 2MB - mobileSizeThreshold: 2097152 + # Maximum size a GCODE file may have on mobile devices to automatically be loaded + # into the viewer, defaults to 2MB + mobileSizeThreshold: 2097152 - # Maximum size a GCODE file may have to automatically be loaded into the viewer, - # defaults to 20MB - sizeThreshold: 20971520 + # Maximum size a GCODE file may have to automatically be loaded into the viewer, + # defaults to 20MB + sizeThreshold: 20971520 .. _sec-configuration-config_yaml-plugins: @@ -1056,6 +1062,15 @@ Use the following settings to configure the server: # How many days to leave unused entries in the preemptive cache config until: 7 + # Configuration of the client IP check to warn about connections from external networks + ipCheck: + + # whether to enable the check, defaults to true + enabled: true + + # additional non-local subnets to consider trusted, in CIDR notation, e.g. "192.168.1.0/24" + trustedSubnets: [] + .. note:: @@ -1085,14 +1100,14 @@ Settings for the built-in slicing support: slicing: # Whether to enable slicing support or not - enabled: + enabled: true # Default slicer to use - defaultSlicer: cura + defaultSlicer: null # Default slicing profiles per slicer defaultProfiles: - cura: ... + curalegacy: ... .. _sec-configuration-config_yaml-system: @@ -1163,7 +1178,7 @@ Use `Javascript regular expressions ``: the plugin ````, e.g. ``octoprint.plugins.discovery`` to change the log level of - the `Discovery plugin `_ or ``octoprint.plugins.cura`` - to change the log level of the `Cura plugin `_. + the :ref:`Discovery plugin ` or ``octoprint.plugins.backup`` + to change the log level of the :ref:`Backup plugin `. * ``octoprint.slicing``: the slicing sub system This list will be expanded when deemed necessary. diff --git a/docs/development/environment.rst b/docs/development/environment.rst index 8308712b7..2fa09aac3 100644 --- a/docs/development/environment.rst +++ b/docs/development/environment.rst @@ -14,18 +14,25 @@ below. * Prerequisites: * `Python 2.7 `_ including ``pip``, ``setuptools`` and ``virtualenv`` + * `Python 3.7 `_ including ``pip``, ``setuptools`` and ``virtualenv`` * `Git `_ - * Checkout the OctoPrint sources from their Git repository: ``git clone https://github.com/foosel/OctoPrint.git`` + * Checkout the OctoPrint sources from their Git repository: + * ``git clone -b devel 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`` + * Create virtual environments in the checked out source folder for both Python 2.7 and Python 3.7 to use for + installing and running OctoPrint and its dependencies (this avoids potential versioning issues for the dependencies + with system wide installed instances): + * PY2: ``virtualenv --python=python2 venv2`` + * PY3: ``virtualenv --python=python3 venv3`` + * Activate one of the virtual environments: + * PY2: ``source venv2/bin/activate`` (Linux, MacOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below) + * PY3: ``source venv3/bin/activate`` (Linux, MacOS) or ``source venv3/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]`` + including its regular *and* development and plugin development dependencies: + * ``pip install -e .[develop,plugins]`` When the virtual environment is activated you can then: @@ -33,11 +40,19 @@ When the virtual environment is activated you can then: * 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`` +To switch the activated virtual environment, simply activate the new environment as described above. + +To deactivate the virtual environment and return to the system's default Python: ``deactivate``. + .. _sec-development-environment-source-linux: Linux ..... +.. todo:: + + This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. + This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different location, please substitute accordingly. @@ -70,7 +85,7 @@ Then: .. code-block:: none cd ~/devel - git clone https://github.com/foosel/OctoPrint.git + git clone -b devel https://github.com/foosel/OctoPrint.git cd OctoPrint virtualenv venv source ./venv/bin/activate @@ -85,12 +100,16 @@ environment. Windows ....... +.. todo:: + + This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. + 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 `_ + * `Python 2.7.15 Windows x86 MSI installer `_ * make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too @@ -120,6 +139,10 @@ Mac OS X 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. +.. todo:: + + This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. + This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different location, please substitute accordingly. @@ -158,6 +181,10 @@ You'll need a user account with administrator privileges. IDE Setup --------- +.. todo:: + + This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. + .. todo:: Using another IDE than the ones below? Please send a diff --git a/docs/development/virtual_printer.rst b/docs/development/virtual_printer.rst index 479cdc198..85d35c50e 100644 --- a/docs/development/virtual_printer.rst +++ b/docs/development/virtual_printer.rst @@ -57,60 +57,71 @@ You can simulate certain conditions and communications through the terminal tab 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. +message with all the available commands: -Action Triggers -............... +.. code-block:: none -``action_pause`` -Sends a "// action:pause" action trigger to the host. + OctoPrint Virtual Printer debug commands -``action_resume`` -Sends a "// action:resume" action trigger to the host. + help + ? + | This help. -``action_disconnect`` -Sends a "// action:disconnect" action trigger to the host. + # Action Triggers -``action_custom [ ]`` -Sends a custom "// action: " action trigger to the host. + 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 -.................... + # Communication Errors -``dont_answer`` -Will not acknowledge the next command. + 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 + trigger_missing_checksum + | Triggers a resend error with a missing checksum + trigger_missing_lineno + | Triggers a "no line number with checksum" error w/o resend request + drop_connection + | Drops the serial connection + prepare_ok + | Will cause to be enqueued for use, + | will be used instead of actual "ok" -``go_awol`` -Will completely stop replying. + # Reply Timing / Sleeping -``trigger_resend_lineno`` -Triggers a resend error with a line number mismatch + sleep + | Sleep s + sleep_after + | Sleeps s after each execution of + sleep_after_next + | Sleeps s after execution of next -``trigger_resend_checksum`` -Triggers a resend error with a checksum mismatch + # SD printing -``drop_connection`` -Drops the serial connection + start_sd + | Select and start printing file from SD + select_sd + | Select file from SD, don't start printing it yet. Use + | start_sd to start the print + cancel_sd + | Cancels an ongoing SD print -``prepare_ok `` -Will cause to be enqueued for use, will be used instead of actual "ok" + # Misc -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 + send + | Sends back + reset + | Simulates a reset. Internal state will be lost. diff --git a/docs/events/index.rst b/docs/events/index.rst index a97e7e385..26deef5bd 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -6,15 +6,6 @@ Events .. contents:: - -.. note:: - - With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events. - Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to - accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer - separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed - to indicate what to do with the command contained. - .. _sec-events-configuration: Configuration @@ -85,6 +76,10 @@ and its origin via the placeholder ``{origin}``. Available Events ================ +.. note:: + + Plugins may add additional events via the :ref:`octoprint.events.register_custom_events hook `. + Server ------ @@ -141,7 +136,8 @@ Disconnected The server has disconnected from the printer Error - An error has occurred in the printer communication. + An unrecoverable error has been encountered, either as reported by the firmware (e.g. a thermal runaway) or + on the connection. Payload: @@ -169,9 +165,7 @@ Upload .. deprecated:: 1.3.0 - * ``file``: the file's path within its storage location - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's path within its storage location. To be removed in 1.4.0. FileAdded A file has been added to a storage. @@ -253,9 +247,7 @@ MetadataAnalysisStarted .. deprecated:: 1.3.0 - * ``file``: the file's path within its storage location - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's path within its storage location. To be removed in 1.4.0. MetadataAnalysisFinished The metadata analysis of a file has finished. @@ -269,9 +261,7 @@ MetadataAnalysisFinished .. deprecated:: 1.3.0 - * ``file``: the file's path within its storage location - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's path within its storage location. To be removed in 1.4.0. FileSelected A file has been selected for printing. @@ -284,10 +274,8 @@ FileSelected .. deprecated:: 1.3.0 - * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``) - * ``filename``: the file's name - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. + * ``filename``: the file's name. To be removed in 1.4.0. FileDeselected No file is selected any more for printing. @@ -322,13 +310,14 @@ PrintStarted * ``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`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``user``: the user who started the print job (if available) .. deprecated:: 1.3.0 - * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``) - * ``filename``: the file's name - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. + * ``filename``: the file's name. To be removed in 1.4.0. PrintFailed A print failed. @@ -338,13 +327,15 @@ PrintFailed * ``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`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``time``: the elapsed time of the print when it failed, in seconds (float) + * ``reason``: the reason the print failed, either ``cancelled`` or ``error`` .. deprecated:: 1.3.0 - * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``) - * ``filename``: the file's name - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. + * ``filename``: the file's name. To be removed in 1.4.0. PrintDone A print completed successfully. @@ -354,14 +345,14 @@ PrintDone * ``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`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) * ``time``: the time needed for the print, in seconds (float) .. deprecated:: 1.3.0 - * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``) - * ``filename``: the file's name - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. + * ``filename``: the file's name. To be removed in 1.4.0. PrintCancelling The print is about to be cancelled. @@ -371,6 +362,9 @@ PrintCancelling * ``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`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``user``: the user who cancelled the print job (if available) * ``firmwareError``: the firmware error that caused cancelling the print job, if any PrintCancelled @@ -381,7 +375,12 @@ PrintCancelled * ``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`` - * ``position``: the print head position at the time of cancelling, if available + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``time``: the elapsed time of the print when it was cancelled, in seconds (float) + * ``user``: the user who cancelled the print job (if available) + * ``position``: the print head position at the time of cancelling (if available, not available if recording of the + position on cancel is disabled) * ``position.x``: x coordinate, as reported back from the firmware through `M114` * ``position.y``: y coordinate, as reported back from the firmware through `M114` * ``position.z``: z coordinate, as reported back from the firmware through `M114` @@ -395,10 +394,8 @@ PrintCancelled .. deprecated:: 1.3.0 - * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``) - * ``filename``: the file's name - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. + * ``filename``: the file's name. To be removed in 1.4.0. PrintPaused The print has been paused. @@ -408,7 +405,11 @@ PrintPaused * ``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`` - * ``position``: the print head position at the time of pausing, if available + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``user``: the user who paused the print job (if available) + * ``position``: the print head position at the time of pausing (if available, not available if the recording of + the position on pause is disabled or the pause is completely handled by the printer's firmware) * ``position.x``: x coordinate, as reported back from the firmware through `M114` * ``position.y``: y coordinate, as reported back from the firmware through `M114` * ``position.z``: z coordinate, as reported back from the firmware through `M114` @@ -422,10 +423,8 @@ PrintPaused .. deprecated:: 1.3.0 - * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``) - * ``filename``: the file's name - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. + * ``filename``: the file's name. To be removed in 1.4.0. PrintResumed The print has been resumed. @@ -435,13 +434,14 @@ PrintResumed * ``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`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``user``: the user who resumed the print job (if available) .. deprecated:: 1.3.0 - * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``) - * ``filename``: the file's name - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. + * ``filename``: the file's name. To be removed in 1.4.0. GCODE processing ---------------- diff --git a/docs/features/accesscontrol.rst b/docs/features/accesscontrol.rst index 3207b1c42..cb6a1e248 100644 --- a/docs/features/accesscontrol.rst +++ b/docs/features/accesscontrol.rst @@ -31,7 +31,13 @@ Internet!). .. hint:: If you plan to have your OctoPrint instance accessible over the internet, - **always enable Access Control**. + **always enable Access Control** and ideally **don't make it accessible to + everyone over the internet but instead use a VPN** or at the very least + HTTP basic authentication on a layer above OctoPrint. + + A physical device that includes heaters and stepper motors really should not be + publicly reachable by everyone with an internet connection, even with access + control enabled. .. _sec-features-access_control-rerunning_wizard: diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index 4fb891eb4..73d8916f8 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -157,9 +157,13 @@ The ``disable_hotends`` snippet is defined as follows: .. code-block:: jinja :caption: Default ``disable_hotends`` snippet + {% if printer_profile.extruder.sharedNozzle %} + M104 T0 S0 + {% else %} {% for tool in range(printer_profile.extruder.count) %} M104 T{{ tool }} S0 {% endfor %} + {% endif %} The ``disable_bed`` snippet is defined as follows: diff --git a/docs/images/bundledplugins-announcements-example1.png b/docs/images/bundledplugins-announcements-example1.png new file mode 100644 index 000000000..153abeb29 Binary files /dev/null and b/docs/images/bundledplugins-announcements-example1.png differ diff --git a/docs/images/bundledplugins-announcements-example2.png b/docs/images/bundledplugins-announcements-example2.png new file mode 100644 index 000000000..6cdda8521 Binary files /dev/null and b/docs/images/bundledplugins-announcements-example2.png differ diff --git a/docs/images/bundledplugins-announcements-settings.png b/docs/images/bundledplugins-announcements-settings.png new file mode 100644 index 000000000..3e280c9de Binary files /dev/null and b/docs/images/bundledplugins-announcements-settings.png differ diff --git a/docs/images/bundledplugins-appkeys-confirmation_prompt.png b/docs/images/bundledplugins-appkeys-confirmation_prompt.png new file mode 100644 index 000000000..a1bbadec5 Binary files /dev/null and b/docs/images/bundledplugins-appkeys-confirmation_prompt.png differ diff --git a/docs/images/bundledplugins-appkeys-settings.png b/docs/images/bundledplugins-appkeys-settings.png new file mode 100644 index 000000000..61b185dac Binary files /dev/null and b/docs/images/bundledplugins-appkeys-settings.png differ diff --git a/docs/images/bundledplugins-appkeys-user_settings.png b/docs/images/bundledplugins-appkeys-user_settings.png new file mode 100644 index 000000000..96fd18ebc Binary files /dev/null and b/docs/images/bundledplugins-appkeys-user_settings.png differ diff --git a/docs/images/bundledplugins-backup-settings.png b/docs/images/bundledplugins-backup-settings.png new file mode 100644 index 000000000..1d21c69e8 Binary files /dev/null and b/docs/images/bundledplugins-backup-settings.png differ diff --git a/docs/images/bundledplugins-forcelogin-dialog.png b/docs/images/bundledplugins-forcelogin-dialog.png new file mode 100644 index 000000000..8508cb6d4 Binary files /dev/null and b/docs/images/bundledplugins-forcelogin-dialog.png differ diff --git a/docs/jsclientlib/index.rst b/docs/jsclientlib/index.rst index cf4f20376..43b734769 100644 --- a/docs/jsclientlib/index.rst +++ b/docs/jsclientlib/index.rst @@ -80,9 +80,13 @@ connection options (``baseurl`` and ``apikey``) directly in the constructor or s .. seealso:: - `OctoPrint-ForceLogin `_ - A plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI. Utilizes the - client library's :ref:`browser component ` to login the user. + :ref:`Application Key Plugin ` + A bundled plugin that implements an authorization workflow for third party clients. It adds various additional + methods to the JS Client Library. + :ref:`ForceLogin Plugin ` + A bundled plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI and + various hooks. Utilizes the client library's :ref:`browser component ` to login the + user. .. toctree:: :maxdepth: 3 diff --git a/docs/modules/users.rst b/docs/modules/users.rst index f147a46a3..2cf3163f5 100644 --- a/docs/modules/users.rst +++ b/docs/modules/users.rst @@ -1,9 +1,9 @@ .. _sec-modules-users: -octoprint.users ---------------- +octoprint.access.users +---------------------- -.. automodule:: octoprint.users +.. automodule:: octoprint.access.users :members: diff --git a/docs/modules/util.rst b/docs/modules/util.rst index 32a61b728..156a25ff3 100644 --- a/docs/modules/util.rst +++ b/docs/modules/util.rst @@ -6,4 +6,10 @@ octoprint.util .. automodule:: octoprint.util :members: +.. _sec-modules-util-commandline: +octoprint.util.commandline +-------------------------- + +.. automodule:: octoprint.util.commandline + :members: diff --git a/docs/plugins/gettingstarted.rst b/docs/plugins/gettingstarted.rst index ac43e92ad..c83fbb7de 100644 --- a/docs/plugins/gettingstarted.rst +++ b/docs/plugins/gettingstarted.rst @@ -54,8 +54,8 @@ We'll start at the most basic form a plugin can take - just a few simple lines o .. code-block:: python :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals __plugin_name__ = "Hello World" __plugin_version__ = "1.0.0" @@ -89,8 +89,8 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t :emphasize-lines: 4-8,13 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -289,8 +289,8 @@ and ``__plugin_description__`` from ``__init__.py``: .. code-block:: python :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -314,8 +314,8 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the :emphasize-lines: 10 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -362,8 +362,8 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class: :emphasize-lines: 7 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -428,8 +428,8 @@ Let's take a look at how all that would look in our plugin's ``__init__.py``: :emphasize-lines: 8, 10, 12-13 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -462,8 +462,8 @@ Adjust your plugin's ``__init__.py`` like this: :emphasize-lines: 15-16 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -569,8 +569,8 @@ again since we don't use that anymore: :emphasize-lines: 15-19 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -666,8 +666,8 @@ like so: :emphasize-lines: 9,22-25 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -846,8 +846,8 @@ a reference to our CSS file: :emphasize-lines: 26 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -931,8 +931,8 @@ Then adjust our returned assets to include our LESS file as well: :emphasize-lines: 27 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin diff --git a/docs/plugins/helpers.rst b/docs/plugins/helpers.rst index c411d3776..f8c5424f3 100644 --- a/docs/plugins/helpers.rst +++ b/docs/plugins/helpers.rst @@ -3,7 +3,7 @@ Helpers ======= -Helpers are methods that plugin can exposed to other plugins in order to make common functionality available on the +Helpers are methods that plugins can expose to other plugins in order to make common functionality available on the system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``. An example for providing some helper functions to the system can be found in the diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 5f86a2c7c..a5a9f0aa3 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -28,6 +28,7 @@ or as ``postfix`` (after the existing lines). .. code-block:: python :linenos: + from past import basestring self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.scripts") # ... @@ -35,7 +36,7 @@ or as ``postfix`` (after the existing lines). for hook in self._gcodescript_hooks: try: retval = self._gcodescript_hooks[hook](self, "gcode", scriptName) - except: + except Exception: self._logger.exception("Error while processing gcodescript hook %s" % hook) else: if retval is None: @@ -44,10 +45,8 @@ or as ``postfix`` (after the existing lines). continue def to_list(data): - if isinstance(data, str): - data = map(str.strip, data.split("\n")) - elif isinstance(data, unicode): - data = map(unicode.strip, data.split("\n")) + if isinstance(data, basestring): + data = map(x.strip() for x in data.split("\n")) if isinstance(data, (list, tuple)): return list(data) @@ -201,31 +200,6 @@ Available plugin hooks .. contents:: :local: -.. _sec-plugins-hook-accesscontrol-appkey: - -octoprint.accesscontrol.appkey -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. py:function:: acl_appkey_hook(*args, **kwargs) - - By handling this hook plugins may register additional :ref:`App session key providers ` - within the system. - - Overrides this to return your additional app information to be used for validating app session keys. You'll - need to return a list of 3-tuples of the format (id, version, public key). - - The ``id`` should be the (unique) identifier of the app. Using a domain prefix might make sense here, e.g. - ``org.octoprint.example.MyApp``. - - ``version`` should be a string specifying the version of the app for which the public key is valid. You can - provide the string ``any`` here, in which case the provided public key will be valid for all versions of the - app for which no specific public key is defined. - - Finally, the public key is expected to be provided as a PKCS1 string without newlines. - - :return: A list of 3-tuples as described above - :rtype: list - .. _sec-plugins-hook-accesscontrol-keyvalidator: octoprint.accesscontrol.keyvalidator @@ -237,7 +211,7 @@ octoprint.accesscontrol.keyvalidator ``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 + Hook handlers are expected to return a :class:`~octoprint.access.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. @@ -255,7 +229,7 @@ octoprint.accesscontrol.keyvalidator :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` + :rtype: :class:`~octoprint.access.users.User` .. _sec-plugins-hook-cli-commands: @@ -380,10 +354,10 @@ octoprint.cli.commands OctoPrint's CLI. :rtype: list -.. _sec-plugins-hook-comm-firmware-info: +.. _sec-plugins-hook-comm-protocol-firmware-info: -octoprint.comm.firmware.info -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +octoprint.comm.protocol.firmware.info +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. py:function:: firmware_info_hook(comm_instance, firmware_name, firmware_data, *args, **kwargs) @@ -402,14 +376,21 @@ octoprint.comm.firmware.info ``firmware_name`` will be ``Some Firmware Name`` in this case. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as + you will effectively block the receive loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + :param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook. :param str firmware_name: The name of the parsed capability :param dict firmware_data: All data contained in the ``M115`` report -.. _sec-plugins-hook-comm-firmware-capabilities: +.. _sec-plugins-hook-comm-protocol-firmware-capabilities: -octoprint.comm.firmware.capabilities -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +octoprint.comm.firmware.protocol.capabilities +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. py:function:: firmware_capability_hook(comm_instance, capability, enabled, already_defined, *args, **kwargs) @@ -421,6 +402,13 @@ octoprint.comm.firmware.capabilities Note that hook handlers will be called once per received capability line. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as + you will effectively block the receive loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + :param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook. :param str capability: The name of the parsed capability :param bool enabled: Whether the capability is reported as enabled or disabled @@ -440,6 +428,13 @@ octoprint.comm.protocol.action No returned value is expected. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within your handlers as + you will effectively block the receive loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + **Example:** Logs if the ``custom`` action (``// action:custom``) is received from the printer's firmware. @@ -477,6 +472,13 @@ This describes actually two hooks: trigger the *actual execution* of whatever functionality lies behind a given @ command, similar to :ref:`the action command hook `. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within your handlers as + you will effectively block the send/receive loops, causing the communication with the printer to stall. + + This includes I/O of any kind. + **Example** Pause the print on ``@wait`` (this mirrors the implementation of the built-in ``@pause`` command, just with a @@ -623,6 +625,13 @@ This describes actually four hooks: 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. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as + you will effectively block the send loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + **Example** The following hook handler replaces all ``M107`` ("Fan Off", deprecated) with an ``M106 S0`` ("Fan On" with speed @@ -658,6 +667,13 @@ octoprint.comm.protocol.gcode.received 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. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as + you will effectively block the receive loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + **Example:** Looks for the response of an ``M115``, which contains information about the ``MACHINE_TYPE``, among other things. @@ -687,6 +703,13 @@ octoprint.comm.protocol.gcode.error 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. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as + you will effectively block the receive loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + **Example:** Looks for error messages containing "fan error" or "bed missing" (ignoring case) and marks them as handled by the @@ -762,6 +785,13 @@ octoprint.comm.protocol.temperatures.received 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. + .. warning:: + + Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as + you will effectively block the receive loop, causing the communication with the printer to stall. + + This includes I/O of any kind. + **Example** The following example shows how to filter out actual temperatures that are outside a sane range of 1°C to 300°C. @@ -847,6 +877,34 @@ octoprint.comm.transport.serial.factory :rtype: A serial instance implementing implementing the methods ``readline(...)``, ``write(...)``, ``close()`` and optionally ``baudrate`` and ``timeout`` attributes as described above. +.. _sec-plugins-hook-events-register_custom_events: + +octoprint.events.register_custom_events +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: register_custom_events_hook(*args, **kwargs) + + Return a list of custom :ref:`events ` to register in the system for your plugin. + + Should return a list of strings which represent the custom events. Their name on the `octoprint.events.Events` object + will be the returned value transformed into upper case ``CAMEL_CASE`` and prefixed with ``PLUGIN_``. Their + value will be prefixed with ``plugin__``. + + Example: + + Consider the following hook part of a plugin with the identifier ``myplugin``. It will register two custom events + in the system, ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_CUSTOM_EVENT`` with value ``plugin_myplugin_my_custom_event`` + and ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_OTHER_CUSTOM_EVENT`` with value ``plugin_myplugin_my_other_custom_event``. + + .. code-block:: python + :linenos: + + def register_custom_events(*args, **kwargs): + return ["my_custom_event", "my_other_custom_event"] + + :return: A list of custom events to register + :rtype: list + .. _sec-plugins-hook-filemanager-analysis-factory: octoprint.filemanager.analysis.factory @@ -973,9 +1031,8 @@ octoprint.printer.factory * ``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` - * ``user_manager``: The :class:`~octoprint.users.UserManager` + * ``user_manager``: The :class:`~octoprint.access.users.UserManager` * ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache` If the factory returns anything but ``None``, it will be assigned to the global ``printer`` instance. @@ -1033,6 +1090,139 @@ octoprint.printer.estimation.factory :return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method :rtype: class or function +.. _sec-plugins-hook-octoprint-printer-sdcardupload: + +octoprint.printer.sdcardupload +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: sd_card_upload_hook(printer, filename, path, start_callback, success_callback, failure_callback, *args, **kwargs) + + Via this hook plugins can change the way files are being uploaded to the sd card of the printer. + + Implementations **must** call the provided ``start_callback`` on start of the file transfer and either the ``success_callback`` + or ``failure_callback`` on the end of the file transfer, depending on whether it was successful or not. + + The ``start_callback`` has the following signature: + + .. code-block:: python + + def start_callback(local_filename, remote_filename): + # ... + + ``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file + to be created on the ``sdcard`` storage. + + ``success_callback`` and ``failure_callback`` both have the following signature: + + .. code-block:: python + + def success_or_failure_callback(local_filename, remote_filename, elapsed): + # ... + + ``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file + to be created on the ``sdcard`` storage. ``elapsed`` is the elapsed time in seconds. + + If the hook is going to handle the upload, it must return the (future) remote filename of the file on the ``sdcard`` + storage. If it returns ``None`` (or an otherwise falsy value), OctoPrint will interpret this as the hook not going to + handle the file upload, in which case the next hook or - if no other hook is registered - the default implementation + will be called. + + **Example** + + The following example creates a dummy SD card uploader that does nothing but sleep for ten seconds when a file + is supposed to be uploaded. Note that the long running process of sleeping for ten seconds is extracted into its + own thread, which is important in order to not block the main application! + + .. code-block:: python + + import threading + import logging + import time + + def nop_upload_to_sd(printer, filename, path, sd_upload_started, sd_upload_succeeded, sd_upload_failed, *args, **kwargs): + logger = logging.getLogger(__name__) + + remote_name = printer._get_free_remote_name(filename) + logger.info("Starting dummy SDCard upload from {} to {}".format(filename, remote_name)) + + sd_upload_started(filename, remote_name) + + def process(): + logger.info("Sleeping 10s...") + time.sleep(10) + logger.info("And done!") + sd_upload_succeeded(filename, remote_name, 10) + + thread = threading.Thread(target=process) + thread.daemon = True + thread.start() + + return remote_name + + __plugin_name__ = "No-op SDCard Upload Test" + __plugin_hooks__ = { + "octoprint.printer.sdcardupload": nop_upload_to_sd + } + + .. versionadded:: 1.3.11 + + :param object printer: the :py:class:`~octoprint.printer.PrinterInterface` instance the hook was called from + :param str filename: filename on the ``local`` storage + :param str path: path of the file in the local file system + :param function sd_upload_started: callback for when the upload started + :param function sd_upload_success: callback for successful finish of upload + :param function sd_upload_failure: callback for failure of upload + :return: the name of the file on the ``sdcard`` storage or ``None`` + :rtype: string or ``None`` + +.. _sec-plugins-hook-server-http-after_request: + +octoprint.server.api.after_request +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: after_request_handlers_hook(*args, **kwargs) + + Allows adding additional after-request-handlers to API endpoints defined by OctoPrint itself and installed plugins. + + Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a + usage example. + + .. important:: + + Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully. + +.. _sec-plugins-hook-server-http-before_request: + +octoprint.server.api.before_request +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: after_request_handlers_hook(*args, **kwargs) + + Allows adding additional before-request-handlers to API endpoints defined by OctoPrint itself and installed plugins. + + Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a + usage example. + + .. important:: + + Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully. + +.. _sec-plugins-hook-server-http-access_validator: + +octoprint.server.http.access_validator +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: access_validator_hook(request, *args, **kwargs) + + Allows adding additional access validators to the default tornado routers. + + Your plugin might need to this to restrict acccess to downloads and webcam snapshots further. See the bundled + "Force Login" plugin for a usage example. + + .. important:: + + Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully. + .. _sec-plugins-hook-server-http-bodysize: octoprint.server.http.bodysize @@ -1107,6 +1297,14 @@ octoprint.server.http.routes view of the blueprint will thus not be reachable since processing of the request will directly be handed over to your defined handler class. + .. important:: + + If you want your route to support CORS if it's enabled in OctoPrint, your `RequestHandler `_ + needs to implement the :class:`~octoprint.server.util.tornado.CorsSupportMixin` for this to work. Note that all of + :class:`~octoprint.server.util.tornado.LargeResponseHandler`, :class:`~octoprint.server.util.tornado.UrlProxyHandler`, + :class:`~octoprint.server.util.tornado.StaticDataHandler` and :class:`~octoprint.server.util.tornado.DeprecatedEndpointHandler` + already implement this mixin. + .. important:: Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully. @@ -1134,6 +1332,85 @@ octoprint.server.http.routes :return: a list of 3-tuples with additional routes as defined above :rtype: list +.. _sec-plugins-hook-server-sockjs-authed: + +octoprint.server.sockjs.authed +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: socket_authed_hook(socket, user, *args, **kwargs): + + Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout). + + See the bundled :ref:`Forcelogin Plugin ` for an example on how to utilize this. + + :param object socket: the socket object which is about to be registered + :param object user: the user that got authenticated on the socket, or None if the user got deauthenticated + +.. _sec-plugins-hook-server-sockjs-register: + +octoprint.server.sockjs.register +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: socket_registration_hook(socket, user, *args, **kwargs): + + Allows plugins to prevent a new :ref:`push socket client ` to be registered to the system. + + Handlers should return either ``True`` or ``False``. ``True`` signals to proceed with normal registration. ``False`` + signals to not register the client. + + See the bundled :ref:`Forcelogin Plugin ` for an example on how to utilize this. + + :param object socket: the socket object which is about to be registered + :param object user: the user currently authenticated on the socket - might be None + :return: whether to proceed with registration (``True``) or not (``False``) + :rtype: boolean + +.. _sec-plugins-hook-server-sockjs-emit: + +octoprint.server.sockjs.emit +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: socket_emit_hook(socket, user, message, payload, *args, **kwargs): + + Allows plugins to prevent any messages to be emitted on an existing :ref:`push connection `. + + Handlers should return either ``True`` to allow the message to be emitted, or ``False`` to prevent it. + + See the bundled :ref:`Forcelogin Plugin ` for an example on how to utilize this. + + :param object socket: the socket object on which a message is about to be emitted + :param object user: the user currently authenticated on the socket - might be None + :param string message: the message type about to be emitted + :param dict payload: the payload of the message about to be emitted (may be None) + :return: whether to proceed with sending the message (``True``) or not (``False``) + :rtype: boolean + +.. _sec-plugins-hook-timelapse-extensions: + +octoprint.timelapse.extensions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: timelapse_extension_hook(*args, **kwargs) + + Allows extending the set of supported file extensions for timelapse files. Handlers must return a list of + additional file extensions. + + **Example** + + Allow the management of timelapse GIFs with extension ``gif``. + + .. code-block:: python + + def get_timelapse_extensions(*args, **kwargs): + return ["gif"] + + __plugin_hooks__ = { + "octoprint.timelapse.extensions": get_timelapse_extensions + } + + :return: a list of additional file extensions + :rtype: list + .. _sec-plugins-hook-ui-web-templatetypes: octoprint.ui.web.templatetypes @@ -1249,12 +1526,12 @@ octoprint.ui.web.templatetypes .. _sec-plugins-hook-users-factory: -octoprint.users.factory -~~~~~~~~~~~~~~~~~~~~~~~ +octoprint.access.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 + Return a :class:`~octoprint.access.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: @@ -1265,7 +1542,6 @@ octoprint.users.factory * ``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` @@ -1273,7 +1549,7 @@ octoprint.users.factory 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 + :class:`~octoprint.access.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 diff --git a/docs/plugins/injectedproperties.rst b/docs/plugins/injectedproperties.rst index 7b4bf311a..15ee482d2 100644 --- a/docs/plugins/injectedproperties.rst +++ b/docs/plugins/injectedproperties.rst @@ -41,10 +41,8 @@ An overview of these properties follows. OctoPrint's file manager, an instance of :class:`octoprint.filemanager.FileManager`. ``self._printer`` OctoPrint's printer management object, an instance of :class:`octoprint.printer.PrinterInterface`. -``self._app_session_manager`` - OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`. ``self._user_manager`` - OctoPrint's user manager, an instance of :class:`octoprint.users.UserManager`. + OctoPrint's user manager, an instance of :class:`octoprint.access.users.UserManager`. ``self._connectivity_checker`` OctoPrint's connectivity checker, an instance of :class:`octoprint.util.ConnectivityChecker`. diff --git a/docs/plugins/mixins.rst b/docs/plugins/mixins.rst index fa73c1757..386ff3d26 100644 --- a/docs/plugins/mixins.rst +++ b/docs/plugins/mixins.rst @@ -68,11 +68,14 @@ calls are done is as follows: * Plugins with a return value that is not ``None`` for :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key` for the provided sorting context will be ordered among each other first. If the returned order number is equal for - two or more implementations, the plugin's identifier will be the next sorting criteria. - * After that follow plugins which returned ``None`` (the default). They are sorted by their identifier. + two or more implementations, they will be sorted first by whether they come bundled with OctoPrint or not, then by + their identifier. + * After that follow plugins which returned ``None`` (the default). They are first sorted by whether they come bundled + with OctoPrint or not, then by their identifier. -Example: Consider three plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called -``plugin_a``, ``plugin_b`` and ``plugin_c``. ``plugin_a`` doesn't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`. +Example: Consider four plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called +``plugin_a``, ``plugin_b``, ``plugin_c`` and ``plugin_d``, the latter coming bundled with OctoPrint. ``plugin_a`` +and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`. ``plugin_b`` and ``plugin_c`` both return ``1`` for the sorting context ``StartupPlugin.on_startup``, ``None`` otherwise: .. code-block:: python @@ -99,7 +102,7 @@ Example: Consider three plugin implementations implementing the :class:`~octopri class PluginB(octoprint.plugin.StartupPlugin): - def get_sorting_key(context): + def get_sorting_key(self, context): if context == "StartupPlugin.on_startup": return 1 return None @@ -120,7 +123,7 @@ Example: Consider three plugin implementations implementing the :class:`~octopri class PluginC(octoprint.plugin.StartupPlugin): - def get_sorting_key(context): + def get_sorting_key(self, context): if context == "StartupPlugin.on_startup": return 1 return None @@ -134,13 +137,45 @@ Example: Consider three plugin implementations implementing the :class:`~octopri __plugin_implementation__ = PluginC() +.. code-block:: python + :linenos: + :caption: plugin_d.py + + # in this example this is bundled with OctoPrint + import octoprint.plugin + + class PluginD(octoprint.plugin.StartupPlugin): + + def on_startup(self, *args, **kwargs): + self._logger.info("PluginD starting up") + + def on_after_startup(self, *args, **kwargs): + self._logger.info("PluginD started up") + + __plugin_implementation__ = PluginD() + OctoPrint will detect that ``plugin_b`` and ``plugin_c`` define a order number, and since it's identical for both (``1``) -will order both plugins based on their plugin identifier. ``plugin_a`` doesn't define a sort key and hence will be -put after the other two. The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_a``. +will order both plugins based first on their bundling status and then on their plugin identifier. +``plugin_a`` and ``plugin_d`` don't define a sort key and hence will be +put after the other two, with ``plugin_d`` coming *before* ``plugin_a`` since it comes bundled with OctoPrint. +The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_d``, ``plugin_a``. Now, the execution order of the ``on_after_startup`` method will be determined based on another sorting context, ``StartupPlugin.on_after_startup`` for which all of the plugins return ``None``. Hence, the execution order of the -``on_after_startup`` method will be purely ordered by plugin identifier, ``plugin_a``, ``plugin_b``, ``plugin_c``. +``on_after_startup`` method will be ordered first by bundle status, then by plugin identifier: ``plugin_d``, ``plugin_a``, ``plugin_b``, ``plugin_c``. + +This will result in the following messages to be generated: + +.. code-block:: plain + + Plugin B starting up + Plugin C starting up + Plugin D starting up + Plugin A starting up + Plugin D started up + Plugin A started up + Plugin B started up + Plugin C started up .. _sec-plugins-mixins-injectedproperties: diff --git a/docs/sphinxext/codeblockext.py b/docs/sphinxext/codeblockext.py index a923c0f87..a5ed06548 100644 --- a/docs/sphinxext/codeblockext.py +++ b/docs/sphinxext/codeblockext.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'The MIT License ' @@ -84,7 +84,7 @@ class CodeBlockExt(CodeBlock): return node # replace all created literal_blocks with literal_block_ext instances - return map(find_and_wrap_literal_block, code_block) + return list(map(find_and_wrap_literal_block, code_block)) def _wrap_literal_block(self, node): literal = literal_block_ext.from_literal_block(node) @@ -160,10 +160,10 @@ class PygmentsBridgeExt(object): # for py3, recognize interactive sessions, but do not try parsing... lexer = sphinx.highlighting.lexers['pycon3'] elif lang == 'guess': - try: +# try: lexer = sphinx.highlighting.guess_lexer(source) - except Exception: - lexer = sphinx.highlighting.lexers['none'] +# except Exception: +# lexer = sphinx.highlighting.lexers['none'] else: if lang in sphinx.highlighting.lexers: lexer = sphinx.highlighting.lexers[lang] @@ -255,4 +255,4 @@ def setup(app): handler = (visit_literal_block_ext, depart_literal_block_ext) app.add_node(literal_block_ext, html=handler, latex=handler, text=handler) - return dict(version="0.1") \ No newline at end of file + return dict(version="0.1") diff --git a/docs/sphinxext/onlineinclude.py b/docs/sphinxext/onlineinclude.py index b6d9a1810..4769faa21 100644 --- a/docs/sphinxext/onlineinclude.py +++ b/docs/sphinxext/onlineinclude.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'The MIT License ' diff --git a/run b/run index 1145a24fd..f67e9cbfd 100755 --- a/run +++ b/run @@ -1,4 +1,6 @@ -#!/usr/bin/env python2 +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals import os import sys @@ -8,15 +10,17 @@ basedir = os.path.dirname(os.path.realpath(__file__)) old = os.path.join(basedir, "octoprint") if os.path.exists(old): # rename left-overs from old file structure - print """ + print(""" Found left-overs from old file structure, renaming to "octoprint.backup". Please remove this manually (I don't dare to do so myself since you might have changes in there I don't know anything about). -""" +""") os.rename(old, os.path.join(basedir, "octoprint.backup")) sys.path.insert(0, os.path.join(basedir, "src")) import octoprint +if len(sys.argv) == 1: + sys.argv.append("serve") octoprint.main() diff --git a/scripts/README.md b/scripts/README.md new file mode 100644 index 000000000..8fbc44621 --- /dev/null +++ b/scripts/README.md @@ -0,0 +1,17 @@ +# init/systemd files for OctoPrint. + +Assumes OctoPrint is installed under user pi at /home/pi/OctoPrint/venv/bin/octoprint. If you have a different +setup you'll need to adjust octoprint.default (init) or octoprint.service (systemd) accordingly. + +## init + +``` +octoprint.default => /etc/default/octoprint +octoprint.init => /etc/init.d/octoprint +``` + +## systemd + +``` +octoprint.service => /etc/systemd/service/octoprint.service +``` diff --git a/scripts/octoprint.service b/scripts/octoprint.service new file mode 100644 index 000000000..e71e07b53 --- /dev/null +++ b/scripts/octoprint.service @@ -0,0 +1,12 @@ +[Unit] +Description=The snappy web interface for your 3D printer +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=pi +ExecStart=/home/pi/OctoPrint/venv/bin/octoprint + +[Install] +WantedBy=multi-user.target diff --git a/setup.cfg b/setup.cfg index 4320f0f8a..24ae4b6df 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,6 +1,9 @@ [metadata] license_file = LICENSE.txt +[bdist_wheel] +universal = 1 + [versioneer] VCS = git style = pep440-tag diff --git a/setup.py b/setup.py index f783049cb..e1b79b9bb 100644 --- a/setup.py +++ b/setup.py @@ -9,53 +9,69 @@ import versioneer import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src")) import octoprint_setuptools +import setuptools #----------------------------------------------------------------------------------------------------------------------- +# Supported python versions +# we test against 2.7, 3.6 and 3.7, so that's what we'll mark as supported +PYTHON_REQUIRES = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4" + # Requirements for our application INSTALL_REQUIRES = [ - "flask>=0.12,<0.13", - "werkzeug>=0.11.1,<0.12", - "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.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", + # the following dependencies are non trivial to update since later versions introduce backwards incompatible + # changes that might affect plugins, or due to other observed problems + + "flask>=0.12,<0.13", # newer versions require newer Jinja versions + "Jinja2>=2.8.1,<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 + "tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585 + "regex!=2018.11.6", # avoid broken 2018.11.6. See #2874 + + # anything below this should be checked on releases for new versions + + "Flask-Login>=0.4.1,<0.5", "Flask-Principal>=0.4,<0.5", - "Flask-Babel>=0.11,<0.12", + "Flask-Babel>=0.12,<0.13", "Flask-Assets>=0.12,<0.13", - "markdown>=2.6.4,<2.7", + "werkzeug>=0.14.1,<0.15", + "PyYAML>=3.13,<4", + "markdown>=3.0,<3.1", "pyserial>=3.4,<3.5", - "netaddr>=0.7.17,<0.8", - "watchdog>=0.8.3,<0.9", - "sarge>=0.1.4,<0.2", - "netifaces>=0.10,<0.11", - "pylru>=1.0.9,<1.1", - "rsa>=3.4,<3.5", + "netaddr>=0.7.19,<0.8", + "watchdog>=0.9.0,<0.10", + "sarge==0.1.5post0", + "netifaces>=0.10.7,<0.11", + "pylru>=1.1,<1.2", + "rsa>=4.0,<5", "pkginfo>=1.4.2,<1.5", - "requests>=2.18.4,<3", - "semantic_version>=2.6.0,<2.7", - "psutil>=5.4.5,<5.5", - "Click>=6.7,<6.8", + "requests>=2.20.0,<3", + "semantic_version>=2.6,<2.7", + "psutil>=5.4.8,<5.5", + "Click>=7,<8", "awesome-slugify>=1.6.5,<1.7", "feedparser>=5.2.1,<5.3", - "chainmap>=1.0.2,<1.1", - "future>=0.15,<0.16", - "scandir>=1.3,<1.4", - "websocket-client>=0.40,<0.41", - "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", + "future>=0.17,<0.18", + "websocket-client>=0.53,<0.54", + "python-dateutil>=2.7.5,<2.8", + "wrapt>=1.10.11,<1.11", + "emoji>=0.5.1,<0.6", "frozendict>=1.2,<1.3" ] -if sys.platform == "darwin": - INSTALL_REQUIRES.append("appdirs>=1.4.0") +# Python 2 specific requirements +INSTALL_REQUIRES_PYTHON2 = [ + "futures>=3.2,<3.3", + "monotonic>=1.5,<1.6", + "scandir>=1.9,<1.10", + "chainmap>=1.0.2,<1.1", +] + +# OSX specific requirements +INSTALL_REQUIRES_OSX = [ + "appdirs>=1.4.0", +] # Additional requirements for optional install options EXTRA_REQUIRES = dict( @@ -63,9 +79,12 @@ EXTRA_REQUIRES = dict( develop=[ # Testing dependencies "mock>=2.0.0,<3", - "nose>=1.3.0,<1.4", + "nose>=1.3.7,<1.4", "ddt", + # linter + "flake8", + # Documentation dependencies "sphinx>=1.6,<1.7", "sphinxcontrib-httpdomain", @@ -75,16 +94,30 @@ EXTRA_REQUIRES = dict( # Dependencies for developing OctoPrint plugins plugins=[ - "cookiecutter>=1.5,<1.7" + "cookiecutter>=1.6,<1.7" ] ) -# Additional requirements for setup -SETUP_REQUIRES = [] - # Dependency links for any of the aforementioned dependencies DEPENDENCY_LINKS = [] +# adapted from https://hynek.me/articles/conditional-python-dependencies/ +if int(setuptools.__version__.split(".", 1)[0]) < 18: + # no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies + # would get lost there + assert "bdist_wheel" not in sys.argv + + # add optional dependencies for setuptools versions < 18 that don't yet support environment markers + if sys.version_info[0] < 3: + INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2 + + if sys.platform == "darwin": + INSTALL_REQUIRES += INSTALL_REQUIRES_OSX +else: + # environment markers supported + EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2 + EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX + #----------------------------------------------------------------------------------------------------------------------- # Anything below here is just command setup and general setup configuration @@ -154,10 +187,10 @@ def params(): long_description = read_file_contents(os.path.join(here, "README.md")) long_description_content_type = "text/markdown" + python_requires = PYTHON_REQUIRES install_requires = INSTALL_REQUIRES extras_require = EXTRA_REQUIRES dependency_links = DEPENDENCY_LINKS - setup_requires = SETUP_REQUIRES classifiers = [ "Development Status :: 5 - Production/Stable", @@ -176,6 +209,9 @@ def params(): "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: JavaScript", "Topic :: Printing", diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 63a74684b..2cf6afb59 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -1,7 +1,8 @@ -#!/usr/bin/env python2 -# coding=utf-8 -from __future__ import absolute_import, division, print_function +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals +import io import sys import logging as log @@ -50,15 +51,24 @@ del version_info #~~ custom exceptions -class FatalStartupError(BaseException): - pass +class FatalStartupError(Exception): + def __init__(self, message, cause=None): + self.cause = cause + Exception.__init__(self, message) + + def __str__(self): + result = Exception.__str__(self) + if self.cause: + return "{}: {}".format(result, str(self.cause)) + else: + return result #~~ init methods to bring up platform def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, logging_config=None, debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None, safe_mode=False, ignore_blacklist=False, after_preinit_logging=None, - after_settings=None, after_logging=None, after_safe_mode=None, + after_settings_init=None, after_logging=None, after_safe_mode=None, after_settings_valid=None, after_event_manager=None, after_connectivity_checker=None, after_plugin_manager=None, after_environment_detector=None): kwargs = dict() @@ -70,55 +80,81 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, if callable(after_preinit_logging): after_preinit_logging(**kwargs) - settings = init_settings(basedir, configfile) + try: + settings = init_settings(basedir, configfile) + except Exception as ex: + raise FatalStartupError("Could not initialize settings manager", cause=ex) kwargs["settings"] = settings - if callable(after_settings): - after_settings(**kwargs) + if callable(after_settings_init): + after_settings_init(**kwargs) + + try: + logger = init_logging(settings, + use_logging_file=use_logging_file, + logging_file=logging_file, + default_config=logging_config, + debug=debug, + verbosity=verbosity, + uncaught_logger=uncaught_logger, + uncaught_handler=uncaught_handler) + except Exception as ex: + raise FatalStartupError("Could not initialize logging", cause=ex) - logger = init_logging(settings, - use_logging_file=use_logging_file, - logging_file=logging_file, - default_config=logging_config, - debug=debug, - verbosity=verbosity, - uncaught_logger=uncaught_logger, - uncaught_handler=uncaught_handler) kwargs["logger"] = logger - if callable(after_logging): after_logging(**kwargs) - settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"]) - safe_mode = safe_mode or settings_safe_mode + settings_start_once_in_safemode = "settings" if settings.getBoolean(["server", "startOnceInSafeMode"]) else None + settings_incomplete_startup_safemode = "incomplete_startup" if settings.getBoolean(["server", "incompleteStartup"]) else None + safe_mode = safe_mode or settings_start_once_in_safemode or settings_incomplete_startup_safemode kwargs["safe_mode"] = safe_mode - if callable(after_safe_mode): after_safe_mode(**kwargs) - event_manager = init_event_manager(settings) + # now before we continue, let's make sure *all* our folders are sane + try: + settings.sanity_check_folders() + except Exception as ex: + raise FatalStartupError("Configured folders didn't pass sanity check", cause=ex) + if callable(after_settings_valid): + after_settings_valid(**kwargs) + + try: + event_manager = init_event_manager(settings) + except Exception as ex: + raise FatalStartupError("Could not initialize event manager", cause=ex) kwargs["event_manager"] = event_manager if callable(after_event_manager): after_event_manager(**kwargs) - connectivity_checker = init_connectivity_checker(settings, event_manager) + try: + connectivity_checker = init_connectivity_checker(settings, event_manager) + except Exception as ex: + raise FatalStartupError("Could not initialize connectivity checker", cause=ex) 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 + try: + plugin_manager = init_pluginsystem(settings, + safe_mode=safe_mode, + ignore_blacklist=ignore_blacklist, + connectivity_checker=connectivity_checker) + except Exception as ex: + raise FatalStartupError("Could not initialize plugin manager", cause=ex) + kwargs["plugin_manager"] = plugin_manager if callable(after_plugin_manager): after_plugin_manager(**kwargs) - environment_detector = init_environment_detector(plugin_manager) - kwargs["environment_detector"] = environment_detector + try: + environment_detector = init_environment_detector(plugin_manager) + except Exception as ex: + raise FatalStartupError("Could not initialize environment detector", cause=ex) + kwargs["environment_detector"] = environment_detector if callable(after_environment_detector): after_environment_detector(**kwargs) @@ -291,7 +327,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con config_from_file = {} if os.path.exists(logging_file) and os.path.isfile(logging_file): import yaml - with open(logging_file, "r") as f: + with io.open(logging_file, 'rt', encoding='utf-8') as f: config_from_file = yaml.safe_load(f) # we merge that with the default config @@ -480,7 +516,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None): if os.stat(path).st_mtime + ttl < time.time(): return None - with bom_aware_open(path, encoding="utf-8", mode="r") as f: + with bom_aware_open(path, encoding="utf-8", mode='rt') as f: result = yaml.safe_load(f) if isinstance(result, list): @@ -494,12 +530,12 @@ def get_plugin_blacklist(settings, connectivity_checker=None): if cache is not None: try: - with bom_aware_open(cache, encoding="utf-8", mode="w") as f: + with bom_aware_open(cache, encoding="utf-8", mode='wt') 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)) + except Exception as e: + logger.info("Fetched plugin blacklist but couldn't write it to its cache file: %s", e) + except Exception as e: + logger.info("Unable to fetch plugin blacklist from {}, proceeding without it: {}".format(url, e)) return result try: @@ -526,7 +562,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None): logger.info("Blacklist processing done") return blacklist - except: + except Exception: logger.exception("Something went wrong while processing the plugin blacklist. Proceeding without it.") @@ -593,6 +629,9 @@ def main(): # cut off stuff from the beginning args = args[-1 * sys_args_length:] if sys_args_length else [] + from octoprint.util.fixes import patch_sarge_async_on_py2 + patch_sarge_async_on_py2() + from octoprint.cli import octo octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT") diff --git a/src/octoprint/__main__.py b/src/octoprint/__main__.py index 3dd81998d..23e03429c 100644 --- a/src/octoprint/__main__.py +++ b/src/octoprint/__main__.py @@ -1,6 +1,10 @@ -#!/usr/bin/env python2 -# coding=utf-8 -from __future__ import absolute_import, division, print_function +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +#import sys +#if sys.version_info[0] >= 3: +# raise RuntimeError("Sorry, OctoPrint does not yet support Python 3") if __name__ == "__main__": import octoprint diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py index 9c9eeab62..5895ced6a 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag @@ -9,13 +11,14 @@ # versioneer-0.15+dev (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" -from __future__ import absolute_import, division, print_function import errno +import io import os import re import subprocess import sys +import logging def get_keywords(): @@ -41,7 +44,7 @@ def get_config(): # _version.py cfg = VersioneerConfig() cfg.VCS = "git" - cfg.style = "pep440-post" + cfg.style = "pep440-tag" cfg.tag_prefix = "" cfg.parentdir_prefix = "" cfg.versionfile_source = "src/octoprint/_version.py" @@ -130,7 +133,7 @@ def git_get_keywords(versionfile_abs): # _version.py. keywords = {} try: - f = open(versionfile_abs, "r") + f = io.open(versionfile_abs, "rt", encoding="utf-8") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) @@ -156,11 +159,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = set(r.strip() for r in refnames.strip("()").split(",")) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = set(r[len(TAG):] for r in refs if r.startswith(TAG)) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -169,7 +172,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = set(r for r in refs if re.search(r'\d', r)) if verbose: print("discarding '%s', no digits" % ",".join(refs-tags)) @@ -254,7 +257,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): abbrev_ref_out = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) - if abbrev_ref_out is not None: + if abbrev_ref_out is not None and abbrev_ref_out != "HEAD": pieces["branch"] = abbrev_ref_out.strip() # now we have TAG-NUM-gHEX or HEX @@ -305,17 +308,18 @@ def git_parse_lookup_file(path): if not os.path.exists(path): return [] + import re lookup = [] - with open(path, "r") as f: + with io.open(path, "rt", encoding="utf-8") as f: for line in f: if '#' in line: - line = line[:line.rindex("#")] + line = line[:line.index("#")] line = line.strip() if not line: continue try: - split_line = map(lambda x: x.strip(), line.split()) + split_line = list(map(lambda x: x.strip(), line.split())) if not len(split_line): continue @@ -336,7 +340,8 @@ def git_parse_lookup_file(path): continue lookup.append(entry) - except: + except Exception: + logging.getLogger(__name__).exception("Versioneer problem") break return lookup @@ -354,6 +359,9 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command): raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed") current_branch = stdout.strip() + if current_branch == "HEAD": + raise NotThisMethod("not on a branch") + for matcher, render, tag, ref_commit in lookup: if matcher.match(current_branch): if tag is None or ref_commit is None: @@ -441,6 +449,31 @@ def render_pep440(pieces): return rendered +def render_pep440_tag(pieces): + """TAG[[.postDISTANCE].dev0+gHEX] -- Just the tag if not dirty, else more info + + Useful for projects that want commit based tracking on some branches + but have the master branch only report tags, to allow for commits that + do not modify actual code (e.g. to .github/* or docs). + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + return rendered + + def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. @@ -591,6 +624,8 @@ def render(pieces, style): rendered = render_pep440_old(pieces) elif style == "pep440-dev": rendered = render_pep440_dev(pieces) + elif style == "pep440-tag": + rendered = render_pep440_tag(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": diff --git a/src/octoprint/access/__init__.py b/src/octoprint/access/__init__.py index eed3bf88b..599123f9b 100644 --- a/src/octoprint/access/__init__.py +++ b/src/octoprint/access/__init__.py @@ -1,6 +1,7 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals ADMIN_GROUP = "admins" USER_GROUP = "users" GUEST_GROUP = "guests" +READONLY_GROUP = "readonly" diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py index cfbe4abbc..9694b7d28 100644 --- a/src/octoprint/access/groups.py +++ b/src/octoprint/access/groups.py @@ -1,10 +1,11 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __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 io import logging import os from functools import partial @@ -15,7 +16,7 @@ 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 import ADMIN_GROUP, USER_GROUP, GUEST_GROUP, READONLY_GROUP from octoprint.access.permissions import Permissions, OctoPrintPermission from flask_principal import Need, Permission @@ -90,6 +91,7 @@ class GroupManager(object): "Admins", "Administrators", self.default_permissions_for_group(ADMIN_GROUP), + [], changeable=False, removable=False, save=False) @@ -97,6 +99,7 @@ class GroupManager(object): "Users", "All logged in users", self.default_permissions_for_group(USER_GROUP), + [], default=True, removable=False, toggleable=False, @@ -105,8 +108,17 @@ class GroupManager(object): "Guests", "Anyone who is not currently logged in", self.default_permissions_for_group(GUEST_GROUP), + [], removable=False, toggleable=False, + save=False), + self.add_group(READONLY_GROUP, + "Read-only Access", + "Group to gain read-only access", + self.default_permissions_for_group(READONLY_GROUP), + [], + changeable=False, + removable=False, save=False) def register_listener(self, listener): @@ -115,10 +127,11 @@ class GroupManager(object): 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): + def add_group(self, key, name, description, permissions, subgroups, + 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): + def update_group(self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True): pass def remove_group(self, key, save=True, notify=True): @@ -128,12 +141,19 @@ class GroupManager(object): return None def _to_permissions(self, *permissions): - return filter(lambda x: x is not None, - [Permissions.find(permission) for permission in permissions]) + return list(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 _from_groups(self, *groups): + return [group.key for group in groups] + + def _to_groups(self, *groups): + return filter(lambda x: x is not None, + [self._to_group(g) for g in groups]) + def _to_group(self, group): # noinspection PyCompatibility if isinstance(group, Group): @@ -150,7 +170,7 @@ class GroupManager(object): for listener in self._group_change_listeners: try: getattr(listener, method)(group, *args, **kwargs) - except: + except Exception: self._logger.exception("Error notifying listener {!r} via {}".format(listener, method)) class GroupChangeListener(object): @@ -164,6 +184,9 @@ class GroupChangeListener(object): def on_group_permissions_changed(self, group, added=None, removed=None): pass + def on_group_subgroups_changed(self, group, added=None, removed=None): + pass + class FilebasedGroupManager(GroupManager): def __init__(self, path=None): @@ -183,45 +206,53 @@ class FilebasedGroupManager(GroupManager): def _load(self): if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile): try: - with open(self._groupfile, "r") as f: + with io.open(self._groupfile, 'rt', encoding='utf-8') as f: data = yaml.safe_load(f) - if not "groups" in data: - groups = data - data = dict(groups=groups) + if not "groups" in data: + groups = data + data = dict(groups=groups) - groups = data.get("groups", dict()) - tracked_permissions = data.get("tracked", list()) + 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 + 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 + 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) + 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: + subgroups = attributes.get("subgroups", []) + + group = Group(key, attributes.get("name", ""), + description=attributes.get("description", ""), + permissions=permissions, + subgroups=subgroups, + default=attributes.get("default", False), + removable=removable, + changeable=changeable, + toggleable=toggleable) + self._groups[key] = group + + for group in self._groups.values(): + group._subgroups = self._to_groups(*group._subgroups) + + except Exception: self._logger.exception("Error while loading groups from file {}".format(self._groupfile)) def _save(self, force=False): @@ -235,15 +266,16 @@ class FilebasedGroupManager(GroupManager): name=group._name, description=group._description, permissions=self._from_permissions(*group._permissions), + subgroups=self._from_groups(*group._subgroups), 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: + with atomic_write(self._groupfile, mode='wt', permissions=0o600, max_permissions=0o666) as f: import yaml - yaml.safe_dump(data, f, default_flow_style=False, indent=" ", allow_unicode=True) + yaml.safe_dump(data, f, default_flow_style=False, indent=4, allow_unicode=True) self._dirty = False self._load() @@ -260,9 +292,9 @@ class FilebasedGroupManager(GroupManager): return None return self._groups.get(key) - def add_group(self, key, name, description, permissions, default=False, removable=True, + def add_group(self, key, name, description, permissions, subgroups, default=False, removable=True, changeable=True, toggleable=True, overwrite=False, notify=True, save=True): - if key in self._groups.keys() and not overwrite: + if key in self._groups and not overwrite: raise GroupAlreadyExists(key) if not permissions: @@ -271,9 +303,13 @@ class FilebasedGroupManager(GroupManager): permissions = self._to_permissions(*permissions) assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions))) + subgroups = self._to_groups(*subgroups) + assert(all(map(lambda g: isinstance(g, Group), subgroups))) + group = Group(key, name, description=description, permissions=permissions, + subgroups=subgroups, default=default, changeable=changeable, removable=removable, @@ -305,7 +341,7 @@ class FilebasedGroupManager(GroupManager): if notify: self._notify_listeners("removed", group) - def update_group(self, key, description=None, permissions=None, default=None, save=True, notify=True): + def update_group(self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True): group = self._to_group(key) if group is None: raise UnknownGroup(key) @@ -334,6 +370,21 @@ class FilebasedGroupManager(GroupManager): notifications.append((("permissions_changed", group), dict(added=added_permissions, removed=removed_permissions))) + if subgroups is not None: + subgroups = self._to_groups(*subgroups) + assert(all(map(lambda g: isinstance(g, Group), subgroups))) + + removed_subgroups = list(set(group._subgroups) - set(subgroups)) + added_subgroups = list(set(subgroups) - set(group._subgroups)) + + if removed_subgroups: + self._dirty = group.remove_subgroups_from_group(removed_subgroups) + if added_subgroups: + self._dirty = group.add_subgroups_to_group(added_subgroups) + + notifications.append((("subgroups_changed", group), + dict(added=added_subgroups, removed=removed_subgroups))) + if default is not None: group.change_default(default) self._dirty = True @@ -368,11 +419,12 @@ class GroupCantBeChanged(Exception): class Group(object): - def __init__(self, key, name, description="", permissions=None, default=False, removable=True, changeable=True, toggleable=True): + def __init__(self, key, name, description="", permissions=None, subgroups=None, default=False, removable=True, changeable=True, toggleable=True): self._key = key self._name = name self._description = description self._permissions = permissions + self._subgroups = subgroups self._default = default self._removable = removable self._changeable = changeable @@ -384,7 +436,8 @@ class Group(object): key=self.key, name=self.get_name(), description=self._description, - permissions=map(lambda p: p.key, self._permissions), + permissions=list(map(lambda p: p.key, self._permissions)), + subgroups=list(map(lambda g: g.key, self._subgroups)), needs=OctoPrintPermission.convert_needs_to_dict(self.needs), default=self._default, removable=self._removable, @@ -452,6 +505,45 @@ class Group(object): return dirty + def add_subgroups_to_group(self, subgroups): + """Adds a list of subgroups to a group""" + if not self.is_changeable(): + raise GroupCantBeChanged(self.key) + + # Make sure the subgroups variable is of type list + if not isinstance(subgroups, list): + subgroups = [subgroups] + + assert(all(map(lambda g: isinstance(g, Group), subgroups))) + + dirty = False + for group in subgroups: + if group.is_toggleable() and group not in self._subgroups: + self._subgroups.append(group) + dirty = True + + return dirty + + def remove_subgroups_from_group(self, subgroups): + """Removes a list of subgroups from a group""" + """Adds a list of subgroups to a group""" + if not self.is_changeable(): + raise GroupCantBeChanged(self.key) + + # Make sure the subgroups variable is of type list + if not isinstance(subgroups, list): + subgroups = [subgroups] + + assert (all(map(lambda g: isinstance(g, Group), subgroups))) + + dirty = False + for group in subgroups: + if group.is_toggleable() and group in self._subgroups: + self._subgroups.remove(group) + dirty = True + + return dirty + def change_default(self, default): """Changes the default flag of a Group""" if not self.is_changeable(): @@ -468,7 +560,11 @@ class Group(object): if Permissions.ADMIN in self._permissions: return Permissions.all() - return filter(lambda p: p is not None, self._permissions) + return list(filter(lambda p: p is not None, self._permissions)) + + @property + def subgroups(self): + return filter(lambda g: g is not None, self._subgroups) @property def needs(self): @@ -476,6 +572,8 @@ class Group(object): needs.add(GroupNeed(self.key)) for p in self.permissions: needs = needs.union(p.needs) + for g in self.subgroups: + needs = needs.union(g.needs) return needs @@ -501,6 +599,3 @@ class Group(object): 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 index 1a632bfaf..035814df0 100644 --- a/src/octoprint/access/permissions.py +++ b/src/octoprint/access/permissions.py @@ -1,11 +1,11 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __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 future.utils import with_metaclass from flask import g, abort from flask_babel import gettext from flask_principal import Permission, PermissionDenied, RoleNeed, Need @@ -16,7 +16,7 @@ from collections import OrderedDict, defaultdict # noinspection PyCompatibility from past.builtins import basestring -from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP +from octoprint.access import ADMIN_GROUP, USER_GROUP, READONLY_GROUP class OctoPrintPermission(Permission): @@ -44,7 +44,7 @@ class OctoPrintPermission(Permission): def __init__(self, name, description, *needs, **kwargs): self._name = name self._description = description - self._dangerous = kwargs.pop("dangerous", False) == True + self._dangerous = kwargs.pop("dangerous", False) self._default_groups = kwargs.pop("default_groups", []) self._key = None @@ -217,10 +217,10 @@ class PermissionsMetaClass(type): return permission def all(cls): - return cls.permissions.values() + return list(cls.permissions.values()) def filter(cls, cb): - return filter(cb, cls.all()) + return list(filter(cb, cls.all())) def find(cls, p, filter=None): key = None @@ -249,8 +249,7 @@ class PermissionsMetaClass(type): return None -class Permissions(object): - __metaclass__ = PermissionsMetaClass +class Permissions(with_metaclass(PermissionsMetaClass)): # Special permission ADMIN = OctoPrintPermission("Admin", @@ -263,7 +262,7 @@ class Permissions(object): gettext("Allows to gather status information, e.g. job progress, " "printer state, temperatures, ..."), RoleNeed("status"), - default_groups=[USER_GROUP, GUEST_GROUP]) + default_groups=[USER_GROUP, READONLY_GROUP]) CONNECTION = OctoPrintPermission("Connection", gettext("Allows to connect to and disconnect from a printer"), @@ -273,7 +272,7 @@ class Permissions(object): WEBCAM = OctoPrintPermission("Webcam", gettext("Allows to watch the webcam stream"), RoleNeed("webcam"), - default_groups=[USER_GROUP, GUEST_GROUP]) + default_groups=[USER_GROUP, READONLY_GROUP]) SYSTEM = OctoPrintPermission("System", gettext("Allows to run system commands, e.g. restart OctoPrint, " @@ -285,7 +284,7 @@ class Permissions(object): 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]) + default_groups=[USER_GROUP, READONLY_GROUP]) FILES_UPLOAD = OctoPrintPermission("File Upload", gettext("Allows users to upload new files"), RoleNeed("files_upload"), @@ -294,7 +293,7 @@ class Permissions(object): 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]) + default_groups=[USER_GROUP, READONLY_GROUP]) FILES_DELETE = OctoPrintPermission("File Delete", gettext("Allows users to delete files"), RoleNeed("files_delete"), FILES_LIST, @@ -314,13 +313,13 @@ class Permissions(object): gettext("Allows access to the GCODE viewer. Includes the \"File Download\"" "permission."), RoleNeed("gcodeviewer"), FILES_DOWNLOAD, - default_groups=[USER_GROUP, GUEST_GROUP]) + default_groups=[USER_GROUP, READONLY_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]) + default_groups=[USER_GROUP, READONLY_GROUP]) CONTROL = OctoPrintPermission("Control", gettext("Allows to control of the printer by using the temperature controls," @@ -336,11 +335,11 @@ class Permissions(object): TIMELAPSE_LIST = OctoPrintPermission("Timelapse List", gettext("Allows to list timelapse videos"), RoleNeed("timelapse_list"), - default_groups=[USER_GROUP, GUEST_GROUP]) + default_groups=[USER_GROUP, READONLY_GROUP]) TIMELAPSE_DOWNLOAD = OctoPrintPermission("Timelapse Download", gettext("Allows to download timelapse videos"), RoleNeed("timelapse_download"), - default_groups=[USER_GROUP, GUEST_GROUP]) + default_groups=[USER_GROUP, READONLY_GROUP]) TIMELAPSE_DELETE = OctoPrintPermission("Timelapse Delete", gettext("Allows to delete timelapse videos and unrendered timelapses"), RoleNeed("timelapse_delete"), diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index fda4c675b..5ba09e617 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from flask_login import UserMixin, AnonymousUserMixin from werkzeug.local import LocalProxy import hashlib +import io import os import yaml import uuid @@ -19,10 +20,11 @@ import logging from builtins import range, bytes from octoprint.settings import settings -from octoprint.util import atomic_write, to_str, deprecated +from octoprint.util import atomic_write, to_bytes, deprecated from octoprint.access.permissions import Permissions, OctoPrintPermission from octoprint.access.groups import GroupChangeListener, Group +from past.builtins import basestring class UserManager(GroupChangeListener, object): def __init__(self, group_manager): @@ -87,8 +89,10 @@ class UserManager(GroupChangeListener, object): 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)) + try: + listener.on_user_logged_in(user) + except Exception: + self._logger.exception("Error in on_user_logged_in on {!r}".format(listener)) self._logger.debug("Logged in user: %r" % user) @@ -117,8 +121,10 @@ class UserManager(GroupChangeListener, object): 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)) + try: + listener.on_user_logged_out(user) + except Exception: + self._logger.exception("Error in on_user_logged_out on {!r}".format(listener)) self._logger.debug("Logged out user: %r" % user) @@ -142,7 +148,7 @@ class UserManager(GroupChangeListener, object): settings().set(["accessControl", "salt"], salt) settings().save() - return hashlib.sha512(to_str(password, encoding="utf-8", errors="replace") + to_str(salt)).hexdigest() + return hashlib.sha512(to_bytes(password, encoding="utf-8", errors="replace") + to_bytes(salt)).hexdigest() def check_password(self, username, password): user = self.find_user(username) @@ -255,7 +261,17 @@ class UserManager(GroupChangeListener, object): try: for user in users: listener.on_user_modified(user) - except: + except Exception: + self._logger.exception("Error in on_user_modified on {!r}".format(listener)) + + def on_group_subgroups_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: + # noinspection PyBroadException + try: + for user in users: + listener.on_user_modified(user) + except Exception: self._logger.exception("Error in on_user_modified on {!r}".format(listener)) def _trigger_on_user_modified(self, user): @@ -284,14 +300,14 @@ class UserManager(GroupChangeListener, object): try: for user in users: listener.on_user_modified(user) - except: + except Exception: 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: + except Exception: self._logger.exception("Error in on_user_removed on {!r}".format(listener)) #~~ Deprecated methods follow @@ -432,10 +448,9 @@ class FilebasedUserManager(UserManager): 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: + with io.open(self._userfile, 'rt', encoding='utf-8') as f: data = yaml.safe_load(f) - for name in data.keys(): - attributes = data[name] + for name, attributes in data.items(): permissions = [] if "permissions" in attributes: permissions = attributes["permissions"] @@ -480,9 +495,7 @@ class FilebasedUserManager(UserManager): return data = {} - for name in self._users.keys(): - user = self._users[name] - + for name, user in self._users.items(): if not user or not isinstance(user, User): continue @@ -498,8 +511,8 @@ class FilebasedUserManager(UserManager): "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) + with atomic_write(self._userfile, mode='wt', permissions=0o600, max_permissions=0o666) as f: + yaml.safe_dump(data, f, default_flow_style=False, indent=4, allow_unicode=True) self._dirty = False self._load() @@ -522,7 +535,7 @@ class FilebasedUserManager(UserManager): groups = self._group_manager.default_groups groups = self._to_groups(*groups) - if username in self._users.keys() and not overwrite: + if username in self._users and not overwrite: raise UserAlreadyExists(username) self._users[username] = User(username, UserManager.create_password_hash(password), active, permissions, groups, apikey=apikey) @@ -530,7 +543,7 @@ class FilebasedUserManager(UserManager): self._save() def change_user_activation(self, username, active): - if username not in self._users.keys(): + if username not in self._users: raise UnknownUser(username) if self._users[username].is_active != active: @@ -541,7 +554,7 @@ class FilebasedUserManager(UserManager): self._trigger_on_user_modified(username) def change_user_permissions(self, username, permissions): - if username not in self._users.keys(): + if username not in self._users: raise UnknownUser(username) user = self._users[username] @@ -564,7 +577,7 @@ class FilebasedUserManager(UserManager): self._trigger_on_user_modified(username) def add_permissions_to_user(self, username, permissions): - if username not in self._users.keys(): + if username not in self._users: raise UnknownUser(username) if self._users[username].add_permissions_to_user(self._to_permissions(*permissions)): @@ -573,7 +586,7 @@ class FilebasedUserManager(UserManager): self._trigger_on_user_modified(username) def remove_permissions_from_user(self, username, permissions): - if username not in self._users.keys(): + if username not in self._users: raise UnknownUser(username) if self._users[username].remove_permissions_from_user(self._to_permissions(*permissions)): @@ -583,7 +596,7 @@ class FilebasedUserManager(UserManager): def remove_permissions_from_users(self, permissions): modified = [] - for user in self._users.keys(): + for user in self._users: dirty = user.remove_permissions_from_user(self._to_permissions(*permissions)) if dirty: self._dirty = True @@ -595,7 +608,7 @@ class FilebasedUserManager(UserManager): self._trigger_on_user_modified(username) def change_user_groups(self, username, groups): - if username not in self._users.keys(): + if username not in self._users: raise UnknownUser(username) user = self._users[username] @@ -615,7 +628,7 @@ class FilebasedUserManager(UserManager): 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(): + if username not in self._users: raise UnknownUser(username) if self._users[username].add_groups_to_user(self._to_groups(*groups)): @@ -628,7 +641,7 @@ class FilebasedUserManager(UserManager): 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(): + if username not in self._users: raise UnknownUser(username) if self._users[username].remove_groups_from_user(self._to_groups(*groups)): @@ -642,8 +655,8 @@ class FilebasedUserManager(UserManager): 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)) + for username, user in self._users.items(): + dirty = user.remove_groups_from_user(self._to_groups(*groups)) if dirty: self._dirty = True modified.append(username) @@ -655,7 +668,7 @@ class FilebasedUserManager(UserManager): self._trigger_on_user_modified(username) def change_user_password(self, username, password): - if not username in self._users.keys(): + if not username in self._users: raise UnknownUser(username) passwordHash = UserManager.create_password_hash(password) @@ -666,7 +679,7 @@ class FilebasedUserManager(UserManager): self._save() def change_user_setting(self, username, key, value): - if not username in self._users.keys(): + if not username in self._users: raise UnknownUser(username) user = self._users[username] @@ -688,21 +701,21 @@ class FilebasedUserManager(UserManager): self._save() def get_all_user_settings(self, username): - if not username in self._users.keys(): + if not username in self._users: 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(): + if not username in self._users: 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(): + if not username in self._users: raise UnknownUser(username) user = self._users[username] @@ -712,7 +725,7 @@ class FilebasedUserManager(UserManager): return user._apikey def delete_api_key(self, username): - if not username in self._users.keys(): + if not username in self._users: raise UnknownUser(username) user = self._users[username] @@ -723,7 +736,7 @@ class FilebasedUserManager(UserManager): def remove_user(self, username): UserManager.remove_user(self, username) - if not username in self._users.keys(): + if not username in self._users: raise UnknownUser(username) del self._users[username] @@ -737,7 +750,7 @@ class FilebasedUserManager(UserManager): return user if userid is not None: - if userid not in self._users.keys(): + if userid not in self._users: return None return self._users[userid] @@ -765,21 +778,30 @@ class FilebasedUserManager(UserManager): # call parent UserManager.on_group_permissions_changed(self, group, added=added, removed=removed) + def on_group_subgroups_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_subgroups_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]))) + (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]))) + (Permissions.find(permission) for permission in permissions)))) def _from_groups(self, *groups): - return list(set([group.key for group in groups])) + return list(set(group.key for group in groups)) def _from_permissions(self, *permissions): - return list(set([permission.key for permission in permissions])) + return list(set(permission.key for permission in permissions)) # ~~ Deprecated methods follow @@ -791,6 +813,39 @@ class FilebasedUserManager(UserManager): deleteApiKey = deprecated("deleteApiKey has been renamed to delete_api_key", includedoc="Replaced by :func:`delete_api_key`", since="1.4.0")(delete_api_key) + 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) ##~~ Exceptions @@ -894,8 +949,8 @@ class User(UserMixin): 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), + "permissions": list(map(lambda p: p.key, self._permissions)), + "groups": list(map(lambda g: g.key, self._groups)), "needs": OctoPrintPermission.convert_needs_to_dict(self.needs), "apikey": self._apikey, "settings": self._settings, @@ -1037,7 +1092,7 @@ class User(UserMixin): if Permissions.ADMIN in self._permissions: return Permissions.all() - return filter(lambda p: p is not None, self._permissions) + return list(filter(lambda p: p is not None, self._permissions)) @property def groups(self): diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index 34ad3f30e..eecebe76c 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -1,11 +1,12 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click +click.disable_unicode_literals_warning = True import octoprint import sys diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index 34c90d78d..6bc902472 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -1,10 +1,11 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import click +click.disable_unicode_literals_warning = True #~~ "octoprint util" commands @@ -70,4 +71,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle 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)) + click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=4, allow_unicode=True)) + +if __name__ == "__main__": + gcode_command() diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index b40f710c3..01e316319 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -1,10 +1,13 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click +click.disable_unicode_literals_warning = True + +import io import json import octoprint_client @@ -12,6 +15,7 @@ import octoprint_client from octoprint.cli import get_ctx_obj_option, bulk_options from octoprint import init_settings, FatalStartupError +from past.builtins import unicode class JsonStringParamType(click.ParamType): name = "json" @@ -19,7 +23,7 @@ class JsonStringParamType(click.ParamType): def convert(self, value, param, ctx): try: return json.loads(value) - except: + except Exception: self.fail("%s is not a valid json string" % value, param, ctx) @@ -143,16 +147,16 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): """POSTs JSON data to the specified server path, taking the data from the specified file.""" if json_flag or yaml_flag: if json_flag: - with open(file_path, "rb") as fp: + with io.open(file_path, 'rt') as fp: data = json.load(fp) else: import yaml - with open(file_path, "rb") as fp: + with io.open(file_path, 'rt') as fp: data = yaml.safe_load(fp) r = ctx.obj.client.post_json(path, data, timeout=timeout) else: - with open(file_path, "rb") as fp: + with io.open(file_path, 'rb') as fp: data = fp.read() r = ctx.obj.client.post(path, data, timeout=timeout) diff --git a/src/octoprint/cli/config.py b/src/octoprint/cli/config.py index 744cfee43..c6f2a4df8 100644 --- a/src/octoprint/cli/config.py +++ b/src/octoprint/cli/config.py @@ -1,11 +1,12 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click +click.disable_unicode_literals_warning = True import logging from octoprint import init_settings, FatalStartupError @@ -17,7 +18,7 @@ import pprint def _to_settings_path(path): if not isinstance(path, (list, tuple)): - path = filter(lambda x: x, map(lambda x: x.strip(), path.split("."))) + path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split(".")))) return path def _set_helper(settings, path, value, data_type=None): @@ -207,7 +208,7 @@ def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False): if as_json: output = json.dumps(value) elif as_yaml: - output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True) + output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True) elif as_raw: output = value else: @@ -232,7 +233,7 @@ def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False): if as_json: output = json.dumps(value) elif as_yaml: - output = yaml.safe_dump(value, default_flow_style=False, indent=" ", allow_unicode=True) + output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True) elif as_raw: output = value else: diff --git a/src/octoprint/cli/dev.py b/src/octoprint/cli/dev.py index 0d8dd57a1..a9649cd16 100644 --- a/src/octoprint/cli/dev.py +++ b/src/octoprint/cli/dev.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms import click +click.disable_unicode_literals_warning = True from past.builtins import basestring @@ -116,7 +117,8 @@ class OctoPrintDevelCommands(click.MultiCommand): if key in options: val = options[key] else: - raw = raw if isinstance(raw, basestring) else str(raw) + if not isinstance(raw, basestring): + raw = str(raw) val = env.from_string(raw).render(cookiecutter=cookiecutter_dict) if not no_input: diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index facfc80cb..f3b791637 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -1,11 +1,12 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click +click.disable_unicode_literals_warning = True import logging from octoprint.cli import pass_octoprint_ctx, OctoPrintContext, get_ctx_obj_option @@ -88,10 +89,10 @@ class OctoPrintPluginCommands(click.MultiCommand): commands = hook(self, pass_octoprint_ctx) for command in commands: if not isinstance(command, click.Command): - self._logger.warn("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command)) + self._logger.warning("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command)) continue result[name + self.sep + command.name] = command - except: + except Exception: self._logger.exception("Error while retrieving cli commands for plugin {}".format(name)) return result diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 1e7a98f19..e86b524d8 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -1,11 +1,12 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click +click.disable_unicode_literals_warning = True import logging import sys @@ -26,6 +27,15 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi logger.info("Starting OctoPrint {}".format(__display_version__)) if safe_mode: logger.info("Starting in SAFE MODE. Third party plugins will be disabled!") + if safe_mode == "flag": + reason = "command line flag" + elif safe_mode == "settings": + reason = "setting in config.yaml" + elif safe_mode == "incomplete_startup": + reason = "problem during last startup" + else: + reason = "unknown" + logger.info("Reason for safe mode: {}".format(reason)) if recorder and len(recorder): logger.info(get_divider_line("-", "Logged during platform initialization:")) @@ -82,12 +92,16 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi 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) + logger = logging.getLogger("octoprint.startup").fatal + echo = lambda x: click.echo(x, err=True) + + for method in logger, echo: + method(str(e)) + method("There was a fatal error starting up OctoPrint.") + else: from octoprint.server import Server octoprint_server = Server(settings=settings, @@ -175,7 +189,7 @@ def serve_command(ctx, **kwargs): basedir = get_value("basedir") configfile = get_value("configfile") verbosity = get_value("verbosity") - safe_mode = get_value("safe_mode") + safe_mode = "flag" if get_value("safe_mode") else None ignore_blacklist = get_value("ignore_blacklist") run_server(basedir, configfile, host, port, debug, @@ -213,7 +227,7 @@ if sys.platform != "win32" and sys.platform != "darwin": basedir = get_value("basedir") configfile = get_value("configfile") verbosity = get_value("verbosity") - safe_mode = get_value("safe_mode") + safe_mode = "flag" if get_value("safe_mode") else None ignore_blacklist = get_value("ignore_blacklist") if pid is None: diff --git a/src/octoprint/comm/__init__.py b/src/octoprint/comm/__init__.py index 314566f29..ff9d7d326 100644 --- a/src/octoprint/comm/__init__.py +++ b/src/octoprint/comm/__init__.py @@ -1,7 +1,6 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals -__author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/src/octoprint/comm/job/__init__.py b/src/octoprint/comm/job/__init__.py index c37129446..04b7c099f 100644 --- a/src/octoprint/comm/job/__init__.py +++ b/src/octoprint/comm/job/__init__.py @@ -1,5 +1,8 @@ -from __future__ import absolute_import, unicode_literals +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import os @@ -128,7 +131,7 @@ class Printjob(ProtocolListener, ListenerAware): def event_payload(self): payload = copy.deepcopy(self._event_data) - payload["user"] = self._user + payload["owner"] = self._user return payload def process_job_started(self): @@ -313,7 +316,7 @@ class LocalFilePrintjob(StoragePrintjob): if self._handle is not None: try: self._handle.close() - except: + except Exception: pass self._handle = None diff --git a/src/octoprint/comm/protocol/__init__.py b/src/octoprint/comm/protocol/__init__.py index 5d125b21d..fab378997 100644 --- a/src/octoprint/comm/protocol/__init__.py +++ b/src/octoprint/comm/protocol/__init__.py @@ -1,9 +1,8 @@ -# coding=utf-8 -from __future__ import absolute_import, print_function, unicode_literals +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals -__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" +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.transport import TransportListener, TransportState from octoprint.plugin import plugin_manager @@ -26,16 +25,16 @@ def register_protocols(): register_protocol(ReprapGcodeProtocol) # more protocols provided by plugins - hooks = plugin_manager().get_hooks(b"octoprint.comm.protocol.register") + hooks = plugin_manager().get_hooks("octoprint.comm.protocol.register") for name, hook in hooks.items(): try: protocols = hook() for protocol in protocols: try: register_protocol(protocol) - except: + except Exception: logger.exception("Error while registering protocol class {} for plugin {}".format(protocol, name)) - except: + except Exception: logger.exception("Error executing octoprint.comm.protocol.register hook for plugin {}".format(name)) @@ -193,7 +192,7 @@ class Protocol(ListenerAware, TransportListener): if self._transport.state == TransportState.CONNECTED: try: self._transport.disconnect() - except: + except Exception: self._logger.exception("Error while disconnecting from transport {}".format(self._transport)) error = True @@ -202,26 +201,26 @@ class Protocol(ListenerAware, TransportListener): else: self.state = ProtocolState.DISCONNECTED - def process(self, job, position=0, tags=None): + def process(self, job, position=0, user=None, tags=None): if not job.can_process(self): raise ValueError("Job {} cannot be processed with protocol {}".format(job, self)) self._job = job self._job.register_listener(self) self._job.process(self, position=position, tags=tags) - def pause_processing(self, tags=None): + def pause_processing(self, user=None, tags=None): if self._job is None or self.state != ProtocolState.PROCESSING: return self.state = ProtocolState.PAUSING self._job.pause() - def resume_processing(self, tags=None): + def resume_processing(self, user=None, tags=None): if self._job is None or self.state != ProtocolState.PAUSED: return self.state = ProtocolState.RESUMING self._job.resume() - def cancel_processing(self, error=False, tags=None): + def cancel_processing(self, error=False, user=None, tags=None): if self._job is not None and self.state in (ProtocolState.PROCESSING, ProtocolState.PAUSED): self.state = ProtocolState.CANCELLING self.notify_listeners("on_protocol_job_cancelling", self, self._job) @@ -230,16 +229,18 @@ class Protocol(ListenerAware, TransportListener): def can_send(self): return True - def send_commands(self, command_type=None, *commands): + def send_commands(self, command_type=None, tags=None, *commands): pass - def send_script(self, script, context=None): + def send_script(self, script, context=None, user=None, tags=None): """ Sends the specified script/the GCODE script with the specified name. Args: script (GcodeScript or unicode): Script or name of the script to send context (dict): Additional render context + user (str): The user on whose behalf the script is being sent. May be None + tags (set): And tags to send with the script commands. May be None """ pass diff --git a/src/octoprint/comm/protocol/reprap/__init__.py b/src/octoprint/comm/protocol/reprap/__init__.py index bff0fce05..d04399b7c 100644 --- a/src/octoprint/comm/protocol/reprap/__init__.py +++ b/src/octoprint/comm/protocol/reprap/__init__.py @@ -1,9 +1,8 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals, print_function, division +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals -__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" +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.protocol import Protocol, ThreeDPrinterProtocolMixin, FileStreamingProtocolMixin, \ MotorControlProtocolMixin, FanControlProtocolMixin, ProtocolState @@ -29,7 +28,7 @@ from octoprint.comm.util.parameters import ChoiceType, Value from octoprint.comm.job import LocalGcodeFilePrintjob, SDFilePrintjob, \ LocalGcodeStreamjob, CopyJobMixin -from octoprint.util import TypedQueue, TypeAlreadyInQueue, ResettableTimer, to_str, to_unicode, protectedkeydict, CountedEvent, monotonic_time +from octoprint.util import TypedQueue, TypeAlreadyInQueue, ResettableTimer, to_bytes, to_unicode, protectedkeydict, CountedEvent, monotonic_time from octoprint.events import Events @@ -324,7 +323,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt transport = PushingTransportWrapper(LineAwareTransportWrapper(transport), timeout=5.0) self._send_queue_active = True - self._sending_thread = threading.Thread(target=self._send_loop, name=b"comm.sending_thread") + self._sending_thread = threading.Thread(target=self._send_loop, name="comm.sending_thread") self._sending_thread.daemon = True self._sending_thread.start() @@ -332,8 +331,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt transport_args=transport_args, transport_kwargs=transport_kwargs) - - def process(self, job, position=0, tags=None): + def process(self, job, position=0, user=None, tags=None): if isinstance(job, LocalGcodeStreamjob): self._internal_flags["only_from_job"] = True self._internal_flags["trigger_events"] = False @@ -368,7 +366,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt self.send_commands(SendQueueMarker(finalize)) self._continue_sending() - def cancel_processing(self, error=False, tags=None, log_position=True): + def cancel_processing(self, error=False, user=None, tags=None, log_position=True): if self.state not in (ProtocolState.PROCESSING, ProtocolState.PAUSED, ProtocolState.PAUSING): return @@ -440,7 +438,8 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt self.send_commands(SendQueueMarker(finalize)) self._continue_sending() - def pause_processing(self, tags=None, log_position=True, suppress_scripts_and_commands=False): + def pause_processing(self, user=None, tags=None, log_position=True, suppress_scripts_and_commands=False): + # TODO sync with comm.py if self._job is None or self.state != ProtocolState.PROCESSING: return @@ -485,7 +484,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt else: self._pause_preparation_done(check_timer=False, suppress_script=suppress_scripts_and_commands) - def resume_processing(self, tags=None, only_adjust_state=False): + def resume_processing(self, user=None, tags=None, only_adjust_state=False): if only_adjust_state: self.state = ProtocolState.PROCESSING else: @@ -587,10 +586,10 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt return self._is_operational() and not self._internal_flags["long_running_command"] and not self._internal_flags["heating"] and not self._internal_flags["dwelling_until"] def send_commands(self, *commands, **kwargs): - command_type = kwargs.get(b"command_type") - on_sent = kwargs.get(b"on_sent") - tags = kwargs.get(b"tags") - force = kwargs.get(b"force", False) + command_type = kwargs.get("command_type") + on_sent = kwargs.get("on_sent") + tags = kwargs.get("tags") + force = kwargs.get("force", False) def sanitize_command(c, ct, t): if isinstance(c, Command): @@ -684,7 +683,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt return self.interval.get("temperature_target_set", target_default) bed = self._internal_flags["temperatures"].bed - if bed and len(bed) > 0 and bed[1] > threshold: + if bed and len(bed) > 0 and bed[1] is not None and bed[1] > threshold: return self.interval.get("temperature_target_set", target_default) return self.interval.get("temperature_idle") @@ -725,7 +724,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt time.sleep(.1) except UnknownScript: pass - except: + except Exception: self._logger.exception("Error while trying to send beforePrinterDisconnected script") self._send_queue_active = False @@ -1172,7 +1171,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt for hook in self._action_hooks: try: self._action_hooks[hook](self, line, action) - except: + except Exception: self._logger.exception("Error while calling hook {} with action command {}".format(self._action_hooks[hook], action)) continue @@ -1463,7 +1462,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt self._command_queue.task_done() def _send_commands(self, *commands, **kwargs): - command_type = kwargs.pop(b"command_type", None) + command_type = kwargs.pop("command_type", None) result = False for command in commands: if len(commands) > 1: @@ -1569,7 +1568,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt def _send_loop(self): """ - The send loop is reponsible of sending commands in ``self._send_queue`` over the line, if it is cleared for + The send loop is responsible of sending commands in ``self._send_queue`` over the line, if it is cleared for sending (through received ``ok`` responses from the printer's firmware. """ @@ -1602,7 +1601,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt if linenumber is not None: # line number predetermined - this only happens for resends, so we'll use the number and # send directly without any processing (since that already took place on the first sending!) - self._do_send_with_checksum(to_str(command.line), linenumber) + self._do_send_with_checksum(to_bytes(command.line), linenumber) else: if not processed: @@ -1703,7 +1702,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt # now we just wait for the next clear and then start again self._clear_to_send.wait() - except: + except Exception: self._logger.exception("Caught an exception in the send loop") self.notify_listeners("on_protocol_log", self, "Closing down send loop") @@ -1732,7 +1731,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt command.code if isinstance(command, GcodeCommand) else None, subcode=command.subcode if isinstance(command, GcodeCommand) else None, tags=command.tags) - except: + except Exception: self._logger.exception("Error while processing hook {name} for phase {phase} and command {command}:".format(**locals())) else: normalized = normalize_command_handler_result(command, hook_results, @@ -1794,7 +1793,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt for name, hook in self._atcommand_hooks[phase].items(): try: hook(self, phase, command.atcommand, command.parameters, tags=command.tags) - except: + except Exception: self._logger.exception("Error while processing hook {} for phase {} and command {}:".format(name, phase, command.atcommand)) # trigger built-in handler if available @@ -1802,7 +1801,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt if atcommand_handler in self._handlers_atcommand: try: getattr(self, atcommand_handler)(command) - except: + except Exception: self._logger.exception("Error in handler for phase {} and command {}".format(phase, command.atcommand)) ##~~ actual sending via serial @@ -1810,7 +1809,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt def _do_increment_and_send_with_checksum(self, line): """ Args: - line (str): the line to send + line (bytes): the line to send """ with self._line_mutex: line_number = self._current_linenumber @@ -1821,20 +1820,20 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt def _do_send_with_checksum(self, line, line_number): """ Args: - line (str): the line to send + line (bytes): the line to send line_number (int): the line number to send """ - command_to_send = b"N" + str(line_number) + b" " + line + command_to_send = b"N" + str(line_number).encode("ascii") + b" " + line checksum = 0 for c in bytearray(command_to_send): checksum ^= c - command_to_send = command_to_send + b"*" + str(checksum) + command_to_send = command_to_send + b"*" + str(checksum).encode("ascii") self._do_send_without_checksum(command_to_send) def _do_send_without_checksum(self, data): """ Args: - data (str): the data to send + data (bytes): the data to send """ self._transport.write(data + b"\n") @@ -1855,7 +1854,14 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt def _gcode_M0_queuing(self, command): self.pause_file_print() - return None, # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause. + + # TODO make configurable & active + #if self._block_M0_M1: + # if self.state in ProtocolState.PROCESSING_STATES: + # self._log("Not sending {} to printer since it's known to block communication, only pausing".format(command)) + # else: + # self._log("Not sending {} to printer since it's known to block communication".format(command)) + # return None, # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause. _gcode_M1_queuing = _gcode_M0_queuing def _gcode_M25_queuing(self, command): @@ -1876,7 +1882,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt self._internal_flags["temperature_autoreporting"] = self._internal_flags["firmware_capabilities"].get(CAPABILITY_AUTOREPORT_TEMP, False) \ and (interval > 0) - except: + except Exception: pass def _gcode_M27_sending(self, command): @@ -1885,7 +1891,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt self._internal_flags["sd_status_autoreporting"] = self._internal_flags["firmware_capabilities"].get(CAPABILITY_AUTOREPORT_SD_STATUS, False) \ and (interval > 0) - except: + except Exception: pass def _gcode_M104_sent(self, command, wait=False, support_r=False): @@ -1940,7 +1946,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt if command.n: try: new_line_number = int(command.n) - except: + except Exception: pass else: new_line_number = 0 @@ -1957,8 +1963,9 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt def _gcode_M112_queuing(self, command): # emergency stop, jump the queue with the M112 - self._do_send_without_checksum(str(self.flavor.command_emergency_stop())) - self._do_increment_and_send_with_checksum(str(self.flavor.command_emergency_stop())) + emergency_stop = self.flavor.command_emergency_stop().bytes + self._do_send_without_checksum(emergency_stop) + self._do_increment_and_send_with_checksum(emergency_stop) # No idea if the printer is still listening or if M112 won. Just in case # we'll now try to also manually make sure all heaters are shut off - better @@ -1969,12 +1976,12 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt shared_nozzle = self._printer_profile["extruder"]["sharedNozzle"] if extruder_count > 1 and not shared_nozzle: for tool in range(extruder_count): - self._do_increment_and_send_with_checksum(self.flavor.command_set_extruder_temp(0, tool=tool)) + self._do_increment_and_send_with_checksum(self.flavor.command_set_extruder_temp(0, tool=tool).bytes) else: - self._do_increment_and_send_with_checksum(self.flavor.command_set_extruder_temp(0)) + self._do_increment_and_send_with_checksum(self.flavor.command_set_extruder_temp(0).bytes) if self._printer_profile["heatedBed"]: - self._do_increment_and_send_with_checksum(str(self.flavor.command_set_bed_temp(0))) + self._do_increment_and_send_with_checksum(self.flavor.command_set_bed_temp(0).bytes) # close to reset host state # TODO needs error handling @@ -2045,7 +2052,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt if interval is None: try: interval = int(self.interval.get("temperature_autoreport", 2)) - except: + except Exception: interval = 2 self.send_commands(self.flavor.command_autoreport_temperature(interval=interval), tags={"trigger:set_autoreport_temperature_interval"}) @@ -2054,7 +2061,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt if interval is None: try: interval = int(self.interval.get("sd_status_autoreport", 1)) - except: + except Exception: interval = 1 self.send_commands(self.flavor.command_autoreport_sd_status(interval=interval), tags={"trigger:protocol.set_autoreport_sdstatus_interval"}) @@ -2065,7 +2072,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt if interval is None: try: interval = max(int(self.timeouts.get("communication_busy", 3)) - 1, 1) - except: + except Exception: interval = 2 self.send_commands(self.flavor.command_busy_protocol_interval(interval), tags={"trigger:protocol.set_busy_protocol_interval"}) @@ -2107,7 +2114,6 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt if __name__ == "__main__": from octoprint.comm.transport.serialtransport import VirtualSerialTransport from octoprint.comm.protocol.reprap.virtual import VirtualPrinter - from octoprint.comm.protocol.reprap.flavors import GenericFlavor from octoprint.comm.protocol import ProtocolListener, FileAwareProtocolListener from octoprint.comm.job import PrintjobListener @@ -2142,12 +2148,12 @@ if __name__ == "__main__": self._job.register_listener(self) self._protocol.process(self._job) - def on_protocol_state(self, protocol, old_state, new_state): + def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs): if protocol != self._protocol: return print("State changed from {} to {}".format(old_state, new_state)) - def on_protocol_temperature(self, protocol, temperatures): + def on_protocol_temperature(self, protocol, temperatures, *args, **kwargs): if protocol != self._protocol: return print("Temperature update: {!r}".format(temperatures)) @@ -2161,7 +2167,7 @@ if __name__ == "__main__": self.start_next_job() - def on_protocol_log(self, protocol, data): + def on_protocol_log(self, protocol, data, *args, **kwargs): if protocol != self._protocol: return print(data) @@ -2172,7 +2178,7 @@ if __name__ == "__main__": print("Job progress: {}% (Time: {} min)".format(int(job.progress * 100) if job.progress is not None else "0", "{}:{}".format(int(job.elapsed / 60), int(job.elapsed % 60)) if job.elapsed is not None else "?")) - def on_job_done(self, job): + def on_job_done(self, job, *args, **kwargs): self.start_next_job() transport = VirtualSerialTransport(virtual_serial_factory=virtual_serial_factory) diff --git a/src/octoprint/comm/protocol/reprap/commands/__init__.py b/src/octoprint/comm/protocol/reprap/commands/__init__.py index 5e97cbaf8..c954f787c 100644 --- a/src/octoprint/comm/protocol/reprap/commands/__init__.py +++ b/src/octoprint/comm/protocol/reprap/commands/__init__.py @@ -1,6 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals, print_function, \ - division +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -47,6 +46,7 @@ class Command(object): tags = set() self.line = line + self.bytes = line.encode("ascii", errors="replace") self.type = type self.tags = tags @@ -56,6 +56,9 @@ class Command(object): def __str__(self): return self.line + def __bytes__(self): + return self.bytes + def __key(self): return self.line, self.type diff --git a/src/octoprint/comm/protocol/reprap/commands/atcommand.py b/src/octoprint/comm/protocol/reprap/commands/atcommand.py index 478b0791b..62e9e79f7 100644 --- a/src/octoprint/comm/protocol/reprap/commands/atcommand.py +++ b/src/octoprint/comm/protocol/reprap/commands/atcommand.py @@ -1,6 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals, print_function, \ - division +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/src/octoprint/comm/protocol/reprap/commands/gcode.py b/src/octoprint/comm/protocol/reprap/commands/gcode.py index 2a99d7633..8e8355e4c 100644 --- a/src/octoprint/comm/protocol/reprap/commands/gcode.py +++ b/src/octoprint/comm/protocol/reprap/commands/gcode.py @@ -1,6 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals, print_function, \ - division +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -14,8 +13,8 @@ class GcodeCommand(Command): pattern = staticmethod(lambda x: GcodeCommand.command_regex.match(x)) - command_regex = re.compile("^\s*((?P[GM](?P\d+))(\\.(?P\d+))?|(?PT(?P\d+))|(?PF(?P\d+)))") - parameter_regex = re.compile("(?P[A-Z])((?P[-+]?[0-9]*\.?[0-9]+)(?!\d)|(\s|$))") + command_regex = re.compile(r"^\s*((?P[GM](?P\d+))(\\.(?P\d+))?|(?PT(?P\d+))|(?PF(?P\d+)))") + parameter_regex = re.compile(r"(?P[A-Z])((?P[-+]?[0-9]*\.?[0-9]+)(?!\d)|(\s|$))") possible_params = tuple(string.ascii_lowercase) + ("subcode", "param", "tool", "feedrate", "original") @@ -24,27 +23,27 @@ class GcodeCommand(Command): if isinstance(line, GcodeCommand): return line - tags = kwargs.get(b"tags") + tags = kwargs.get("tags") if tags is None: tags = set() - type = kwargs.get(b"type") + command_type = kwargs.get("type") line = line.strip() code = "" - args = dict(original=line, type=type, tags=tags) + args = dict(original=line, type=command_type, tags=tags) match = GcodeCommand.command_regex.match(line) if match is None: raise ValueError("{!r} is not a Gcode line".format(line)) - if match.group(b"GM"): - code = match.group(b"GM") + if match.group("GM"): + code = match.group("GM") - if match.group(b"subcode"): - args[b"subcode"] = int(match.group(b"subcode")) + if match.group("subcode"): + args["subcode"] = int(match.group("subcode")) if match.group(0) != line: rest = line[len(match.group(0)):] @@ -54,9 +53,9 @@ class GcodeCommand(Command): if not matched_param: break - key = matched_param.group(b"key").lower() - if matched_param.group(b"value"): - value = matched_param.group(b"value") + key = matched_param.group("key").lower() + if matched_param.group("value"): + value = matched_param.group("value") if "." in value: value = float(value) else: @@ -68,29 +67,29 @@ class GcodeCommand(Command): rest = rest.lstrip() if rest: - args[b"param"] = rest + args["param"] = rest - elif match.group(b"T"): + elif match.group("T"): code = "T" - args[b"tool"] = int(match.group(b"tool")) + args["tool"] = int(match.group("tool")) - elif match.group(b"F"): + elif match.group("F"): code = "F" - args[b"feedrate"] = int(match.group(b"feedrate")) + args["feedrate"] = int(match.group("feedrate")) return GcodeCommand(code, **args) def __init__(self, code, **kwargs): self.code = code - self.subcode = kwargs.pop(b"subcode", None) - self.tool = kwargs.pop(b"tool", None) - self.feedrate = kwargs.pop(b"feedrate", None) - self.param = kwargs.pop(b"param", None) - self.original = kwargs.pop(b"original", None) + self.subcode = kwargs.pop("subcode", None) + self.tool = kwargs.pop("tool", None) + self.feedrate = kwargs.pop("feedrate", None) + self.param = kwargs.pop("param", None) + self.original = kwargs.pop("original", None) - type = kwargs.pop(b"type", None) - tags = kwargs.pop(b"tags", None) + command_type = kwargs.pop("type", None) + tags = kwargs.pop("tags", None) self.args = kwargs @@ -99,7 +98,7 @@ class GcodeCommand(Command): else: line = self.original - super(GcodeCommand, self).__init__(line, type=type, tags=tags) + super(GcodeCommand, self).__init__(line, type=command_type, tags=tags) self._repr = self._to_repr() diff --git a/src/octoprint/comm/protocol/reprap/flavors/__init__.py b/src/octoprint/comm/protocol/reprap/flavors/__init__.py index b13028678..91c0ef8c9 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/__init__.py +++ b/src/octoprint/comm/protocol/reprap/flavors/__init__.py @@ -1,14 +1,14 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -from .generic import * -from .marlin import * -from .repetier import * -from .reprapfirmware import * -from .smoothieware import * +from .generic import * # noqa: F403 +from .marlin import * # noqa: F403 +from .repetier import * # noqa: F403 +from .reprapfirmware import * # noqa: F403 +from .smoothieware import * # noqa: F403 -from .anet import * -from .malyan import * +from .anet import * # noqa: F403 +from .malyan import * # noqa: F403 diff --git a/src/octoprint/comm/protocol/reprap/flavors/anet.py b/src/octoprint/comm/protocol/reprap/flavors/anet.py index 9503ea837..705908c0a 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/anet.py +++ b/src/octoprint/comm/protocol/reprap/flavors/anet.py @@ -1,4 +1,8 @@ -from __future__ import absolute_import, unicode_literals +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from .repetier import RepetierFlavor diff --git a/src/octoprint/comm/protocol/reprap/flavors/generic.py b/src/octoprint/comm/protocol/reprap/flavors/generic.py index 230f272ab..f51ff3d93 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/generic.py +++ b/src/octoprint/comm/protocol/reprap/flavors/generic.py @@ -1,9 +1,8 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals, print_function, \ - division +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' -__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" import re import logging @@ -18,7 +17,7 @@ _flavor_registry = dict() def _register_flavor(cls): - key = getattr(cls, b"key", None) + key = getattr(cls, "key", None) if key and not key in _flavor_registry: _flavor_registry[key] = cls @@ -63,10 +62,10 @@ class GenericFlavor(object): long_running_commands = ["G4", "G28", "G29", "G30", "G32", "M190", "M109", "M400", "M226"] asynchronous_commands = ["G0", "G1", "G2", "G3"] - regex_resend_linenumber = re.compile("(N|N:)?(?P%s)" % regex_int_pattern) + regex_resend_linenumber = re.compile(r"(N|N:)?(?P%s)" % regex_int_pattern) """Regex to use for request line numbers in resend requests""" - regex_temp = re.compile("(?PB|T(?P\d*)):\s*(?P%s)(\s*\/?\s*(?P%s))?" % ( + regex_temp = re.compile(r"(?PB|T(?P\d*)):\s*(?P%s)(\s*/?\s*(?P%s))?" % ( regex_positive_float_pattern, regex_positive_float_pattern)) """Regex matching temperature entries in line. @@ -78,7 +77,7 @@ class GenericFlavor(object): * ``target``: target temperature, if provided (float) """ - regex_position = re.compile("(?PX|Y|Z|E):(?P{float})\s*".format(float=regex_float_pattern)) + regex_position = re.compile(r"(?P[XYZE]):(?P{float})\s*".format(float=regex_float_pattern)) """Regex for matching position entries in line. Groups will be as follows: @@ -87,12 +86,12 @@ class GenericFlavor(object): * ``pos``: axis position (float) """ - regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):") + regex_firmware_splitter = re.compile(r"\s*([A-Z0-9_]+):") """Regex to use for splitting M115 responses.""" - regex_sd_file_opened = re.compile("file opened:\s*(?P.*?)(\s+size:\s*(?P[0-9]+)|$)") + regex_sd_file_opened = re.compile(r"file opened:\s*(?P.*?)(\s+size:\s*(?P[0-9]+)|$)") - regex_sd_printing_byte = re.compile("sd printing byte (?P[0-9]*)/(?P[0-9]*)") + regex_sd_printing_byte = re.compile(r"sd printing byte (?P[0-9]*)/(?P[0-9]*)") """Regex matching SD printing status reports. Groups will be as follows: @@ -262,7 +261,7 @@ class GenericFlavor(object): line_to_resend = None match = cls.regex_resend_linenumber.search(line) if match is not None: - line_to_resend = int(match.group(b"n")) + line_to_resend = int(match.group("n")) return dict(linenumber=line_to_resend) @classmethod @@ -309,7 +308,7 @@ class GenericFlavor(object): def parse_message_position(cls, line, lower_line, state, flags): position = dict(x=None, y=None, z=None, e=None) for match in re.finditer(cls.regex_position, line): - position[match.group(b"axis").lower()] = float(match.group(b"pos")) + position[match.group("axis").lower()] = float(match.group("pos")) return dict(position=position) @classmethod @@ -351,8 +350,8 @@ class GenericFlavor(object): if not match: return - name = match.group(b"name") - size = int(match.group(b"size")) + name = match.group("name") + size = int(match.group("size")) return dict(name=name, long_name=name, size=size) @classmethod @@ -388,7 +387,7 @@ class GenericFlavor(object): match = cls.regex_sd_printing_byte.match(lower_line) if not match: return None - return dict(current=int(match.group(b"current")), total=int(match.group(b"total"))) + return dict(current=int(match.group("current")), total=int(match.group("total"))) ##~~ Commands @@ -560,7 +559,7 @@ class GenericFlavor(object): dict: the canonicalized version of ``parsed`` """ - reported_extruders = filter(lambda x: x.startswith("T"), parsed.keys()) + reported_extruders = list(filter(lambda x: x.startswith("T"), parsed.keys())) if not "T" in reported_extruders: # Our reported_extruders are either empty or consist purely # of Tn keys, no need for any action diff --git a/src/octoprint/comm/protocol/reprap/flavors/malyan.py b/src/octoprint/comm/protocol/reprap/flavors/malyan.py index 1d4d451d3..ab13bfff9 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/malyan.py +++ b/src/octoprint/comm/protocol/reprap/flavors/malyan.py @@ -1,4 +1,8 @@ -from __future__ import absolute_import, unicode_literals +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor diff --git a/src/octoprint/comm/protocol/reprap/flavors/marlin.py b/src/octoprint/comm/protocol/reprap/flavors/marlin.py index ab9fe0735..0735d9331 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/marlin.py +++ b/src/octoprint/comm/protocol/reprap/flavors/marlin.py @@ -1,10 +1,8 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals, print_function, \ - division +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' -__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License" - +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor diff --git a/src/octoprint/comm/protocol/reprap/flavors/repetier.py b/src/octoprint/comm/protocol/reprap/flavors/repetier.py index c1b43d612..8204fde3b 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/repetier.py +++ b/src/octoprint/comm/protocol/reprap/flavors/repetier.py @@ -1,11 +1,8 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals, print_function, \ - division +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals -__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" - +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.protocol.reprap.flavors import GenericFlavor @@ -54,8 +51,8 @@ class RepetierFlavor(GenericFlavor): if "targetextr" in lower_line: match = cls.regex_tempextr.match(lower_line) if match is not None: - tool_num = int(match.group(b"toolnum")) - target = float(match.group(b"target")) + tool_num = int(match.group("toolnum")) + target = float(match.group("target")) tool = "T{}".format(tool_num) temperatures = dict() temperatures[tool] = (None, target) @@ -65,7 +62,7 @@ class RepetierFlavor(GenericFlavor): elif "targetbed" in lower_line: match = cls.regex_tempbed.match(lower_line) if match is not None: - target = float(match.group(b"target")) + target = float(match.group("target")) temperatures = dict(bed=(None, target)) return dict(max_tool_num=flags.get("current_tool", 0), temperatures=temperatures, diff --git a/src/octoprint/comm/protocol/reprap/flavors/reprapfirmware.py b/src/octoprint/comm/protocol/reprap/flavors/reprapfirmware.py index 8e566f0ff..b38442f4b 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/reprapfirmware.py +++ b/src/octoprint/comm/protocol/reprap/flavors/reprapfirmware.py @@ -1,4 +1,8 @@ -from __future__ import absolute_import, unicode_literals +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor diff --git a/src/octoprint/comm/protocol/reprap/flavors/smoothieware.py b/src/octoprint/comm/protocol/reprap/flavors/smoothieware.py index 82bf26b32..ac3d5a977 100644 --- a/src/octoprint/comm/protocol/reprap/flavors/smoothieware.py +++ b/src/octoprint/comm/protocol/reprap/flavors/smoothieware.py @@ -1,4 +1,8 @@ -from __future__ import absolute_import, unicode_literals +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor diff --git a/src/octoprint/comm/protocol/reprap/scripts.py b/src/octoprint/comm/protocol/reprap/scripts.py index f968ad0ad..c62833ba5 100644 --- a/src/octoprint/comm/protocol/reprap/scripts.py +++ b/src/octoprint/comm/protocol/reprap/scripts.py @@ -1,10 +1,9 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" - from octoprint.comm.scripts import Script, UnknownScript from octoprint.comm.protocol.reprap.util import process_gcode_line @@ -21,6 +20,6 @@ class GcodeScript(Script): def render(self, context=None): script = super(GcodeScript, self).render(context) - return filter(lambda x: x is not None and x.strip() != "", - map(lambda x: process_gcode_line(x), - script)) + return list(filter(lambda x: x is not None and x.strip() != "", + map(lambda x: process_gcode_line(x), + script))) diff --git a/src/octoprint/comm/protocol/reprap/util/__init__.py b/src/octoprint/comm/protocol/reprap/util/__init__.py index 540c7d469..cff0eff12 100644 --- a/src/octoprint/comm/protocol/reprap/util/__init__.py +++ b/src/octoprint/comm/protocol/reprap/util/__init__.py @@ -1,9 +1,8 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals, print_function, \ - division +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' -__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License" +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.protocol.reprap.commands import Command from octoprint.util import PrependableQueue, TypeAlreadyInQueue, CountedEvent @@ -19,7 +18,7 @@ import threading try: # noinspection PyCompatibility import queue -except: +except Exception: # noinspection PyCompatibility import Queue as queue @@ -296,7 +295,7 @@ class PositionRecord(object): try: int(attr[1:]) - except: + except Exception: return False return True diff --git a/src/octoprint/comm/protocol/reprap/util/queues.py b/src/octoprint/comm/protocol/reprap/util/queues.py index 5ff0b6199..995e2d435 100644 --- a/src/octoprint/comm/protocol/reprap/util/queues.py +++ b/src/octoprint/comm/protocol/reprap/util/queues.py @@ -1,11 +1,9 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals, print_function, \ - division +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" - from octoprint.util import PrependableQueue, TypedQueue, TypeAlreadyInQueue try: @@ -181,7 +179,7 @@ class QueueMarker(object): if callable(self.callback): try: self.callback() - except: + except Exception: logging.getLogger(__name__).exception("Error while running callback of QueueMarker") diff --git a/src/octoprint/comm/scripts/__init__.py b/src/octoprint/comm/scripts/__init__.py index 5f64ea5aa..957563ea2 100644 --- a/src/octoprint/comm/scripts/__init__.py +++ b/src/octoprint/comm/scripts/__init__.py @@ -1,10 +1,9 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" - class Script(object): def __init__(self, name, renderer, context=None): diff --git a/src/octoprint/comm/transport/__init__.py b/src/octoprint/comm/transport/__init__.py index 297fd2dfe..1721d3f0e 100644 --- a/src/octoprint/comm/transport/__init__.py +++ b/src/octoprint/comm/transport/__init__.py @@ -1,9 +1,8 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals -__author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' -__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License" +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.util.parameters import get_param_dict @@ -30,16 +29,16 @@ def register_transports(): register_transport(SerialOverTcpTransport) # more transports provided by plugins - hooks = plugin_manager().get_hooks(b"octoprint.comm.transport.register") + hooks = plugin_manager().get_hooks("octoprint.comm.transport.register") for name, hook in hooks.items(): try: transports = hook() for transport in transports: try: register_transport(transport) - except: + except Exception: logger.exception("Error while registering transport class {} for plugin {}".format(transport, name)) - except: + except Exception: logger.exception("Error executing octoprint.comm.transport.register hook for plugin {}".format(name)) @@ -273,7 +272,7 @@ class LineAwareTransportWrapper(SeparatorAwareTransportWrapper): class PushingTransportWrapper(TransportWrapper): - def __init__(self, transport, name="pushingTransportReceiveLoop", timeout=None): + def __init__(self, transport, name=b"PushingTransportWrapper.receiver_loop", timeout=None): super(PushingTransportWrapper, self).__init__(transport) self.name = name self.timeout = timeout @@ -309,7 +308,7 @@ class PushingTransportWrapper(TransportWrapper): self.notify_listeners("on_transport_data_pushed", self, data) except TimeoutTransportException as ex: self.notify_listeners("on_transport_data_exception", self, ex) - except: + except Exception: if self._receiver_active: raise diff --git a/src/octoprint/comm/transport/serialtransport.py b/src/octoprint/comm/transport/serialtransport.py index 1b5af66e0..85d77cf87 100644 --- a/src/octoprint/comm/transport/serialtransport.py +++ b/src/octoprint/comm/transport/serialtransport.py @@ -1,9 +1,8 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals -__author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' -__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License" +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.transport import Transport, LineAwareTransportWrapper, PushingTransportWrapper from octoprint.comm.util.parameters import TextType, IntegerType, SuggestionType, Value @@ -108,18 +107,18 @@ class SerialTransport(Transport): try: if callable(getattr(self._serial, "cancel_read", None)): self._serial.cancel_read() - except: + except Exception: self._logger.exception("Error while cancelling pending reads from the serial port") try: if callable(getattr(self._serial, "cancel_write", None)): self._serial.cancel_write() - except: + except Exception: self._logger.exception("Error while cancelling pending writes to the serial port") try: self._serial.close() - except: + except Exception: self._logger.exception("Error while closing the serial port") error = True @@ -153,13 +152,13 @@ class SerialTransport(Transport): try: # second try written += try_to_write(to_send) - except: + except Exception: if not self._closing: message = "Unexpected error while writing to serial port" self._logger.exception(message) self.disconnect(error=message) break - except: + except Exception: if not self._closing: message = "Unexpected error while writing to serial port" self._logger.exception(message) @@ -186,4 +185,4 @@ if __name__ == "__main__": # list ports ports = SerialTransport.get_available_serial_ports() for port in ports: - print(port.title + ": " + port.name) + print(port.title + ": " + port.value) diff --git a/src/octoprint/comm/transport/sockettransport.py b/src/octoprint/comm/transport/sockettransport.py index daccefcfa..ad8ca4c0e 100644 --- a/src/octoprint/comm/transport/sockettransport.py +++ b/src/octoprint/comm/transport/sockettransport.py @@ -1,9 +1,8 @@ -# coding=utf-8 -from __future__ import absolute_import, print_function, unicode_literals +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals -__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" +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" from octoprint.comm.transport import Transport, LineAwareTransportWrapper from octoprint.comm.util.parameters import TextType, IntegerType @@ -44,7 +43,7 @@ class TcpTransport(Transport): try: self._socket.close() return True - except: + except Exception: self._logger.exception("Error closing socket") return False diff --git a/src/octoprint/comm/util/parameters.py b/src/octoprint/comm/util/parameters.py index 0edac6420..0141b10a1 100644 --- a/src/octoprint/comm/util/parameters.py +++ b/src/octoprint/comm/util/parameters.py @@ -1,9 +1,10 @@ -# coding=utf-8 -from __future__ import absolute_import, unicode_literals +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' -__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License" +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" +from past.builtins import unicode def get_param_dict(data, options): options_by_name = dict((option.name, option) for option in options) @@ -82,7 +83,7 @@ class ChoiceType(ParamType): def as_dict(self): result = ParamType.as_dict(self) - result.update(dict(choices=map(lambda x: x.as_dict(), self.choices))) + result.update(dict(choices=list(map(lambda x: x.as_dict(), self.choices)))) return result class SuggestionType(ParamType): @@ -95,7 +96,7 @@ class SuggestionType(ParamType): def as_dict(self): result = ParamType.as_dict(self) - result.update(dict(suggestions=map(lambda x: x.as_dict(), self.suggestions))) + result.update(dict(suggestions=list(map(lambda x: x.as_dict(), self.suggestions)))) return result class ListType(ParamType): @@ -113,7 +114,7 @@ class ListType(ParamType): else: raise ValueError("value {!r} must be either a comma-separated string or a list".format(value)) - return map(self.factory, items) + return list(map(self.factory, items)) class Value(object): def __init__(self, value, title=None): diff --git a/src/octoprint/daemon.py b/src/octoprint/daemon.py index 6b42e1d88..dab6751bd 100644 --- a/src/octoprint/daemon.py +++ b/src/octoprint/daemon.py @@ -1,12 +1,13 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + """ Generic linux daemon base class Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35 """ -from __future__ import absolute_import, division, print_function -import sys, os, time, signal +import io, sys, os, time, signal class Daemon: """ @@ -60,9 +61,9 @@ class Daemon: # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() - si = open(os.devnull, 'r') - so = open(os.devnull, 'a+') - se = open(os.devnull, 'a+') + si = io.open(os.devnull, 'rt', encoding='utf-8') + so = io.open(os.devnull, 'at+', encoding='utf-8') + se = io.open(os.devnull, 'at+', encoding='utf-8') os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) @@ -133,7 +134,7 @@ class Daemon: except OSError: try: self.remove_pidfile() - except: + except Exception: self.error("Daemon found not running, but could not remove stale pidfile") return False else: @@ -142,7 +143,7 @@ class Daemon: def get_pid(self): """Get the pid from the pidfile.""" try: - with open(self.pidfile,'r') as pf: + with io.open(self.pidfile,'rt', encoding='utf-8') as pf: pid = int(pf.read().strip()) except (IOError, ValueError): pid = None @@ -150,7 +151,7 @@ class Daemon: def set_pid(self, pid): """Write the pid to the pidfile.""" - with open(self.pidfile,'w+') as f: + with io.open(self.pidfile,'wt+', encoding='utf-8') as f: f.write(str(pid) + '\n') def remove_pidfile(self): diff --git a/src/octoprint/environment.py b/src/octoprint/environment.py index 4d539297e..b46a7eb1a 100644 --- a/src/octoprint/environment.py +++ b/src/octoprint/environment.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -54,7 +54,7 @@ class EnvironmentDetector(object): self.notify_plugins() return environment - except: + except Exception: self._logger.exception("Unexpected error while detecting environment") with self._cache_lock: self._cache = dict() @@ -71,21 +71,21 @@ class EnvironmentDetector(object): # determine python version try: result["version"] = platform.python_version() - except: + except Exception: 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: + except Exception: 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: + except Exception: self._logger.exception("Error detecting pip version") return result @@ -105,7 +105,7 @@ class EnvironmentDetector(object): result["freq"] = cpu_freq.max if ram and hasattr(ram, "total"): result["ram"] = ram.total - except: + except Exception: self._logger.exception("Error while detecting hardware environment") return result @@ -118,7 +118,7 @@ class EnvironmentDetector(object): additional = implementation.get_additional_environment() if additional is not None and isinstance(additional, dict) and len(additional): result[implementation._identifier] = additional - except: + except Exception: self._logger.exception("Error while fetching additional " "environment data from plugin {}".format(implementation._identifier)) @@ -134,7 +134,7 @@ class EnvironmentDetector(object): try: _log(self._format()) - except: + except Exception: self._logger.exception("Error logging detected environment") def _format(self): @@ -145,10 +145,10 @@ class EnvironmentDetector(object): dumped_environment = yaml.safe_dump(environment, default_flow_style=False, - indent=" ", + indent=4, 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"], + return "Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"], environment["os"]["id"].title(), environment["os"]["platform"], environment_lines) @@ -162,6 +162,6 @@ class EnvironmentDetector(object): for implementation in self._environment_plugins: try: implementation.on_environment_detected(environment) - except: + except Exception: 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 5a638a128..cae1b493d 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge , Lars Norpchen" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -14,6 +14,7 @@ except ImportError: import Queue as queue import threading import collections +import re from octoprint.settings import settings import octoprint.plugin @@ -23,7 +24,7 @@ _instance = None def all_events(): - return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("__")] + return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("_") and not name in ("register_event",)] class Events(object): @@ -119,6 +120,23 @@ class Events(object): # Settings SETTINGS_UPDATED = "SettingsUpdated" + @classmethod + def register_event(cls, event, prefix=None): + name = cls._to_identifier(event) + if prefix: + event = prefix + event + name = cls._to_identifier(prefix) + name + setattr(cls, name, event) + return name, event + + # based on https://stackoverflow.com/a/1176023 + _first_cap_re = re.compile('(.)([A-Z][a-z]+)') + _all_cap_re = re.compile('([a-z0-9])([A-Z])') + + @classmethod + def _to_identifier(cls, name): + s1 = cls._first_cap_re.sub(r'\1_\2', name) + return cls._all_cap_re.sub(r'\1_\2', s1).upper() def eventManager(): global _instance @@ -135,6 +153,7 @@ class EventManager(object): def __init__(self): self._registeredListeners = collections.defaultdict(list) self._logger = logging.getLogger(__name__) + self._logger_fire = logging.getLogger("{}.fire".format(__name__)) self._startup_signaled = False self._shutdown_signaled = False @@ -156,21 +175,21 @@ class EventManager(object): self._shutdown_signaled = True eventListeners = self._registeredListeners[event] - self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload)) + self._logger_fire.debug("Firing event: {} (Payload: {!r})".format(event, payload)) for listener in eventListeners: - self._logger.debug("Sending action to %r" % listener) + self._logger.debug("Sending action to {!r}".format(listener)) try: listener(event, payload) - except: - self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener)) + except Exception: + self._logger.exception("Got an exception while sending event {} (Payload: {!r}) to {}".format(event, payload, listener)) octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin, "on_event", args=(event, payload), initialized=True) self._logger.info("Event loop shut down") - except: + except Exception: self._logger.exception("Ooops, the event bus worker loop crashed") def fire(self, event, payload=None): @@ -227,7 +246,7 @@ class EventManager(object): return self._registeredListeners[event].append(callback) - self._logger.debug("Subscribed listener %r for event %s" % (callback, event)) + self._logger.debug("Subscribed listener {!r} for event {}".format(callback, event)) def unsubscribe (self, event, callback): """ @@ -236,7 +255,6 @@ class EventManager(object): try: self._registeredListeners[event].remove(callback) - self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event)) except ValueError: # not registered pass @@ -282,7 +300,7 @@ class DebugEventListener(GenericEventListener): def __init__(self): GenericEventListener.__init__(self) - events = filter(lambda x: not x.startswith("__"), dir(Events)) + events = list(filter(lambda x: not x.startswith("__"), dir(Events))) self.subscribe(events) def eventCallback(self, event, payload): @@ -316,12 +334,12 @@ class CommandTrigger(GenericEventListener): self._logger.info("Invalid subscription definition, not a dictionary: {!r}".format(subscription)) continue - if not "event" in subscription.keys() or not "command" in subscription.keys() \ - or not "type" in subscription.keys() or not subscription["type"] in ["system", "gcode"]: + if not "event" in subscription or not "command" in subscription \ + or not "type" in subscription or not subscription["type"] in ["system", "gcode"]: self._logger.info("Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format(subscription)) continue - if "enabled" in subscription.keys() and not subscription["enabled"]: + if "enabled" in subscription and not subscription["enabled"]: self._logger.info("Disabled command trigger: {!r}".format(subscription)) continue @@ -330,11 +348,11 @@ class CommandTrigger(GenericEventListener): commandType = subscription["type"] debug = subscription["debug"] if "debug" in subscription else False - if not event in self._subscriptions.keys(): + if event not in self._subscriptions: self._subscriptions[event] = [] self._subscriptions[event].append((command, commandType, debug)) - if not event in eventsToSubscribe: + if event not in eventsToSubscribe: eventsToSubscribe.append(event) self.subscribe(eventsToSubscribe) @@ -359,8 +377,8 @@ class CommandTrigger(GenericEventListener): else: processedCommand = self._processCommand(command, payload) self.executeCommand(processedCommand, commandType, debug=debug) - except KeyError as e: - self._logger.warn("There was an error processing one or more placeholders in the following command: %s" % command) + except KeyError: + self._logger.warning("There was an error processing one or more placeholders in the following command: %s" % command) def executeCommand(self, command, commandType, debug=False): if commandType == "system": @@ -388,10 +406,10 @@ class CommandTrigger(GenericEventListener): commandExecutioner(command) except subprocess.CalledProcessError as e: if debug: - self._logger.warn("Command failed with return code {}: {}".format(e.returncode, str(e))) + self._logger.warning("Command failed with return code {}: {}".format(e.returncode, str(e))) else: - self._logger.warn("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode)) - except: + self._logger.warning("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode)) + except Exception: self._logger.exception("Command failed") t = threading.Thread(target=process) @@ -429,7 +447,8 @@ class CommandTrigger(GenericEventListener): import json try: json_string = json.dumps(payload) - except: + except Exception: + self._logger.exception("JSON: Cannot dump %r", payload) json_string = "" params = { diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 24f5ac1c0..8111b065b 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -1,11 +1,12 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __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" import logging +import io import os import octoprint.plugin @@ -30,10 +31,6 @@ extensions = dict( def full_extension_tree(): result = dict( - # extensions for 3d model files - model=dict( - stl=ContentTypeMapping(["stl"], "application/sla") - ), # extensions for printable machine code machinecode=dict( gcode=ContentTypeMapping(["gcode", "gco", "g"], "text/plain") @@ -74,6 +71,16 @@ def full_extension_tree(): else: return merged + slicer_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin) + for plugin in slicer_plugins: + try: + plugin_result = plugin.get_slicer_extension_tree() + if plugin_result is None or not isinstance(plugin_result, dict): + continue + result = octoprint.util.dict_merge(result, plugin_result, leaf_merger=leaf_merger) + except Exception: + logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from SlicerPlugin {name}".format(name=plugin.key)) + extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree") for name, hook in extension_tree_hooks.items(): try: @@ -81,13 +88,13 @@ def full_extension_tree(): if hook_result is None or not isinstance(hook_result, dict): continue result = octoprint.util.dict_merge(result, hook_result, leaf_merger=leaf_merger) - except: + except Exception: logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from hook {name}".format(name=name)) return result def get_extensions(type, subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() for key, value in subtree.items(): @@ -101,7 +108,7 @@ def get_extensions(type, subtree=None): return None def get_all_extensions(subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() result = [] @@ -120,7 +127,7 @@ def get_all_extensions(subtree=None): return result def get_path_for_extension(extension, subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() for key, value in subtree.items(): @@ -136,11 +143,11 @@ def get_path_for_extension(extension, subtree=None): return None def get_content_type_mapping_for_extension(extension, subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() for key, value in subtree.items(): - content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value. extensions + content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions list_extension_matches = isinstance(value, (list, tuple)) and extension in value if content_extension_matches or list_extension_matches: @@ -256,7 +263,7 @@ class FileManager(object): file_name = storage_manager.split_path(path) # we'll use the default printer profile for the backlog since we don't know better - queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default()) + queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default(), None) if self._analysis_queue.enqueue(queue_entry, high_priority=high_priority): counter += 1 @@ -337,8 +344,8 @@ class FileManager(object): links = [("model", dict(name=source_path))] _, stl_name = self.split_path(source_location, source_path) file_obj = StreamWrapper(os.path.basename(dest_path), - io.BytesIO(u";Generated from {stl_name} {hash}\n".format(**locals()).encode("ascii", "replace")), - io.FileIO(tmp_path, "rb")) + io.BytesIO(";Generated from {stl_name} {hash}\n".format(**locals()).encode("ascii", "replace")), + io.FileIO(tmp_path, 'rb')) printer_profile = self._printer_profile_manager.get(printer_profile_id) self.add_file(dest_location, dest_path, file_obj, @@ -415,15 +422,17 @@ class FileManager(object): if self._last_slicing_progress != progress_int: self._last_slicing_progress = progress_int for callback in self._slicing_progress_callbacks: - try: callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int) - except: self._logger.exception("Exception while pushing slicing progress") + try: + callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int) + except Exception: + self._logger.exception("Exception while pushing slicing progress") if progress_int: def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress): for plugin in self._progress_plugins: try: plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress) - except: + except Exception: self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier) import threading @@ -446,8 +455,8 @@ class FileManager(object): def list_files(self, destinations=None, path=None, filter=None, recursive=None): if not destinations: - destinations = self._storage_managers.keys() - if isinstance(destinations, (str, unicode, basestring)): + destinations = list(self._storage_managers.keys()) + if isinstance(destinations, basestring): destinations = [destinations] result = dict() @@ -462,7 +471,7 @@ class FileManager(object): for hook in self._preprocessor_hooks.values(): try: hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite) - except: + except Exception: self._logger.exception("Error when calling preprocessor hook {}, ignoring".format(hook)) continue @@ -476,12 +485,9 @@ class FileManager(object): 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) - if queue_entry: - self._analysis_queue.enqueue(queue_entry, high_priority=True) - else: - self._add_analysis_result(destination, path, analysis) + queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile, analysis=analysis) + if queue_entry: + self._analysis_queue.enqueue(queue_entry, high_priority=True) _, name = self._storage(destination).split_path(path_in_storage) eventManager().fire(Events.FILE_ADDED, dict(storage=destination, @@ -631,9 +637,9 @@ class FileManager(object): pos=pos, date=time.time()) try: - with atomic_write(self._recovery_file, max_permissions=0o666) as f: - yaml.safe_dump(data, stream=f, default_flow_style=False, indent=" ", allow_unicode=True) - except: + with atomic_write(self._recovery_file, mode='wt', max_permissions=0o666) as f: + yaml.safe_dump(data, stream=f, default_flow_style=False, indent=2, allow_unicode=True) + except Exception: self._logger.exception("Could not write recovery data to file {}".format(self._recovery_file)) def delete_recovery_data(self): @@ -642,7 +648,7 @@ class FileManager(object): try: os.remove(self._recovery_file) - except: + except Exception: self._logger.exception("Error deleting recovery data file {}".format(self._recovery_file)) def get_recovery_data(self): @@ -651,10 +657,10 @@ class FileManager(object): import yaml try: - with open(self._recovery_file) as f: + with io.open(self._recovery_file, 'rt', encoding='utf-8') as f: data = yaml.safe_load(f) return data - except: + except Exception: self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file)) self.delete_recovery_data() @@ -706,7 +712,7 @@ class FileManager(object): def _on_analysis_finished(self, entry, result): self._add_analysis_result(entry.location, entry.path, result) - def _analysis_queue_entry(self, destination, path, printer_profile=None): + def _analysis_queue_entry(self, destination, path, printer_profile=None, analysis=None): if printer_profile is None: printer_profile = self._printer_profile_manager.get_current_or_default() @@ -715,6 +721,6 @@ class FileManager(object): file_type = get_file_type(absolute_path) if file_type: - return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile) + return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile, analysis) else: return None diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index ad24a3e4f..9aafaca9a 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -20,7 +20,7 @@ from octoprint.events import Events, eventManager from octoprint.settings import settings -class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")): +class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")): """ A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary for processing. @@ -33,6 +33,7 @@ class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, locatio location (str): Location the file is located on. absolute_path (str): Absolute path on disk through which to access the file. printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis. + analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none. """ def __str__(self): @@ -94,16 +95,16 @@ class AnalysisQueue(object): self._queues[entry.type].dequeue(entry.location, entry.path) def dequeue_folder(self, destination, path): - for queue in self._queues.values(): - queue.dequeue_folder(destination, path) + for q in self._queues.values(): + q.dequeue_folder(destination, path) def pause(self): - for queue in self._queues.values(): - queue.pause() + for q in self._queues.values(): + q.pause() def resume(self): - for queue in self._queues.values(): - queue.resume() + for q in self._queues.values(): + q.resume() def _analysis_finished(self, entry, result): for callback in self._callbacks: @@ -298,7 +299,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): - * **Key** * **Description** - * ``estimatedPrintTime`` - * Estimated time the file take to print, in minutes + * Estimated time the file take to print, in seconds - * ``filament`` * Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for the second and so on. For each tool extruded length and volume (based on diameter) are provided. @@ -341,6 +342,8 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): import sys import yaml + if self._current.analysis: + return self._current.analysis try: throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \ else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"]) @@ -364,7 +367,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): self._logger.info("Invoking analysis command: {}".format(" ".join(command))) self._aborted = False - p = sarge.run(command, async=True, stdout=sarge.Capture()) + p = sarge.run(command, async_=True, stdout=sarge.Capture()) while len(p.commands) == 0: # somewhat ugly... we can't use wait_events because @@ -379,7 +382,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): 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))) + raise RuntimeError("Error while trying to run command {}".format(" ".join(command))) try: # let's wait for stuff to finish diff --git a/src/octoprint/filemanager/destinations.py b/src/octoprint/filemanager/destinations.py index 11a971884..1659a01eb 100644 --- a/src/octoprint/filemanager/destinations.py +++ b/src/octoprint/filemanager/destinations.py @@ -1,5 +1,6 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' class FileDestinations(object): diff --git a/src/octoprint/filemanager/storage/local.py b/src/octoprint/filemanager/storage/local.py index ad3a79c48..7ba16df2e 100644 --- a/src/octoprint/filemanager/storage/local.py +++ b/src/octoprint/filemanager/storage/local.py @@ -1,9 +1,10 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" +import io import logging import os import pylru @@ -27,7 +28,7 @@ from slugify import Slugify import octoprint.filemanager -from octoprint.util import is_hidden_path, to_unicode +from octoprint.util import is_hidden_path, to_unicode, to_bytes from . import Storage, StorageError @@ -42,11 +43,11 @@ class LocalFileStorage(Storage): This storage type implements :func:`path_on_disk`. """ - _UNICODE_VARIATIONS = re.compile(u"[\uFE00-\uFE0F]") + _UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U) @classmethod def _no_unicode_variations(cls, text): - return cls._UNICODE_VARIATIONS.sub(u"", text) + return cls._UNICODE_VARIATIONS.sub("", text) _SLUGIFY = Slugify() _SLUGIFY.safe_chars = "-_.()[] " @@ -55,7 +56,7 @@ class LocalFileStorage(Storage): def _slugify(cls, text): text = to_unicode(text) text = cls._no_unicode_variations(text) - text = demojize(text, delimiters=(u"", u"")) + text = demojize(text, delimiters=("", "")) return cls._SLUGIFY(text) def __init__(self, basefolder, create=False, key="local"): @@ -92,10 +93,10 @@ class LocalFileStorage(Storage): if os.path.exists(old_metadata_path): # load the old metadata file try: - with open(old_metadata_path) as f: + with io.open(old_metadata_path, 'rt', encoding='utf-8') as f: import yaml self._old_metadata = yaml.safe_load(f) - except: + except Exception: self._logger.exception("Error while loading old metadata file") # make sure the metadata is initialized as far as possible @@ -106,7 +107,7 @@ class LocalFileStorage(Storage): try: import shutil shutil.move(old_metadata_path, backup_path) - except: + except Exception: self._logger.exception("Could not rename old metadata.yaml file") else: @@ -189,10 +190,10 @@ class LocalFileStorage(Storage): path = self.sanitize_path(to_unicode(path)) base = self.path_in_storage(path) if base: - base += u"/" + base += "/" else: path = self.basefolder - base = u"" + base = "" return self._list_folder(path, base=base, entry_filter=filter, recursive=recursive) def add_folder(self, path, ignore_existing=True, display=None): @@ -515,14 +516,14 @@ class LocalFileStorage(Storage): def split_path(self, path): path = to_unicode(path) - split = path.split(u"/") + split = path.split("/") if len(split) == 1: - return u"", split[0] + return "", split[0] else: return self.join_path(*split[:-1]), split[-1] def join_path(self, *path): - return u"/".join(map(to_unicode, path)) + return "/".join(map(to_unicode, path)) def sanitize(self, path): """ @@ -551,23 +552,23 @@ class LocalFileStorage(Storage): 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"/") + path = path.replace(os.path.sep, "/") + path = path.split("/") if isinstance(path, (list, tuple)): if len(path) == 1: name = to_unicode(path[0]) - path = u"" + path = "" else: name = to_unicode(path[-1]) path = self.join_path(*map(to_unicode, path[:-1])) if not path: - path = u"" + path = "" return path, name def sanitize_name(self, name): """ - Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise + Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``, ``(``, and ``)`` as is. """ @@ -576,11 +577,11 @@ class LocalFileStorage(Storage): if name is None: return None - if u"/" in name or u"\\" in name: + if "/" in name or "\\" in name: raise ValueError("name must not contain / or \\") - result = self._slugify(name).replace(u" ", u"_") - if result and result != u"." and result != u".." and result[0] == u".": + result = self._slugify(name).replace(" ", "_") + if result and result != "." and result != ".." and result[0] == ".": # hidden files under *nix result = result[1:] return result @@ -594,12 +595,12 @@ class LocalFileStorage(Storage): path = to_unicode(path) if len(path): - if path[0] == u"/": + if path[0] == "/": path = path[1:] - elif path[0] == u"." and path[1] == u"/": + elif path[0] == "." and path[1] == "/": path = path[2:] - path_elements = path.split(u"/") + path_elements = path.split("/") joined_path = self.basefolder for path_element in path_elements: joined_path = os.path.join(joined_path, self.sanitize_name(path_element)) @@ -619,16 +620,16 @@ class LocalFileStorage(Storage): counter = 1 while os.path.exists(sanitized_path): counter += 1 - sanitized = self.sanitize_name(u"{}_({}){}".format(sanitized_name, counter, sanitized_ext)) + sanitized = self.sanitize_name("{}_({}){}".format(sanitized_name, counter, sanitized_ext)) sanitized_path = os.path.join(path, sanitized) try: shutil.move(entry_path, sanitized_path) - self._logger.info(u"Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path)) + self._logger.info("Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path)) return sanitized, sanitized_path - except: - self._logger.exception(u"Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path)) + except Exception: + self._logger.exception("Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path)) raise return entry, entry_path @@ -636,12 +637,12 @@ class LocalFileStorage(Storage): def path_in_storage(self, path): if isinstance(path, (tuple, list)): path = self.join_path(*path) - if isinstance(path, (str, unicode, basestring)): + 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"/") - if path.startswith(u"/"): + path = path.replace(os.path.sep, "/") + if path.startswith("/"): path = path[1:] return path @@ -717,8 +718,8 @@ class LocalFileStorage(Storage): print_time = history_entry["printTime"] try: print_time = float(print_time) - except: - self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time)) + except Exception: + self._logger.warning("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: @@ -902,7 +903,7 @@ class LocalFileStorage(Storage): entry_is_file = entry.is_file() entry_is_dir = entry.is_dir() entry_stat = entry.stat() - except: + except Exception: # error while trying to fetch file metadata, that might be thanks to file already having # been moved or deleted - ignore it and continue continue @@ -914,7 +915,7 @@ class LocalFileStorage(Storage): entry_name = new_entry_name entry_path = new_entry_path entry_stat = os.stat(entry_path) - except: + except Exception: # error while trying to rename the file, we'll continue here and ignore it continue @@ -1011,7 +1012,7 @@ class LocalFileStorage(Storage): extended_entry_data["size"] = get_size() result[entry_name] = extended_entry_data - except: + except Exception: # 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 @@ -1065,7 +1066,7 @@ class LocalFileStorage(Storage): blocksize = 65536 hash = hashlib.sha1() - with open(path, "rb") as f: + with io.open(path, 'rb') as f: buffer = f.read(blocksize) while len(buffer) > 0: hash.update(buffer) @@ -1125,11 +1126,11 @@ class LocalFileStorage(Storage): metadata_path = os.path.join(path, ".metadata.json") if os.path.exists(metadata_path): - with open(metadata_path) as f: + with io.open(metadata_path, 'rt', encoding='utf-8') as f: try: import json metadata = json.load(f) - except: + except Exception: self._logger.exception("Error while reading .metadata.json from {path}".format(**locals())) else: if isinstance(metadata, dict): @@ -1142,9 +1143,9 @@ class LocalFileStorage(Storage): metadata_path = os.path.join(path, ".metadata.json") try: import json - with atomic_write(metadata_path) as f: - json.dump(metadata, f, indent=4, separators=(",", ": ")) - except: + with atomic_write(metadata_path, mode='wb') as f: + f.write(to_bytes(json.dumps(metadata, indent=4, separators=(",", ": ")))) + except Exception: self._logger.exception("Error while writing .metadata.json to {path}".format(**locals())) else: self._metadata_cache[path] = deepcopy(metadata) @@ -1157,7 +1158,7 @@ class LocalFileStorage(Storage): if os.path.exists(metadata_path): try: os.remove(metadata_path) - except: + except Exception: self._logger.exception("Error while deleting {metadata_file} from {path}".format(**locals())) if path in self._metadata_cache: del self._metadata_cache[path] @@ -1180,10 +1181,10 @@ class LocalFileStorage(Storage): # TODO 1.3.10 Remove ".metadata.yaml" files return - with open(metadata_path_yaml) as f: + with io.open(metadata_path_yaml, 'rt', encoding='utf-8') as f: try: metadata = yaml.safe_load(f) - except: + except Exception: self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals())) return @@ -1191,8 +1192,8 @@ class LocalFileStorage(Storage): # looks invalid, ignore it return - with atomic_write(metadata_path_json) as f: - json.dump(metadata, f, indent=4, separators=(",", ": ")) + with atomic_write(metadata_path_json, mode='wb') as f: + f.write(to_bytes(json.dumps(metadata, indent=4, separators=(",", ": ")))) # TODO 1.3.10 Remove ".metadata.yaml" files diff --git a/src/octoprint/filemanager/util.py b/src/octoprint/filemanager/util.py index d8bd9561f..4a247e62b 100644 --- a/src/octoprint/filemanager/util.py +++ b/src/octoprint/filemanager/util.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -64,7 +64,7 @@ class DiskFileWrapper(AbstractFileWrapper): shutil.copy2(self.path, path) def stream(self): - return io.open(self.path, "rb") + return io.open(self.path, 'rb') class StreamWrapper(AbstractFileWrapper): """ @@ -87,7 +87,7 @@ class StreamWrapper(AbstractFileWrapper): """ import shutil - with atomic_write(path, "wb") as dest: + with atomic_write(path, mode='wb') as dest: with self.stream() as source: shutil.copyfileobj(source, dest) @@ -142,7 +142,7 @@ class MultiStream(io.RawIOBase): for stream in self.streams: try: stream.close() - except: + except Exception: pass def readable(self, *args, **kwargs): diff --git a/src/octoprint/logging/__init__.py b/src/octoprint/logging/__init__.py index 1021b169a..6a0043ba5 100644 --- a/src/octoprint/logging/__init__.py +++ b/src/octoprint/logging/__init__.py @@ -1,5 +1,7 @@ -# coding=utf-8 -from __future__ import absolute_import +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +from past.builtins import basestring from octoprint.logging import handlers @@ -77,17 +79,18 @@ def get_divider_line(c, message=None, length=78, indent=3): Examples: - >>> get_divider_line("-") + >>> from octoprint.util import to_native_str + >>> to_native_str(get_divider_line("-")) '------------------------------------------------------------------------------' - >>> get_divider_line("=", length=10) + >>> to_native_str(get_divider_line("=", length=10)) '==========' - >>> get_divider_line("-", message="Hi", length=10) + >>> to_native_str(get_divider_line("-", message="Hi", length=10)) '--- Hi ---' - >>> get_divider_line("-", message="A slightly longer text") + >>> to_native_str(get_divider_line("-", message="A slightly longer text")) '--- A slightly longer text ---------------------------------------------------' - >>> get_divider_line("-", message="A slightly longer text", indent=5) + >>> to_native_str(get_divider_line("-", message="A slightly longer text", indent=5)) '----- A slightly longer text -------------------------------------------------' - >>> get_divider_line("-", message="Hello World!", length=10) + >>> to_native_str(get_divider_line("-", message="Hello World!", length=10)) '--- Hello World!' >>> get_divider_line(None) Traceback (most recent call last): @@ -120,7 +123,7 @@ def get_divider_line(c, message=None, length=78, indent=3): formatted divider line """ - assert isinstance(c, (str, unicode, bytes)), "c is not text" + assert isinstance(c, basestring), "c is not text" assert len(c) == 1, "c is not a single character" assert isinstance(length, int), "length is not an int" assert isinstance(indent, int), "indent is not an int" @@ -128,7 +131,7 @@ def get_divider_line(c, message=None, length=78, indent=3): if message is None: return c * length - assert isinstance(message, (str, unicode, bytes)), "message is not text" + assert isinstance(message, basestring), "message is not text" space = length - 2 * (indent + 1) if space >= len(message): @@ -147,4 +150,3 @@ def prefix_multilines(text, prefix=": "): 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 52a8bff46..633f53118 100644 --- a/src/octoprint/logging/handlers.py +++ b/src/octoprint/logging/handlers.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals import logging.handlers import os @@ -18,7 +18,7 @@ class AsyncLogHandlerMixin(logging.Handler): def emit(self, record): try: self._executor.submit(self._emit, record) - except: + except Exception: self.handleError(record) def _emit(self, record): @@ -29,6 +29,8 @@ class AsyncLogHandlerMixin(logging.Handler): class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler): def __init__(self, *args, **kwargs): + kwargs["encoding"] = kwargs.get("encoding", "utf-8") + super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs) # clean up old files on handler start @@ -40,6 +42,10 @@ class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler): rollover_callbacks = [] + def __init__(self, *args, **kwargs): + kwargs["encoding"] = kwargs.get("encoding", "utf-8") + super(OctoPrintLogHandler, self).__init__(*args, **kwargs) + @classmethod def registerRolloverCallback(cls, callback, *args, **kwargs): cls.rollover_callbacks.append((callback, args, kwargs)) @@ -67,6 +73,7 @@ class CommunicationLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFil cls.do_rollover[logger] = True def __init__(self, *args, **kwargs): + kwargs["encoding"] = kwargs.get("encoding", "utf-8") super(CommunicationLogHandler, self).__init__(*args, **kwargs) self.cleanupFiles() diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index b0a9fa54f..06d29ee89 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -1,4 +1,6 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + """ This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the registered plugin types. @@ -13,35 +15,25 @@ registered plugin types. :members: """ -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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import os import logging +import threading from octoprint.settings import settings as s, SubSettings from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin) -from octoprint.plugin.types import * +from octoprint.plugin.types import OctoPrintPlugin, SettingsPlugin +from octoprint.plugin.types import * # noqa: F403 ## used by multiple other modules -from octoprint.util import deprecated +from octoprint.util import deprecated, to_native_str # singleton _instance = None def _validate_plugin(phase, plugin_info): - if phase == "after_load": - if plugin_info.implementation is not None and isinstance(plugin_info.implementation, AppPlugin): - # transform app plugin into hook - import warnings - warnings.warn("{name} uses deprecated plugin mixin AppPlugin, use octoprint.accesscontrol.appkey hook instead".format(name=plugin_info.key), DeprecationWarning) - - hooks = plugin_info.hooks - if not "octoprint.accesscontrol.appkey" in hooks: - hooks["octoprint.accesscontrol.appkey"] = plugin_info.implementation.get_additional_apps - setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks) return True def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None, @@ -95,7 +87,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en if plugin_restart_needing_hooks is None: plugin_restart_needing_hooks = ["octoprint.server.http.*", "octoprint.printer.factory", - "octoprint.access.permissions"] + "octoprint.access.permissions", + "octoprint.timelapse.extensions"] if plugin_obsolete_hooks is None: plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"] @@ -161,14 +154,15 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None): try: get_preprocessors, set_preprocessors = instance.get_settings_preprocessors() - except: + except Exception: logging.getLogger(__name__).exception("Error while retrieving preprocessors for plugin {}".format(plugin_key)) return 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, initialized=True): +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 @@ -206,7 +200,6 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call 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. - """ if not isinstance(types, (list, tuple)): @@ -216,18 +209,21 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call if kwargs is None: kwargs = dict() + logger = logging.getLogger(__name__) + 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): + logger.debug("Calling {} on {}".format(method, plugin._identifier)) try: result = getattr(plugin, method)(*args, **kwargs) if callback: callback(plugin._identifier, plugin, result) except Exception as exc: - logging.getLogger(__name__).exception("Error while calling plugin %s" % plugin._identifier) + logger.exception("Error while calling plugin %s" % plugin._identifier) if error_callback: error_callback(plugin._identifier, plugin, exc) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 8987a8228..4456f0f9b 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -1,4 +1,6 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + """ In this module resides the core data structures and logic of the plugin system. It is implemented in an OctoPrint-agnostic way and could be extracted into a separate Python module in the future. @@ -20,14 +22,13 @@ way and could be extracted into a separate Python module in the future. """ -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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import os +import io import imp from collections import defaultdict, namedtuple, OrderedDict import logging @@ -37,7 +38,9 @@ import inspect import pkg_resources import pkginfo -from past.builtins import basestring +from past.builtins import unicode + +from octoprint.util import to_unicode try: from os import scandir @@ -209,7 +212,7 @@ class PluginInfo(object): if self.version: return "{name} ({version})".format(name=self.name, version=self.version) else: - return self.name + return to_unicode(self.name) def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""), show_location=False, location_str=" - {location}", @@ -242,17 +245,19 @@ class PluginInfo(object): str: The long string representation of the plugin as described above """ if show_enabled: - ret = enabled_strs[2] if self.blacklisted else (enabled_strs[0] if self.enabled else enabled_strs[1]) + ret = to_unicode(enabled_strs[2]) if self.blacklisted \ + else (to_unicode(enabled_strs[0]) if self.enabled + else to_unicode(enabled_strs[1])) else: ret = "" - ret += str(self) + ret += unicode(self) if show_bundled: - ret += bundled_strs[0] if self.bundled else bundled_strs[1] + ret += to_unicode(bundled_strs[0]) if self.bundled else to_unicode(bundled_strs[1]) if show_location and self.location: - ret += location_str.format(location=self.location) + ret += to_unicode(location_str).format(location=self.location) return ret @@ -512,15 +517,15 @@ class PluginInfo(object): try: import ast - with open(path, "rb") as f: + with io.open(path, 'rb') as f: root = ast.parse(f.read()) - assignments = filter(lambda x: isinstance(x, ast.Assign) and x.targets, - root.body) + assignments = list(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)) + return list(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): @@ -536,7 +541,8 @@ class PluginInfo(object): result[key] = a.value.args[0].s break - except: + except Exception: + # TODO: really ignore all errors? pass return result @@ -628,7 +634,7 @@ class PluginManager(object): @property def plugin_hooks(self): - return {key: map(lambda v: (v[1], v[2]), value) for key, value in self._plugin_hooks.items()} + return {key: list(map(lambda v: (v[1], v[2]), value)) for key, value in self._plugin_hooks.items()} def find_plugins(self, existing=None, ignore_uninstalled=True, incl_all_found=False): added, found = self._find_plugins(existing=existing, ignore_uninstalled=ignore_uninstalled) @@ -651,7 +657,7 @@ class PluginManager(object): ignored_uninstalled=ignore_uninstalled) result_added.update(added) result_found += found - except: + except Exception: self.logger.exception("Error fetching plugins from folders") if self.plugin_entry_points: @@ -662,7 +668,7 @@ class PluginManager(object): ignore_uninstalled=ignore_uninstalled) result_added.update(added) result_found += found - except: + except Exception: self.logger.exception("Error fetching plugins from entry points") return result_added, result_found @@ -682,7 +688,7 @@ class PluginManager(object): 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)) + self.logger.warning("Plugin folder {folder} could not be found, skipping it".format(folder=folder)) continue for entry in scandir(folder): @@ -720,9 +726,9 @@ class PluginManager(object): plugin.managable = not flagged_readonly and not actual_readonly plugin.enabled = False added[key] = plugin - except: + except Exception: self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder)) - except: + except Exception: self.logger.exception("Error processing folder {}".format(folder)) return added, found @@ -752,7 +758,7 @@ class PluginManager(object): for entry in gen: try: yield entry - except: + except Exception: 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?") @@ -772,7 +778,7 @@ class PluginManager(object): package_name = entry_point.dist.project_name try: entry_point_metadata = EntryPointMetadata(entry_point) - except: + except Exception: self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name)) else: kwargs.update(dict( @@ -802,7 +808,7 @@ class PluginManager(object): plugin.location)) added[key] = plugin - except: + except Exception: self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group)) return added, found @@ -817,7 +823,7 @@ class PluginManager(object): module = imp.find_module(module_name) else: return None - except: + except Exception: self.logger.warn("Could not locate plugin {key}".format(key=key)) return None @@ -831,7 +837,7 @@ class PluginManager(object): 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)) + self.logger.warning("Plugin {} is blacklisted.".format(plugin)) plugin.blacklisted = True if not plugin.validate("before_import", additional_validators=self.plugin_validators): @@ -839,12 +845,15 @@ class PluginManager(object): # ... then create and return the real one return self._import_plugin(key, *module, - name=name, version=version, summary=summary, author=author, url=url, + module_name=module_name, 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): + def _import_plugin(self, key, f, filename, description, module_name=None, 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) + if module_name: + instance = imp.load_module(module_name, f, filename, description) + else: + instance = imp.load_module(key, f, filename, description) plugin = PluginInfo(key, filename, instance, name=name, version=version, @@ -854,14 +863,14 @@ class PluginManager(object): license=license, parsed_metadata=parsed_metadata) plugin.bundled = bundled - except: + except Exception: self.logger.exception("Error loading plugin {key}".format(key=key)) return None if plugin.check(): return plugin else: - self.logger.warn("Plugin \"{plugin}\" did not pass check".format(plugin=str(plugin))) + self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin))) return None def _is_plugin_disabled(self, key): @@ -892,7 +901,7 @@ class PluginManager(object): incl_all_found=True) # let's clean everything we DIDN'T find first - removed = [key for key in self.enabled_plugins.keys() + self.disabled_plugins.keys() if key not in found] + removed = [key for key in list(self.enabled_plugins.keys()) + list(self.disabled_plugins.keys()) if key not in found] for key in removed: try: del self.enabled_plugins[key] @@ -925,7 +934,7 @@ class PluginManager(object): try: if plugin.loaded and not plugin.forced_disabled: if plugin.blacklisted: - self.logger.warn("Plugin {} is blacklisted. Not enabling it.".format(plugin)) + self.logger.warning("Plugin {} is blacklisted. Not enabling it.".format(plugin)) continue self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup) except PluginNeedsRestart: @@ -967,7 +976,7 @@ class PluginManager(object): def load_plugin(self, name, plugin=None, startup=False, initialize_implementation=True): if not name in self.plugins: - self.logger.warn("Trying to load an unknown plugin {name}".format(**locals())) + self.logger.warning("Trying to load an unknown plugin {name}".format(**locals())) return if plugin is None: @@ -985,12 +994,12 @@ class PluginManager(object): self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals())) except PluginLifecycleException as e: raise e - except: + except Exception: self.logger.exception("There was an error loading plugin %s" % name) def unload_plugin(self, name): if not name in self.plugins: - self.logger.warn("Trying to unload unknown plugin {name}".format(**locals())) + self.logger.warning("Trying to unload unknown plugin {name}".format(**locals())) return plugin = self.plugins[name] @@ -1013,7 +1022,7 @@ class PluginManager(object): self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals())) except PluginLifecycleException as e: raise e - except: + except Exception: self.logger.exception("There was an error unloading plugin {name}".format(**locals())) # make sure the plugin is NOT in the list of enabled plugins but in the list of disabled plugins @@ -1024,7 +1033,7 @@ class PluginManager(object): def enable_plugin(self, name, plugin=None, initialize_implementation=True, startup=False): if not name in self.disabled_plugins: - self.logger.warn("Tried to enable plugin {name}, however it is not disabled".format(**locals())) + self.logger.warning("Tried to enable plugin {name}, however it is not disabled".format(**locals())) return if plugin is None: @@ -1044,7 +1053,7 @@ class PluginManager(object): self._activate_plugin(name, plugin) except PluginLifecycleException as e: raise e - except: + except Exception: self.logger.exception("There was an error while enabling plugin {name}".format(**locals())) return False else: @@ -1066,7 +1075,7 @@ class PluginManager(object): def disable_plugin(self, name, plugin=None): if not name in self.enabled_plugins: - self.logger.warn("Tried to disable plugin {name}, however it is not enabled".format(**locals())) + self.logger.warning("Tried to disable plugin {name}, however it is not enabled".format(**locals())) return if plugin is None: @@ -1080,7 +1089,7 @@ class PluginManager(object): self._deactivate_plugin(name, plugin) except PluginLifecycleException as e: raise e - except: + except Exception: self.logger.exception("There was an error while disabling plugin {name}".format(**locals())) return False else: @@ -1105,7 +1114,7 @@ class PluginManager(object): try: callback, order = self._get_callback_and_order(definition) except ValueError as e: - self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) + self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) continue self._plugin_hooks[hook].append((order, name, callback)) @@ -1124,7 +1133,7 @@ class PluginManager(object): try: callback, order = self._get_callback_and_order(definition) except ValueError as e: - self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) + self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) continue try: @@ -1183,7 +1192,7 @@ class PluginManager(object): if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): hooks = hooks[0] - hooks = filter(lambda hook: hook is not None, hooks) + hooks = list(filter(lambda hook: hook is not None, hooks)) if not hooks: return False if not plugin or not plugin.hooks: @@ -1217,7 +1226,7 @@ class PluginManager(object): if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): hooks = hooks[0] - hooks = filter(lambda hook: hook is not None, hooks) + hooks = list(filter(lambda hook: hook is not None, hooks)) if not hooks: return False if not hook: @@ -1255,7 +1264,7 @@ class PluginManager(object): if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)): mixins = mixins[0] - mixins = filter(lambda mixin: mixin is not None, mixins) + mixins = list(filter(lambda mixin: mixin is not None, mixins)) if not mixins: return False if not plugin or not plugin.implementation: @@ -1325,7 +1334,7 @@ class PluginManager(object): for factory in inject_factories: try: return_value = factory(name, implementation) - except: + except Exception: self.logger.exception("Exception while executing injection factory %r" % factory) else: if return_value is not None: @@ -1362,7 +1371,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=(" ", "!", "#"), only_to_handler=None): - all_plugins = self.enabled_plugins.values() + self.disabled_plugins.values() + all_plugins = list(self.enabled_plugins.values()) + list(self.disabled_plugins.values()) def _log(message, level=logging.INFO): if only_to_handler is not None: @@ -1380,9 +1389,9 @@ class PluginManager(object): location_str=location_str, show_enabled=show_enabled, enabled_strs=enabled_str), - sorted(self.plugins.values(), key=lambda x: str(x).lower()))) + sorted(self.plugins.values(), key=lambda x: unicode(x).lower()))) _log("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins), - plugins=formatted_plugins)) + plugins=formatted_plugins)) def get_plugin(self, identifier, require_enabled=True): """ @@ -1473,17 +1482,18 @@ class PluginManager(object): if sorting_context is not None and isinstance(impl[1], SortablePlugin): try: sorting_value = impl[1].get_sorting_key(sorting_context) - except: + except Exception: self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0])) if sorting_value is not None: try: - int(sorting_value) + sorting_value = int(sorting_value) except ValueError: - self.logger.warn("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context)) + self.logger.warning("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context)) sorting_value = None - return sorting_value is None, sorting_value, impl[0] + plugin_info = self.get_plugin_info(impl[0], require_enabled=False) + return sorting_value is None, sorting_value, not plugin_info.bundled if plugin_info else True, impl[0] return [impl[1] for impl in sorted(result, key=sort_func)] @@ -1501,7 +1511,7 @@ class PluginManager(object): assert callable(f) implementations = self.get_implementations(*types, sorting_context=kwargs.get("sorting_context", None)) - return filter(f, implementations) + return list(filter(f, implementations)) def get_helpers(self, name, *helpers): """ @@ -1563,8 +1573,10 @@ class PluginManager(object): """ for client in self.registered_clients: - try: client(plugin, data, permissions=permissions) - except: self.logger.exception("Exception while sending plugin data to client") + try: + client(plugin, data, permissions=permissions) + except Exception: + self.logger.exception("Exception while sending plugin data to client") def _sort_hooks(self, hook): self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook], @@ -1619,13 +1631,14 @@ def is_editable_install(install_dir, package, module, location): if os.path.isfile(package_link): expected_target = os.path.normcase(os.path.realpath(location)) try: - with open(package_link) as f: + with io.open(package_link, 'rt', encoding='utf-8') as f: contents = f.readlines() for line in contents: target = os.path.normcase(os.path.realpath(os.path.join(line.strip(), module))) if target == expected_target: return True - except: + except Exception: + raise # TODO really ignore this? pass return False @@ -1645,10 +1658,13 @@ class EntryPointMetadata(pkginfo.Distribution): for metadata_file in metadata_files: try: return self.entry_point.dist.get_metadata(metadata_file) - except: + except (IOError, OSError): + # file not found, metadata file might be missing, ignore + # IOError: file not found in Py2 + # OSError (specifically FileNotFoundError): file not found in Py3 pass - warnings.warn('No package metadata found for package: {}'.format(self.entry_point.module_name)) + warnings.warn('No package metadata found for package {}'.format(self.entry_point.module_name)) class Plugin(object): diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index c8b9488cc..cb6332d40 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1,4 +1,6 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + """ This module bundles all of OctoPrint's supported plugin implementation types as well as their common parent class, :class:`OctoPrintPlugin`. @@ -16,8 +18,6 @@ Please note that the plugin implementation types are documented in the section """ -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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -25,9 +25,6 @@ __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): """ The parent class of all OctoPrint plugin mixins. @@ -69,7 +66,7 @@ class OctoPrintPlugin(Plugin): .. attribute:: _app_session_manager - The :class:`~octoprint.users.SessionManager` instance. Injected by the plugin core system upon initialization of + The :class:`~octoprint.access.users.SessionManager` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _plugin_lifecycle_manager @@ -79,7 +76,7 @@ class OctoPrintPlugin(Plugin): .. attribute:: _user_manager - The :class:`~octoprint.users.UserManager` instance. Injected by the plugin core system upon initialization + The :class:`~octoprint.access.users.UserManager` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _connectivity_checker @@ -159,6 +156,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin): is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be externally reachable, use :func:`on_after_startup` instead or additionally. + .. warning:: + + Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. + The relevant sorting context is ``StartupPlugin.on_startup``. :param string host: the host the server will listen on, may be ``0.0.0.0`` @@ -171,6 +172,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin): """ Called just after launch of the server, so when the listen loop is actually running already. + .. warning:: + + Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. + The relevant sorting context is ``StartupPlugin.on_after_startup``. """ @@ -191,6 +196,10 @@ class ShutdownPlugin(OctoPrintPlugin, SortablePlugin): """ Called upon the imminent shutdown of OctoPrint. + .. warning:: + + Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. + The relevant sorting context is ``ShutdownPlugin.on_shutdown``. """ pass @@ -225,6 +234,8 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin): js JavaScript files, such as additional view models + jsclient + JavaScript files containing additional parts for the JS Client Library (since 1.3.10) css CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode. less @@ -239,6 +250,7 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin): def get_assets(self): return dict( js=['js/my_file.js', 'js/my_other_file.js'], + clientjs=['clientjs/my_file.js'], css=['css/my_styles.css'], less=['less/my_styles.less'] ) @@ -1483,7 +1495,7 @@ 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)) @@ -1801,6 +1813,10 @@ class EventHandlerPlugin(OctoPrintPlugin): """ Called by OctoPrint upon processing of a fired event on the platform. + .. warning:: + + Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. + Arguments: event (str): The type of event that got fired, see :ref:`the list of events ` for possible values @@ -1839,8 +1855,9 @@ class SlicerPlugin(OctoPrintPlugin): The human readable name of the slicer. This will be displayed to the user during slicer selection. same_device True if the slicer runs on the same device as OctoPrint, False otherwise. Slicers running on the same - device will not be allowed to slice while a print is running due to performance reasons. Slice requests - against slicers running on the same device will result in an error. + device will not be allowed to slice on systems with less than two CPU cores (or an unknown number) while a + print is running due to performance reasons. Slice requests against slicers running on the same device and + less than two cores will result in an error. progress_report ``True`` if the slicer can report back slicing progress to OctoPrint ``False`` otherwise. source_file_types @@ -1863,6 +1880,21 @@ class SlicerPlugin(OctoPrintPlugin): destination_extensions=["gco", "gcode", "g"] ) + # noinspection PyMethodMayBeStatic + def get_slicer_extension_tree(self): + """ + Fetch additional entries to put into the extension tree for accepted files + + By default, a subtree for ``model`` files with ``stl`` extension is returned. Slicers who want to support + additional/other file types will want to override this. + + For the extension tree format, take a look at the docs of the :ref:`octoprint.filemanager.extension_tree hook `. + + Returns: (dict) a dictionary containing a valid extension subtree. + """ + from octoprint.filemanager import ContentTypeMapping + return dict(model=dict(stl=ContentTypeMapping(["stl"], "application/sla"))) + def get_slicer_profiles(self, profile_path): """ Fetch all :class:`~octoprint.slicing.SlicingProfile` stored for this slicer. @@ -1986,7 +2018,7 @@ class SlicerPlugin(OctoPrintPlugin): For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information about the slicing job under the following keys: - _analysis + analysis Analysis result of the generated machine code as returned by the slicer itself. This should match the data structure described for the analysis queue of the matching machine code format, e.g. :class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue` for GCODE files. @@ -2045,20 +2077,3 @@ class ProgressPlugin(OctoPrintPlugin): :param int progress: Current progress as a value between 0 and 100 """ pass - - -class AppPlugin(OctoPrintPlugin): - """ - Using the :class:`AppPlugin mixin` plugins may register additional :ref:`App session key providers ` - within the system. - - .. deprecated:: 1.2.0 - - Refer to the :ref:`octoprint.accesscontrol.appkey hook ` instead. - - """ - - # noinspection PyMethodMayBeStatic - def get_additional_apps(self): - return [] - diff --git a/src/octoprint/plugins/__init__.py b/src/octoprint/plugins/__init__.py index 1b0510c60..a16150cde 100644 --- a/src/octoprint/plugins/__init__.py +++ b/src/octoprint/plugins/__init__.py @@ -1 +1,4 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + # make our plugins testable diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 0dd9a4be2..bb9d6c0f6 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -1,4 +1,4 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -7,6 +7,9 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms import octoprint.plugin from octoprint.server import user_permission +from octoprint.access import USER_GROUP +from octoprint.access.permissions import Permissions +from octoprint.events import Events import flask from flask_babel import gettext @@ -34,31 +37,66 @@ class Prompt(object): class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, + octoprint.plugin.EventHandlerPlugin, octoprint.plugin.SettingsPlugin, octoprint.plugin.SimpleApiPlugin, octoprint.plugin.TemplatePlugin): + COMMAND = "M876" + CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT" + # noinspection PyMissingConstructor def __init__(self): self._prompt = None - self._selection_command = None + self._enable = "detected" + self._command = None + self._enable_emergency_sending = False + self._enable_signal_support = False + self._cap_prompt_support = False def initialize(self): - self._selection_command = self._settings.get([b"selection_command"]) + self._enable = self._settings.get(["enable"]) + self._command = self._settings.get(["command"]) + self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"]) + self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"]) + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + dict(key="INTERACT", + name="Interact with printer prompts", + description=gettext("Allows to see and interact with printer prompts"), + default_groups=[USER_GROUP], + roles=["interact"]) + ] #~ AssetPlugin def get_assets(self): - return dict(js=["js/action_command_prompt.js"]) + return dict(js=["js/action_command_prompt.js"], + clientjs=["clientjs/action_command_prompt.js"]) + + #~ EventHandlerPlugin + + def on_event(self, event, payload): + if event == Events.CONNECTED and self._enable == "always" and self._enable_signal_support: + self._printer.commands(["{command} P1".format(command=self._command)]) #~ SettingsPlugin def get_settings_defaults(self): - return dict(selection_command=None) + return dict(enable="detected", + command=self.COMMAND, + enable_emergency_sending=True, + enable_signal_support=True) def on_settings_save(self, data): octoprint.plugin.SettingsPlugin.on_settings_save(self, data) - self._selection_command = self._settings.get([b"selection_command"]) + self._enable = self._settings.get(["enable"]) + self._command = self._settings.get(["command"]) + self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"]) + self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"]) #~ SimpleApiPlugin @@ -67,7 +105,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, def on_api_command(self, command, data): if command == "select": - if not user_permission.can(): + if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can(): return flask.abort(403, "Insufficient permissions") if self._prompt is None: @@ -80,7 +118,7 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, self._answer_prompt(choice) def on_api_get(self, request): - if not user_permission.can(): + if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can(): return flask.abort(403, "Insufficient permissions") if self._prompt is None: return flask.jsonify() @@ -95,63 +133,93 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, #~ action command handler def action_command_handler(self, comm, line, action, *args, **kwargs): - if not action.startswith(b"prompt_"): - return - - if self._selection_command is None: - self._logger.info("Got a prompt command from the printer but no selection command is defined") + if not action.startswith("prompt_"): return parts = action.split(None, 1) if len(parts) == 1: action = parts[0] - parameter = b"" + parameter = "" else: action, parameter = parts - if action == b"prompt_begin": + if action == "prompt_begin": if self._prompt is not None and self._prompt.active: - self._logger.warn("Prompt is already defined") + self._logger.warning("Prompt is already defined") return self._prompt = Prompt(parameter.strip()) - elif action == b"prompt_choice" or action == b"prompt_button": + elif action == "prompt_choice" or action == "prompt_button": if self._prompt is None: return if self._prompt.active: - self._logger.warn("Prompt is already active") + self._logger.warning("Prompt is already active") return self._prompt.add_choice(parameter.strip()) - elif action == b"prompt_show": + elif action == "prompt_show": if self._prompt is None: return if self._prompt.active: - self._logger.warn("Prompt is already active") + self._logger.warning("Prompt is already active") return self._show_prompt() - elif action == b"prompt_end": + elif action == "prompt_end": if self._prompt is None: return self._close_prompt() self._prompt = None + #~ queuing handling + + def gcode_queuing_handler(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs): + if gcode != self._command: + return + + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support) or not self._enable_emergency_sending: + return + + if not "S" in cmd: + # we only force-send M876 Sx + return + + # noinspection PyProtectedMember + return comm_instance._emergency_force_send(cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode) + + #~ capability reporting + + def firmware_capability_handler(self, comm_instance, capability, enabled, already_defined, *args, **kwargs): + if capability == self.CAP_PROMPT_SUPPORT and enabled: + self._cap_prompt_support = True + if self._enable == "detected" and self._enable_signal_support: + self._printer.commands(["{command} P1".format(command=self._command)]) + #~ prompt handling def _show_prompt(self): + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): + return + self._prompt.activate() self._plugin_manager.send_plugin_message(self._identifier, dict(action="show", text=self._prompt.text, choices=self._prompt.choices)) def _close_prompt(self): + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): + return + self._prompt = None self._plugin_manager.send_plugin_message(self._identifier, dict(action="close")) def _answer_prompt(self, choice): + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): + return + self._close_prompt() - self._printer.commands([self._selection_command.format(choice=choice)]) + self._printer.commands(["{command} S{choice}".format(command=self._command, + choice=choice)]) __plugin_name__ = "Action Command Prompt Support" @@ -162,5 +230,8 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin your printer wil __plugin_license__ = "AGPLv3" __plugin_implementation__ = ActionCommandPromptPlugin() __plugin_hooks__ = { - b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler + "octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, + "octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler, + "octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions } diff --git a/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js b/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js new file mode 100644 index 000000000..9ba9b4a14 --- /dev/null +++ b/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js @@ -0,0 +1,25 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintActionCommandPromptClient = function(base) { + this.base = base; + }; + + OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) { + return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts); + }; + + OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) { + var data = { + choice: choice + }; + return this.base.simpleApiCommand("action_command_prompt", "select", data, opts); + }; + + OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient); + return OctoPrintActionCommandPromptClient; +}); diff --git a/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js index 6298a5338..bcc78928b 100644 --- a/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js +++ b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js @@ -1,39 +1,14 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintActionCommandPromptClient = function(base) { - this.base = base; - }; - - OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) { - return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts); - }; - - OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) { - var data = { - choice: choice - }; - return this.base.simpleApiCommand("action_command_prompt", "select", data, opts); - }; - - OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient); - return OctoPrintActionCommandPromptClient; -}); - $(function() { function ActionCommandPromptViewModel(parameters) { var self = this; self.loginState = parameters[0]; + self.access = parameters[1]; self._modal = undefined; self.requestData = function() { - if (!self.loginState.isUser()) return; + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return; OctoPrint.plugins.action_command_prompt.get() .done(self.fromResponse); @@ -78,7 +53,7 @@ $(function() { }; self.onDataUpdaterPluginMessage = function(plugin, data) { - if (!self.loginState.isUser()) return; + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return; if (plugin !== "action_command_prompt") { return; } @@ -99,6 +74,6 @@ $(function() { OCTOPRINT_VIEWMODELS.push({ construct: ActionCommandPromptViewModel, - dependencies: ["loginStateViewModel"] + dependencies: ["loginStateViewModel", "accessViewModel"] }); }); diff --git a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 index a30e7f9b8..df45ff760 100644 --- a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 +++ b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 @@ -2,10 +2,43 @@

- +
- -
{{ _('Use this to define the command to tell the printer about the selection. OctoPrint will replace {choice} with the index of the selected choice. E.g. M876 S{choice} will become M123 S1') }}
+ + + +
+
+
+ +
+
+ +
+ +
{{ _('Use this to define the dialog command. Default is M876. You normally should not have to change this.') }}
+
+
+
+
+ +
+
+
+
+ +
+
diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 344ad3483..2963e2cfa 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -9,20 +9,23 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms import octoprint.plugin import calendar -import codecs +import io import os import re import time import threading +import sys +PY2 = sys.version_info[0] < 3 import feedparser import flask from collections import OrderedDict +from octoprint.access import ADMIN_GROUP 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 octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag +from octoprint.util import utmify, count from flask_babel import gettext from octoprint import __version__ as OCTOPRINT_VERSION @@ -50,11 +53,13 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, dict(key="READ", name="Read announcements", description=gettext("Allows to read announcements"), + default_groups=[ADMIN_GROUP], roles=["read"]), dict(key="MANAGE", name="Manage announcement subscriptions", description=gettext("Allows to manage announcement subscriptions. Includes \"Read announcements\" " "permission"), + default_groups=[ADMIN_GROUP], roles=["manage"], permissions=["PLUGIN_ANNOUNCEMENTS_READ"]) ] @@ -104,7 +109,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, ttl=6*60, display_limit=3, summary_limit=300) - settings["enabled_channels"] = settings["channels"].keys() + settings["enabled_channels"] = list(settings["channels"].keys()) return settings def get_settings_version(self): @@ -150,7 +155,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, # Blueprint Plugin @octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403) def get_channel_data(self): from octoprint.settings import valid_boolean_trues @@ -170,7 +175,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, for key, data in channel_configs.items(): read_until = channel_configs[key].get("read_until", None) entries = sorted(self._to_internal_feed(channel_data.get(key, []), read_until=read_until), key=lambda e: e["published"], reverse=True) - unread = len(filter(lambda e: not e["read"], entries)) + unread = count(filter(lambda e: not e["read"], entries)) if read_until is None and entries: last = entries[0]["published"] @@ -191,14 +196,16 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, def etag(): import hashlib hash = hashlib.sha1() - hash.update(repr(sorted(enabled))) - hash.update(repr(sorted(forced))) - hash.update(OCTOPRINT_VERSION) + def hash_update(value): + hash.update(value.encode("utf-8")) + 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])) + hash_update(repr(channel_configs[channel])) channel_data = self._get_channel_data_from_cache(channel, channel_configs[channel]) - hash.update(repr(channel_data)) + hash_update(repr(channel_data)) return hash.hexdigest() @@ -211,7 +218,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, unless=lambda: force)(view)() @octoprint.plugin.BlueprintPlugin.route("/channels/", methods=["POST"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403) def channel_command(self, channel): from octoprint.server.util.flask import get_json_command_from_request @@ -358,7 +365,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, now = time.time() if os.stat(channel_path).st_mtime + ttl > now: d = feedparser.parse(channel_path) - self._logger.debug(u"Loaded channel {} from cache at {}".format(key, channel_path)) + self._logger.debug("Loaded channel {} from cache at {}".format(key, channel_path)) return d return None @@ -373,15 +380,15 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, start = time.time() r = requests.get(url, timeout=30) r.raise_for_status() - self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start)) - except Exception as e: + self._logger.info("Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start)) + except Exception: self._logger.exception( - u"Could not fetch channel {} from {}: {}".format(key, config["url"], str(e))) + "Could not fetch channel {} from {}".format(key, config["url"])) return None response = r.text channel_path = self._get_channel_cache_path(key) - with codecs.open(channel_path, mode="w", encoding="utf-8") as f: + with io.open(channel_path, mode="wt", encoding="utf-8") as f: f.write(response) return feedparser.parse(response) @@ -391,15 +398,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, result = [] if "entries" in feed: for entry in feed["entries"]: - internal_entry = self._to_internal_entry(entry, read_until=read_until) - if internal_entry: - result.append(internal_entry) + try: + internal_entry = self._to_internal_entry(entry, read_until=read_until) + if internal_entry: + result.append(internal_entry) + except Exception: + self._logger.exception("Error while converting entry from feed, skipping it") return result def _to_internal_entry(self, entry, read_until=None): """Convert feed entries to internal data structure.""" - published = calendar.timegm(entry["published_parsed"]) + timestamp = entry.get("published_parsed", None) + if timestamp is None: + timestamp = entry.get("updated_parsed", None) + if timestamp is None: + return None + + published = calendar.timegm(timestamp) read = True if read_until is not None: @@ -423,22 +439,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, _image_tag_re = re.compile(r'') def _strip_images(text): """ - >>> _strip_images(u"I'm a link and this is an image: foo") - u"I'm a link and this is an image: " - >>> _strip_images(u"One and two and three and four \\"four\\"") - u'One and two and three and four ' - >>> _strip_images(u"No images here") - u'No images here' + >>> from octoprint.util import to_native_str + >>> to_native_str(_strip_images("I'm a link and this is an image: foo")) + "I'm a link and this is an image: " + >>> to_native_str(_strip_images("One and two and three and four \\"four\\"")) + 'One and two and three and four ' + >>> to_native_str(_strip_images("No images here")) + 'No images here' """ return _image_tag_re.sub('', text) def _replace_images(text, callback): """ >>> callback = lambda img: "foobar" - >>> _replace_images(u"I'm a link and this is an image: foo", callback) - u"I'm a link and this is an image: foobar" - >>> _replace_images(u"One and two and three and four \\"four\\"", callback) - u'One foobar and two foobar and three foobar and four foobar' + >>> from octoprint.util import to_native_str + >>> to_native_str(_replace_images("I'm a link and this is an image: foo", callback)) + "I'm a link and this is an image: foobar" + >>> to_native_str(_replace_images("One and two and three and four \\"four\\"", callback)) + 'One foobar and two foobar and three foobar and four foobar' """ result = text for match in _image_tag_re.finditer(text): @@ -450,14 +468,15 @@ def _replace_images(text, callback): _image_src_re = re.compile(r'src=(?P[\'"]*)(?P.*?)(?P=quote)(?=\s+|>)') def _lazy_images(text, placeholder=None): """ - >>> _lazy_images(u"I'm a link and this is an image: foo") - u'I\\'m a link and this is an image: \\'foo\\'' - >>> _lazy_images(u"I'm a link and this is an image: foo", placeholder="ph.png") - u'I\\'m a link and this is an image: \\'foo\\'' - >>> _lazy_images(u"One and two and three and four \\"four\\"", placeholder="ph.png") - u'One and two and three and four four' - >>> _lazy_images(u"No images here") - u'No images here' + >>> from octoprint.util import to_native_str + >>> to_native_str(_lazy_images("I'm a link and this is an image: foo")) + 'I\\'m a link and this is an image: \\'foo\\'' + >>> to_native_str(_lazy_images("I'm a link and this is an image: foo", placeholder="ph.png")) + 'I\\'m a link and this is an image: \\'foo\\'' + >>> to_native_str(_lazy_images("One and two and three and four \\"four\\"", placeholder="ph.png")) + 'One and two and three and four four' + >>> to_native_str(_lazy_images("No images here")) + 'No images here' """ if placeholder is None: # 1px transparent gif @@ -476,18 +495,23 @@ def _lazy_images(text, placeholder=None): def _strip_tags(text): """ - >>> _strip_tags(u"Hello world<img src='foo.jpg'>") - u"Hello world<img src='foo.jpg'>" - >>> _strip_tags(u"> > Foo") - u'> > Foo' + >>> from octoprint.util import to_native_str + >>> to_native_str(_strip_tags("Hello world<img src='foo.jpg'>")) + "Hello world<img src='foo.jpg'>" + >>> to_native_str(_strip_tags("> > Foo")) + '> > Foo' """ - - from HTMLParser import HTMLParser + try: + # noinspection PyCompatibility + from html.parser import HTMLParser + except ImportError: + # noinspection PyCompatibility + from HTMLParser import HTMLParser class TagStripper(HTMLParser): - def __init__(self): - HTMLParser.__init__(self) + def __init__(self, **kw): + HTMLParser.__init__(self, **kw) self._fed = [] def handle_data(self, data): @@ -502,7 +526,7 @@ def _strip_tags(text): def get_data(self): return "".join(self._fed) - tag_stripper = TagStripper() + tag_stripper = TagStripper() if PY2 else TagStripper(convert_charrefs=False) tag_stripper.feed(text) return tag_stripper.get_data() diff --git a/src/octoprint/plugins/announcements/static/js/announcements.js b/src/octoprint/plugins/announcements/static/js/announcements.js index e4fc58f33..ece0a9367 100644 --- a/src/octoprint/plugins/announcements/static/js/announcements.js +++ b/src/octoprint/plugins/announcements/static/js/announcements.js @@ -67,9 +67,11 @@ $(function() { return link; }; - self.markRead = function(channel, until) { + self.markRead = function(channel, until, reload) { if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return; + reload = !!reload; + var url = PLUGIN_BASEURL + "announcements/channels/" + channel; var payload = { @@ -84,7 +86,9 @@ $(function() { data: JSON.stringify(payload), contentType: "application/json; charset=UTF-8", success: function() { - self.retrieveData() + if (reload) { + self.retrieveData() + } } }) }; diff --git a/src/octoprint/plugins/announcements/templates/announcements.jinja2 b/src/octoprint/plugins/announcements/templates/announcements.jinja2 index 524e8850a..47bf0952e 100644 --- a/src/octoprint/plugins/announcements/templates/announcements.jinja2 +++ b/src/octoprint/plugins/announcements/templates/announcements.jinja2 @@ -28,7 +28,7 @@
diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py new file mode 100644 index 000000000..5912f02e7 --- /dev/null +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -0,0 +1,422 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, unicode_literals + +import flask +import threading +import os +import yaml +import io +import time +from binascii import hexlify +from collections import defaultdict +from flask_babel import gettext + +import octoprint.plugin +from octoprint.settings import valid_boolean_trues +from octoprint.server.util.flask import restricted_access, no_firstrun_access +from octoprint.server import NO_CONTENT, current_user, admin_permission +from octoprint.util import atomic_write, monotonic_time, ResettableTimer + +from octoprint.access import ADMIN_GROUP +from octoprint.access.permissions import Permissions + + +CUTOFF_TIME = 10 * 60 # 10min +POLL_TIMEOUT = 5 # 5 seconds + +class AppAlreadyExists(Exception): + pass + + +class PendingDecision(object): + def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None): + self.app_id = app_id + self.app_token = app_token + self.user_id = user_id + self.user_token = user_token + self.created = monotonic_time() + + if callable(timeout_callback): + self.poll_timeout = ResettableTimer(POLL_TIMEOUT, timeout_callback, [user_token]) + self.poll_timeout.start() + + def external(self): + return dict(app_id=self.app_id, + user_id=self.user_id, + user_token=self.user_token) + + +class ReadyDecision(object): + def __init__(self, app_id, app_token, user_id): + self.app_id = app_id + self.app_token = app_token + self.user_id = user_id + + @classmethod + def for_pending(cls, pending, user_id): + return cls(pending.app_id, pending.app_token, user_id) + + +class ActiveKey(object): + def __init__(self, app_id, api_key, user_id): + self.app_id = app_id + self.api_key = api_key + self.user_id = user_id + + def external(self): + return dict(app_id=self.app_id, + api_key=self.api_key, + user_id=self.user_id) + + def internal(self): + return dict(app_id=self.app_id, + api_key=self.api_key) + + @classmethod + def for_internal(cls, internal, user_id): + return cls(internal["app_id"], internal["api_key"], user_id) + + +class AppKeysPlugin(octoprint.plugin.AssetPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin): + + def __init__(self): + self._pending_decisions = [] + self._pending_lock = threading.RLock() + + self._ready_decisions = [] + self._ready_lock = threading.RLock() + + self._keys = defaultdict(list) + self._keys_lock = threading.RLock() + + self._key_path = None + + def initialize(self): + self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml") + self._load_keys() + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + dict(key="ADMIN", + name="Admin access", + description=gettext("Allows administrating all application keys"), + roles=["admin"], + dangerous=True, + default_groups=[ADMIN_GROUP]) + ] + + ##~~ TemplatePlugin + + def get_template_configs(self): + return [dict(type="usersettings", name=gettext("Application Keys")), + dict(type="settings", name=gettext("Application Keys"))] + + ##~~ AssetPlugin + + def get_assets(self): + return dict(js=["js/appkeys.js"], + clientjs=["clientjs/appkeys.js"], + less=["less/appkeys.less"], + css=["css/appkeys.css"]) + + ##~~ BlueprintPlugin mixin + + @octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"]) + @no_firstrun_access + def handle_probe(self): + return NO_CONTENT + + @octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"]) + @no_firstrun_access + def handle_request(self): + data = flask.request.json + if not "app" in data: + return flask.make_response("No app name provided", 400) + + app_name = data["app"] + user_id = None + if "user" in data: + user_id = data["user"] + + app_token, user_token = self._add_pending_decision(app_name, user_id=user_id) + + self._plugin_manager.send_plugin_message(self._identifier, dict(type="request_access", + app_name=app_name, + user_token=user_token, + user_id=user_id)) + response = flask.jsonify(app_token=app_token) + response.status_code = 201 + response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True) + return response + + @octoprint.plugin.BlueprintPlugin.route("/request/") + @no_firstrun_access + def handle_decision_poll(self, app_token): + result = self._get_pending_by_app_token(app_token) + if result: + for pending_decision in result: + pending_decision.poll_timeout.reset() + + response = flask.jsonify(message="Awaiting decision") + response.status_code = 202 + return response + + result = self._get_decision(app_token) + if result: + return flask.jsonify(api_key=result) + + return flask.abort(404) + + @octoprint.plugin.BlueprintPlugin.route("/decision/", methods=["POST"]) + @restricted_access + def handle_decision(self, user_token): + data = flask.request.json + if not "decision" in data: + return flask.make_response("No decision provided", 400) + decision = data["decision"] in valid_boolean_trues + user_id = current_user.get_name() + + result = self._set_decision(user_token, decision, user_id) + if not result: + return flask.abort(404) + + # Close access_request dialog for this request on all open OctoPrint connections + self._plugin_manager.send_plugin_message(self._identifier, dict( + type="end_request", + user_token=user_token + )) + + return NO_CONTENT + + def is_blueprint_protected(self): + return False # No API key required to request API access + + ##~~ SimpleApiPlugin mixin + + def get_api_commands(self): + return dict(generate=["app"], + revoke=["key"]) + + def on_api_get(self, request): + user_id = current_user.get_name() + if not user_id: + return flask.abort(403) + + if request.values.get("all") in valid_boolean_trues and Permissions.PLUGIN_APPKEYS_ADMIN.can(): + keys = self._all_api_keys() + else: + keys = self._api_keys_for_user(user_id) + + return flask.jsonify(keys=list(map(lambda x: x.external(), keys)), + pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id))) + + def on_api_command(self, command, data): + user_id = current_user.get_name() + if not user_id: + return flask.abort(403) + + if command == "revoke": + api_key = data.get("key") + if not api_key: + return flask.abort(400) + + if not admin_permission.can(): + user_for_key = self._user_for_api_key(api_key) + if user_for_key is None or user_for_key.user_id != user_id: + return flask.abort(403) + + self._delete_api_key(api_key) + + elif command == "generate": + # manual generateKey + app_name = data.get("app") + if not app_name: + return flask.abort(400) + + self._add_api_key(user_id, app_name.strip()) + + return NO_CONTENT + + ##~~ key validator hook + + def validate_api_key(self, api_key, *args, **kwargs): + return self._user_for_api_key(api_key) + + ##~~ Helpers + + def _add_pending_decision(self, app_name, user_id=None): + app_token = self._generate_key() + user_token = self._generate_key() + + with self._pending_lock: + self._remove_stale_pending() + self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token, + timeout_callback=self._expire_pending)) + + return app_token, user_token + + def _get_pending_by_app_token(self, app_token): + result = [] + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.app_token == app_token: + result.append(data) + return result + + def _get_pending_by_user_id(self, user_id): + result = [] + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.user_id == user_id or data.user_id is None: + result.append(data) + return result + + def _expire_pending(self, user_token): + with self._pending_lock: + len_before = len(self._pending_decisions) + self._pending_decisions = list(filter(lambda x: x.user_token != user_token, + self._pending_decisions)) + len_after = len(self._pending_decisions) + + if len_after < len_before: + self._plugin_manager.send_plugin_message(self._identifier, dict( + type="end_request", + user_token=user_token + )) + + def _remove_stale_pending(self): + with self._pending_lock: + cutoff = monotonic_time() - CUTOFF_TIME + len_before = len(self._pending_decisions) + self._pending_decisions = list(filter(lambda x: x.created >= cutoff, + self._pending_decisions)) + len_after = len(self._pending_decisions) + if len_after < len_before: + self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after)) + + def _set_decision(self, user_token, decision, user_id): + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.user_token == user_token and (data.user_id == user_id or data.user_id is None): + pending = data + break + else: + return False # not found + + if decision: + with self._ready_lock: + self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id)) + + with self._pending_lock: + self._pending_decisions = list(filter(lambda x: x.user_token != user_token, + self._pending_decisions)) + + return True + + def _get_decision(self, app_token): + self._remove_stale_pending() + + with self._ready_lock: + for data in self._ready_decisions: + if data.app_token == app_token: + decision = data + break + else: + return False # not found + + api_key = self._add_api_key(decision.user_id, decision.app_id) + + with self._ready_lock: + self._ready_decisions = list(filter(lambda x: x.app_token != app_token, + self._ready_decisions)) + + return api_key + + def _add_api_key(self, user_id, app_name): + with self._keys_lock: + for key in self._keys[user_id]: + if key.app_id.lower() == app_name.lower(): + return key.api_key + + key = ActiveKey(app_name, self._generate_key(), user_id) + self._keys[user_id].append(key) + self._save_keys() + return key.api_key + + def _delete_api_key(self, api_key): + with self._keys_lock: + for user_id, data in self._keys.items(): + self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data)) + self._save_keys() + + def _user_for_api_key(self, api_key): + with self._keys_lock: + for user_id, data in self._keys.items(): + if any(filter(lambda x: x.api_key == api_key, data)): + return self._user_manager.findUser(userid=user_id) + return None + + def _api_keys_for_user(self, user_id): + with self._keys_lock: + return self._keys[user_id] + + def _all_api_keys(self): + with self._keys_lock: + result = [] + for user_id, keys in self._keys.items(): + result += keys + return result + + def _generate_key(self): + return hexlify(os.urandom(16)) + + def _load_keys(self): + with self._keys_lock: + if not os.path.exists(self._key_path): + return + + try: + with io.open(self._key_path, 'rt', encoding="utf-8", errors="strict") as f: + persisted = yaml.safe_load(f) + except Exception: + self._logger.exception("Could not load application keys from {}".format(self._key_path)) + return + + if not isinstance(persisted, dict): + return + + keys = defaultdict(list) + for user_id, persisted_keys in persisted.items(): + keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys] + self._keys = keys + + def _save_keys(self): + with self._keys_lock: + to_persist = dict() + for user_id, keys in self._keys.items(): + to_persist[user_id] = [x.internal() for x in keys] + + try: + with atomic_write(self._key_path, mode='wt') as f: + yaml.safe_dump(to_persist, f, allow_unicode=True) + except Exception: + self._logger.exception("Could not write application keys to {}".format(self._key_path)) + +__plugin_name__ = "Application Keys Plugin" +__plugin_description__ = "Implements a workflow for third party clients to obtain API keys" +__plugin_author__ = "Gina Häußge, Aldo Hoeben" +__plugin_disabling_discouraged__ = gettext("Without this plugin third party clients will no longer be able to " + "obtain an API key without you manually copy-pasting it.") +__plugin_implementation__ = AppKeysPlugin() +__plugin_hooks__ = { + "octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions +} diff --git a/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js new file mode 100644 index 000000000..9b29428aa --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js @@ -0,0 +1,98 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintAppKeysClient = function(base) { + this.base = base; + }; + + OctoPrintAppKeysClient.prototype.getKeys = function(opts) { + return this.base.simpleApiGet("appkeys", opts); + }; + + OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) { + return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts); + }; + + OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) { + return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts); + }; + + OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) { + return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts); + }; + + OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) { + return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts); + }; + + OctoPrintAppKeysClient.prototype.probe = function(opts) { + return this.base.get(this.base.getBlueprintUrl("appkeys") + "probe", opts); + }; + + OctoPrintAppKeysClient.prototype.request = function(app, opts) { + return this.requestForUser(app, undefined, opts); + }; + + OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) { + return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts); + }; + + OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) { + return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts); + }; + + OctoPrintAppKeysClient.prototype.authenticate = function(app, user) { + var deferred = $.Deferred(); + var client = this; + + client.probe() + .done(function() { + client.requestForUser(app, user) + .done(function(response) { + var token = response.app_token; + if (!token) { + // no token received, something went wrong + deferred.reject(); + return; + } + + var interval = 1000; + var poll = function() { + client.checkDecision(token) + .done(function(response) { + if (response.api_key) { + // got a decision, resolve the promise + deferred.resolve(response.api_key); + } else { + // no decision yet, poll a bit more + deferred.notify(); + window.setTimeout(poll, interval); + } + }) + .fail(function() { + // something went wrong + deferred.reject(); + }); + }; + window.setTimeout(poll, interval); + }) + .fail(function() { + // something went wrong + deferred.reject(); + }); + }) + .fail(function() { + // workflow unsupported + deferred.reject(); + }); + + return deferred.promise(); + }; + + OctoPrintClient.registerPluginComponent("appkeys", OctoPrintAppKeysClient); + return OctoPrintAppKeysClient; +}); diff --git a/src/octoprint/plugins/appkeys/static/css/appkeys.css b/src/octoprint/plugins/appkeys/static/css/appkeys.css new file mode 100644 index 000000000..6240d21d7 --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/css/appkeys.css @@ -0,0 +1 @@ +#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a{color:#000}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox],#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox]{margin-top:0} \ No newline at end of file diff --git a/src/octoprint/plugins/appkeys/static/js/appkeys.js b/src/octoprint/plugins/appkeys/static/js/appkeys.js new file mode 100644 index 000000000..bdd72e97b --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/js/appkeys.js @@ -0,0 +1,308 @@ +$(function() { + function UserAppKeysViewModel(parameters) { + var self = this; + self.loginState = parameters[0]; + + self.keys = new ItemListHelper( + "plugin.appkeys.userkeys", + { + "app": function (a, b) { + // sorts ascending + if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1; + if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1; + return 0; + } + }, + { + }, + "app", + [], + [], + 5 + ); + self.pending = {}; + self.openRequests = {}; + + self.editorApp = ko.observable(); + + self.requestData = function() { + OctoPrint.plugins.appkeys.getKeys() + .done(self.fromResponse); + }; + + self.fromResponse = function(response) { + self.keys.updateItems(response.keys); + self.pending = response.pending; + _.each(self.pending, function(data, token) { + self.openRequests[token] = self.promptForAccess(data.app_id, token); + }) + }; + + self.generateKey = function() { + return OctoPrint.plugins.appkeys.generateKey(self.editorApp()) + .done(self.requestData) + .done(function() { + self.editorApp(""); + }); + }; + + self.revokeKey = function(key) { + var perform = function() { + OctoPrint.plugins.appkeys.revokeKey(key) + .done(self.requestData); + }; + + showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}), + perform); + }; + + self.allowApp = function(token) { + return OctoPrint.plugins.appkeys.decide(token, true) + .done(self.requestData); + }; + + self.denyApp = function(token) { + return OctoPrint.plugins.appkeys.decide(token, false) + .done(self.requestData); + }; + + self.promptForAccess = function(app, token) { + var message = gettext("\"%(app)s\" has requested access to control OctoPrint through the API."); + message = _.sprintf(message, {app: app}); + message = "

" + message + "

" + gettext("Do you want to allow access to this application with your user account?") + "

"; + return new PNotify({ + title: gettext("Access Request"), + text: message, + hide: false, + icon: "fa fa-key", + confirm: { + confirm: true, + buttons: [{ + text: gettext("Allow"), + click: function(notice) { + self.allowApp(token); + notice.remove(); + } + }, { + text: gettext("Deny"), + click: function(notice) { + self.denyApp(token); + notice.remove(); + } + }] + }, + buttons: { + sticker: false, + closer: false + } + }); + }; + + self.onUserSettingsShown = function() { + self.requestData(); + }; + + self.onUserLoggedIn = function() { + self.requestData(); + }; + + self.onDataUpdaterPluginMessage = function(plugin, data) { + if (plugin !== "appkeys") { + return; + } + + var app, token, user; + + if (data.type === "request_access" && self.loginState.isUser()) { + app = data.app_name; + token = data.user_token; + user = data.user_id; + + if (user && user !== self.loginState.username()) { + return; + } + + if (self.pending[token] !== undefined) { + return; + } + + self.openRequests[token] = self.promptForAccess(app, token); + + } else if (data.type === "end_request") { + token = data.user_token; + + if (self.openRequests[token] !== undefined) { + // another instance responded to the access request before the current user did + if (self.openRequests[token].state !== "closed") { + self.openRequests[token].remove(); + } + delete self.openRequests[token] + } + } + }; + } + + function AllAppKeysViewModel(parameters) { + var self = this; + self.loginState = parameters[0]; + + self.keys = new ItemListHelper( + "plugin.appkeys.allkeys", + { + "user_app": function (a, b) { + // sorts ascending, first by user, then by app + if (a["user_id"] > b["user_id"]) return 1; + if (a["user_id"] < b["user_id"]) return -1; + + if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1; + if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1; + + return 0; + } + }, + { + }, + "user_app", + [], + [], + 10 + ); + self.users = ko.observableArray([]); + self.apps = ko.observableArray([]); + + self.markedForDeletion = ko.observableArray([]); + + self.onSettingsShown = function() { + self.requestData(); + }; + + self.onUserLoggedIn = function() { + self.requestData(); + }; + + self.requestData = function() { + OctoPrint.plugins.appkeys.getAllKeys() + .done(self.fromResponse); + }; + + self.fromResponse = function(response) { + self.keys.updateItems(response.keys); + + var users = []; + var apps = []; + _.each(response.keys, function(key) { + users.push(key.user_id); + apps.push(key.app_id.toLowerCase()); + }); + + users = _.uniq(users); + users.sort(); + self.users(users); + + apps = _.uniq(apps); + apps.sort(); + self.apps(apps); + }; + + self.revokeKey = function(key) { + var perform = function() { + OctoPrint.plugins.appkeys.revokeKey(key) + .done(self.requestData); + }; + + showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}), + perform); + }; + + self.revokeMarked = function() { + var perform = function() { + self._bulkRevoke(self.markedForDeletion()) + .done(function() { + self.markedForDeletion.removeAll(); + }); + }; + + showConfirmationDialog(_.sprintf(gettext("You are about to revoke %(count)d application keys."), {count: self.markedForDeletion().length}), + perform); + }; + + self.markAllOnPageForDeletion = function() { + self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.keys.paginatedItems(), "api_key")))); + }; + + self.markAllForDeletion = function() { + self.markedForDeletion(_.uniq(_.map(self.keys.allItems, "api_key"))); + }; + + self.markAllByUserForDeletion = function(user) { + self.markAllByFilterForDeletion(function(e) { return (e.user_id === user); }); + }; + + self.markAllByAppForDeletion = function(app) { + self.markAllByFilterForDeletion(function(e) { return (e.app_id.toLowerCase() === app); }) + }; + + self.markAllByFilterForDeletion = function(filter) { + self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(_.filter(self.keys.allItems, filter), "api_key")))); + }; + + self.clearMarked = function() { + self.markedForDeletion.removeAll(); + }; + + self._bulkRevoke = function(keys) { + var title, message, handler; + + title = gettext("Revoking application keys"); + message = _.sprintf(gettext("Revoking %(count)d application keys..."), {count: keys.length}); + handler = function(key) { + return OctoPrint.plugins.appkeys.revokeKey(key) + .done(function() { + deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: key}), true); + }) + .fail(function(jqXHR) { + var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: key}); + var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: key, error: jqXHR.responseText}); + deferred.notify(short, long, false); + }); + }; + + var deferred = $.Deferred(); + + var promise = deferred.promise(); + + var options = { + title: title, + message: message, + max: keys.length, + output: true + }; + showProgressModal(options, promise); + + var requests = []; + _.each(keys, function(key) { + var request = handler(key); + requests.push(request) + }); + $.when.apply($, _.map(requests, wrapPromiseWithAlways)) + .done(function() { + deferred.resolve(); + self.requestData(); + }); + + return promise; + }; + } + + OCTOPRINT_VIEWMODELS.push([ + UserAppKeysViewModel, + ["loginStateViewModel"], + ["#usersettings_plugin_appkeys"] + ]); + + OCTOPRINT_VIEWMODELS.push([ + AllAppKeysViewModel, + ["loginStateViewModel"], + ["#settings_plugin_appkeys"] + ]) +}); diff --git a/src/octoprint/plugins/appkeys/static/less/appkeys.less b/src/octoprint/plugins/appkeys/static/less/appkeys.less new file mode 100644 index 000000000..0e7d3f1c8 --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/less/appkeys.less @@ -0,0 +1,24 @@ +#settings_plugin_appkeys_userkeys_table, +#settings_plugin_appkeys_allkeys_table { + .settings_plugin_appkeys_app { + } + .settings_plugin_appkeys_actions { + width: 75px; + text-align: center; + + a { + color: black; + } + } + .settings_plugin_appkeys_user { + width: 100px; + } + .settings_plugin_appkeys_checkbox { + text-align: center; + width: 10px; + + input[type="checkbox"] { + margin-top: 0; + } + } +} diff --git a/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 new file mode 100644 index 000000000..700fb8f2b --- /dev/null +++ b/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 @@ -0,0 +1,59 @@ +
+

{{ _('There are no application keys registered yet.') }}

+
+
+ + + + + + + + + + + + + + + + + + +
{{ _('User') }}{{ _('Application identifier') }}{{ _('Action') }}

{{ _('API Key') }}:
+ +
diff --git a/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 new file mode 100644 index 000000000..2499b2330 --- /dev/null +++ b/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 @@ -0,0 +1,49 @@ +{{ _('Registered application keys') }} + +
+

{{ _('There are no application keys registered yet.') }}

+
+
+ + + + + + + + + + + + + +
{{ _('Application identifier') }}{{ _('Action') }}

{{ _('API Key') }}:
+ +
+ +{{ _('Manually generate an application key') }} + +
+
+ +
+ +
+
+ +
+
+ +
+
+
diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py new file mode 100644 index 000000000..9b4d759b5 --- /dev/null +++ b/src/octoprint/plugins/backup/__init__.py @@ -0,0 +1,971 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import octoprint.plugin + +from octoprint.settings import default_settings +from octoprint.plugin.core import FolderOrigin +from octoprint.server import admin_permission, NO_CONTENT +from octoprint.server.util.flask import no_firstrun_access +from octoprint.util import is_hidden_path, to_bytes +from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version, is_octoprint_compatible +from octoprint.util.platform import is_os_compatible +from octoprint.util.pip import LocalPipCaller +from octoprint.access import ADMIN_GROUP +from octoprint.access.permissions import Permissions + +try: + from os import scandir +except ImportError: + from scandir import scandir + +try: + import zlib # check if zlib is available +except ImportError: + zlib = None + + +from flask_babel import gettext + +import io +import flask +import logging +import os +import requests +import sarge +import shutil +import tempfile +import threading +import time +import zipfile +import json +import sys +import traceback + + +UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json" + +BACKUP_FILE_PREFIX = "octoprint-backup" + +BACKUP_DATE_TIME_FMT = "%Y%m%d-%H%M%S" + +def build_backup_filename(): + return "{}-{}.zip".format(BACKUP_FILE_PREFIX, + time.strftime(BACKUP_DATE_TIME_FMT)) + + +class BackupPlugin(octoprint.plugin.SettingsPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.StartupPlugin): + + _pip_caller = None + + # noinspection PyMissingConstructor + def __init__(self): + self._in_progress = [] + self._in_progress_lock = threading.RLock() + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + dict(key="ACCESS", + name="Backup access", + description=gettext("Allows access to backups and restores"), + roles=["access"], + dangerous=True, + default_groups=[ADMIN_GROUP]) + ] + + ##~~ StartupPlugin + + def on_after_startup(self): + self._clean_dir_backup(self._settings._basedir, + on_log_progress=self._logger.info) + + ##~~ AssetPlugin + + def get_assets(self): + return dict(js=["js/backup.js"], + clientjs=["clientjs/backup.js"], + css=["css/backup.css"], + less=["less/backup.less"]) + + ##~~ TemplatePlugin + + def get_template_configs(self): + return [dict(type="settings", name=gettext("Backup & Restore"))] + + ##~~ BlueprintPlugin + + @octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def get_state(self): + backups = self._get_backups() + unknown_plugins = self._get_unknown_plugins() + return flask.jsonify(backups=backups, + backup_in_progress=len(self._in_progress) > 0, + unknown_plugins=unknown_plugins, + restore_supported=is_os_compatible(["!windows"])) + + @octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def get_unknown_plugins(self): + # TODO add caching + unknown_plugins = self._get_unknown_plugins() + return flask.jsonify(unknown_plugins=unknown_plugins) + + @octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def delete_unknown_plugins(self): + data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) + try: + os.remove(data_file) + except Exception: + pass + return NO_CONTENT + + @octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def get_backups(self): + backups = self._get_backups() + return flask.jsonify(backups=backups) + + @octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def create_backup(self): + backup_file = build_backup_filename() + + data = flask.request.json + exclude = data.get("exclude", []) + + def on_backup_start(name, temporary_path, exclude): + self._logger.info("Creating backup zip at {} (excluded: {})...".format(temporary_path, + ",".join(exclude) if len(exclude) else "-")) + + with self._in_progress_lock: + self._in_progress.append(name) + self._send_client_message("backup_started", payload=dict(name=name)) + + def on_backup_done(name, final_path, exclude): + with self._in_progress_lock: + self._in_progress.remove(name) + self._send_client_message("backup_done", payload=dict(name=name)) + + self._logger.info("... done creating backup zip.") + + def on_backup_error(name, exc_info): + with self._in_progress_lock: + try: + self._in_progress.remove(name) + except ValueError: + # we'll ignore that + pass + + self._send_client_message("backup_error", payload=dict(name=name, + error="{}".format(exc_info[1]))) + self._logger.error("Error while creating backup zip", exc_info=exc_info) + + thread = threading.Thread(target=self._create_backup, + args=(backup_file,), + kwargs=dict(exclude=exclude, + settings=self._settings, + plugin_manager=self._plugin_manager, + datafolder=self.get_plugin_data_folder(), + on_backup_start=on_backup_start, + on_backup_done=on_backup_done, + on_backup_error=on_backup_error)) + thread.daemon = True + thread.start() + + response = flask.jsonify(started=True, + name=backup_file) + response.status_code = 201 + return response + + @octoprint.plugin.BlueprintPlugin.route("/backup/", methods=["DELETE"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def delete_backup(self, filename): + backup_folder = self.get_plugin_data_folder() + full_path = os.path.realpath(os.path.join(backup_folder, filename)) + if full_path.startswith(backup_folder) \ + and os.path.exists(full_path) \ + and not is_hidden_path(full_path): + try: + os.remove(full_path) + except Exception: + self._logger.exception("Could not delete {}".format(filename)) + raise + return NO_CONTENT + + @octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"]) + @no_firstrun_access + @Permissions.PLUGIN_BACKUP_ACCESS.require(403) + def perform_restore(self): + if not is_os_compatible(["!windows"]): + return flask.make_response("Invalid request, the restores are not supported on the underlying operating system", 400) + + input_name = "file" + input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"]) + + if input_upload_path in flask.request.values: + # file to restore was uploaded + path = flask.request.values[input_upload_path] + + elif flask.request.json and "path" in flask.request.json: + # existing backup is supposed to be restored + backup_folder = self.get_plugin_data_folder() + path = os.path.realpath(os.path.join(backup_folder, flask.request.json["path"])) + if not path.startswith(backup_folder) \ + or not os.path.exists(path) \ + or is_hidden_path(path): + return flask.abort(404) + + else: + return flask.make_response("Invalid request, neither a file nor a path of a file to restore provided", 400) + + def on_install_plugins(plugins): + force_user = self._settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"]) + pip_args = self._settings.global_get(["plugins", "pluginmanager", "pip_args"]) + + def on_log(line): + self._logger.info(line) + self._send_client_message("logline", dict(line=line, type="stdout")) + + for plugin in plugins: + octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"]) + os_compatible = is_os_compatible(plugin["compatibility"]["os"]) + compatible = octoprint_compatible and os_compatible + if not compatible: + if not octoprint_compatible and not os_compatible: + self._logger.warn("Cannot install plugin {}, it is incompatible to this version " + "of OctoPrint and the underlying operating system".format(plugin["id"])) + elif not octoprint_compatible: + self._logger.warn("Cannot install plugin {}, it is incompatible to this version " + "of OctoPrint".format(plugin["id"])) + elif not os_compatible: + self._logger.warn("Cannot install plugin {}, it is incompatible to the underlying " + "operating system".format(plugin["id"])) + self._send_client_message("plugin_incompatible", dict(plugin=plugin["id"], + octoprint_compatible=octoprint_compatible, + os_compatible=os_compatible)) + continue + + self._logger.info("Installing plugin {}".format(plugin["id"])) + self._send_client_message("installing_plugin", dict(plugin=plugin["id"])) + self.__class__._install_plugin(plugin, + force_user=force_user, + pip_args=pip_args, + on_log=on_log) + + def on_report_unknown_plugins(plugins): + self._send_client_message("unknown_plugins", payload=dict(plugins=plugins)) + + def on_log_progress(line): + self._logger.info(line) + self._send_client_message("logline", payload=dict(line=line, stream="stdout")) + + def on_log_error(line, exc_info=None): + self._logger.error(line, exc_info=exc_info) + self._send_client_message("logline", payload=dict(line=line, stream="stderr")) + + if exc_info is not None: + exc_type, exc_value, exc_tb = exc_info + output = traceback.format_exception(exc_type, exc_value, exc_tb) + for line in output: + self._send_client_message("logline", payload=dict(line=line.rstrip(), stream="stderr")) + + def on_restore_start(path): + self._send_client_message("restore_started") + + def on_restore_done(path): + self._send_client_message("restore_done") + + def on_restore_failed(path): + self._send_client_message("restore_failed") + + def on_invalid_backup(line): + on_log_error(line) + + archive = tempfile.NamedTemporaryFile(delete=False) + archive.close() + shutil.copy(path, archive.name) + path = archive.name + + # noinspection PyTypeChecker + thread = threading.Thread(target=self._restore_backup, + args=(path,), + kwargs=dict(settings=self._settings, + plugin_manager=self._plugin_manager, + datafolder=self.get_plugin_data_folder(), + on_install_plugins=on_install_plugins, + on_report_unknown_plugins=on_report_unknown_plugins, + on_invalid_backup=on_invalid_backup, + on_log_progress=on_log_progress, + on_log_error=on_log_error, + on_restore_start=on_restore_start, + on_restore_done=on_restore_done, + on_restore_failed=on_restore_failed)) + thread.daemon = True + thread.start() + + return flask.jsonify(started=True) + + ##~~ tornado hook + + def route_hook(self, *args, **kwargs): + from octoprint.server.util.tornado import LargeResponseHandler, path_validation_factory + from octoprint.util import is_hidden_path + from octoprint.server import app + from octoprint.server.util.tornado import access_validation_factory + from octoprint.server.util.flask import admin_validator + + return [ + (r"/download/(.*)", LargeResponseHandler, dict(path=self.get_plugin_data_folder(), + as_attachment=True, + path_validation=path_validation_factory(lambda path: not is_hidden_path(path), + status_code=404), + access_validation=access_validation_factory(app, admin_validator))) + ] + + def bodysize_hook(self, current_max_body_sizes, *args, **kwargs): + # max upload size of 1GB for the restore endpoint + return [("POST", r"/restore", 1024 * 1024 * 1024)] + + ##~~ CLI hook + + def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs): + import click + + @click.command("backup") + @click.option("--exclude", multiple=True, + help="Identifiers of data folders to exclude, e.g. 'uploads' to exclude uploads or " + "'timelapse' to exclude timelapses.") + def backup_command(exclude): + """ + Creates a new backup. + """ + + backup_file = build_backup_filename() + settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings) + + datafolder = os.path.join(settings.getBaseFolder("data"), "backup") + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + + click.echo("Creating backup at {}, please wait...".format(backup_file)) + self._create_backup(backup_file, + exclude=exclude, + settings=settings, + plugin_manager=cli_group.plugin_manager, + datafolder=datafolder) + click.echo("Done.") + + @click.command("restore") + @click.argument("path") + def restore_command(path): + """ + Restores an existing backup from the backup zip provided as argument. + + OctoPrint does not need to run for this to proceed. + """ + settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings) + plugin_manager = cli_group.plugin_manager + + datafolder = os.path.join(settings.getBaseFolder("data"), "backup") + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + + # register plugin manager plugin setting overlays + plugin_info = plugin_manager.get_plugin_info("pluginmanager") + if plugin_info and plugin_info.implementation: + default_settings_overlay = dict(plugins=dict()) + default_settings_overlay["plugins"]["pluginmanager"] = plugin_info.implementation.get_settings_defaults() + settings.add_overlay(default_settings_overlay, at_end=True) + + if not os.path.isabs(path): + datafolder = os.path.join(settings.getBaseFolder("data"), "backup") + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + path = os.path.join(datafolder, path) + + if not os.path.exists(path): + click.echo("Backup {} does not exist".format(path), err=True) + sys.exit(-1) + + archive = tempfile.NamedTemporaryFile(delete=False) + archive.close() + shutil.copy(path, archive.name) + path = archive.name + + def on_install_plugins(plugins): + if not plugins: + return + + force_user = settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"]) + pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"]) + + def log(line): + click.echo("\t{}".format(line)) + + for plugin in plugins: + octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"]) + os_compatible = is_os_compatible(plugin["compatibility"]["os"]) + compatible = octoprint_compatible and os_compatible + if not compatible: + if not octoprint_compatible and not os_compatible: + click.echo("Cannot install plugin {}, it is incompatible to this version of " + "OctoPrint and the underlying operating system".format(plugin["id"])) + elif not octoprint_compatible: + click.echo("Cannot install plugin {}, it is incompatible to this version of " + "OctoPrint".format(plugin["id"])) + elif not os_compatible: + click.echo("Cannot install plugin {}, it is incompatible to the underlying " + "operating system".format(plugin["id"])) + continue + + click.echo("Installing plugin {}".format(plugin["id"])) + self.__class__._install_plugin(plugin, + force_user=force_user, + pip_args=pip_args, + on_log=log) + + def on_report_unknown_plugins(plugins): + if not plugins: + return + + click.echo("The following plugins were not found in the plugin repository. You'll need to install them manually.") + for plugin in plugins: + click.echo("\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?")) + + def on_log_progress(line): + click.echo(line) + + def on_log_error(line, exc_info=None): + click.echo(line, err=True) + + if exc_info is not None: + exc_type, exc_value, exc_tb = exc_info + output = traceback.format_exception(exc_type, exc_value, exc_tb) + for line in output: + click.echo(line.rstrip(), err=True) + + if self._restore_backup(path, + settings=settings, + plugin_manager=plugin_manager, + datafolder=datafolder, + on_install_plugins=on_install_plugins, + on_report_unknown_plugins=on_report_unknown_plugins, + on_log_progress=on_log_progress, + on_log_error=on_log_error, + on_invalid_backup=on_log_error): + click.echo("Restored from {}".format(path)) + else: + click.echo("Restoring from {} failed".format(path), err=True) + + return [backup_command, restore_command] + + ##~~ helpers + + def _get_backups(self): + backups = [] + for entry in scandir(self.get_plugin_data_folder()): + if is_hidden_path(entry.path): + continue + if not entry.is_file(): + continue + if not entry.name.endswith(".zip"): + continue + + backups.append(dict(name=entry.name, + date=entry.stat().st_mtime, + size=entry.stat().st_size, + url=flask.url_for("index") + "plugin/backup/download/" + entry.name)) + return backups + + def _get_unknown_plugins(self): + data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) + if os.path.exists(data_file): + try: + with io.open(data_file, mode='rb', encoding="utf-8") as f: + unknown_plugins = json.load(f) + + assert isinstance(unknown_plugins, list) + assert all(map(lambda x: isinstance(x, dict) and "key" in x and "name" in x and "url" in x, unknown_plugins)) + + installed_plugins = self._plugin_manager.plugins + unknown_plugins = list(filter(lambda x: x["key"] not in installed_plugins, unknown_plugins)) + if not unknown_plugins: + # no plugins left uninstalled, delete data file + try: + os.remove(data_file) + except Exception: + self._logger.exception("Error while deleting list of unknown plugins at {}".format(data_file)) + + return unknown_plugins + except Exception: + self._logger.exception("Error while reading list of unknown plugins from {}".format(data_file)) + try: + os.remove(data_file) + except Exception: + self._logger.exception("Error while deleting list of unknown plugins at {}".format(data_file)) + + return [] + + @classmethod + def _clean_dir_backup(cls, basedir, + on_log_progress=None): + basedir_backup = basedir + ".bck" + + if os.path.exists(basedir_backup): + def remove_bck(): + if callable(on_log_progress): + on_log_progress("Found config folder backup from prior restore, deleting it...") + shutil.rmtree(basedir_backup) + if callable(on_log_progress): + on_log_progress("... deleted.") + + thread = threading.Thread(target=remove_bck) + thread.daemon = True + thread.start() + + @classmethod + def _get_disk_size(cls, path, ignored=None): + if ignored is None: + ignored = [] + + if path in ignored: + return 0 + + total = 0 + for entry in scandir(path): + if entry.is_dir(): + total += cls._get_disk_size(entry.path, ignored=ignored) + elif entry.is_file(): + total += entry.stat().st_size + return total + + @classmethod + def _free_space(cls, path, size): + from psutil import disk_usage + return disk_usage(path).free > size + + @classmethod + def _get_plugin_repository_data(cls, url, logger=None): + if logger is None: + logger = logging.getLogger(__name__) + + try: + r = requests.get(url, timeout=30) + r.raise_for_status() + except Exception: + logger.exception("Error while fetching the plugin repository data from {}".format(url)) + return dict() + + from octoprint.plugins.pluginmanager import map_repository_entry + return dict((plugin["id"], plugin) for plugin in map(map_repository_entry, r.json())) + + @classmethod + def _install_plugin(cls, plugin, force_user=False, pip_args=None, on_log=None): + if pip_args is None: + pip_args = [] + + if on_log is None: + on_log = logging.getLogger(__name__).info + + # prepare pip caller + def log(prefix, *lines): + for line in lines: + on_log("{} {}".format(prefix, line.rstrip())) + + def log_call(*lines): + log(">", *lines) + + def log_stdout(*lines): + log("<", *lines) + + def log_stderr(*lines): + log("!", *lines) + + if cls._pip_caller is None: + cls._pip_caller = LocalPipCaller(force_user=force_user) + + cls._pip_caller.on_log_call = log_call + cls._pip_caller.on_log_stdout = log_stdout + cls._pip_caller.on_log_stderr = log_stderr + + # install plugin + pip = ["install", sarge.shell_quote(plugin["archive"]), '--no-cache-dir'] + + if plugin.get("follow_dependency_links"): + pip.append("--process-dependency-links") + + if force_user: + pip.append("--user") + + if pip_args: + pip += pip_args + + cls._pip_caller.execute(*pip) + + @classmethod + def _create_backup(cls, name, + exclude=None, + settings=None, + plugin_manager=None, + datafolder=None, + on_backup_start=None, + on_backup_done=None, + on_backup_error=None): + exclude_by_default = ("generated", "logs", "watched",) + + try: + if exclude is None: + exclude = [] + + configfile = settings._configfile + basedir = settings._basedir + + temporary_path = os.path.join(datafolder, ".{}".format(name)) + final_path = os.path.join(datafolder, name) + + own_folder = datafolder + defaults = [os.path.join(basedir, "config.yaml"),] + \ + [os.path.join(basedir, folder) for folder in default_settings["folder"].keys()] + + # check how much many bytes we are about to backup + size = os.stat(configfile).st_size + for folder in default_settings["folder"].keys(): + if folder in exclude or folder in exclude_by_default: + continue + size += cls._get_disk_size(settings.global_get_basefolder(folder), + ignored=[own_folder,]) + size += cls._get_disk_size(basedir, ignored=defaults + [own_folder,]) + + # since we can't know the compression ratio beforehand, we assume we need the same amount of space + if not cls._free_space(os.path.dirname(temporary_path), size): + raise InsufficientSpace() + + compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED + + if callable(on_backup_start): + on_backup_start(name, temporary_path, exclude) + + with zipfile.ZipFile(temporary_path, mode="w", compression=compression, allowZip64=True) as zip: + def add_to_zip(source, target, ignored=None): + if ignored is None: + ignored = [] + + if source in ignored: + return + + if os.path.isdir(source): + for entry in scandir(source): + add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored) + elif os.path.isfile(source): + zip.write(source, arcname=target) + + # add metadata + metadata = dict(version=get_octoprint_version_string(), + excludes=exclude) + zip.writestr("metadata.json", json.dumps(metadata)) + + # backup current config file + add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,]) + + # backup configured folder paths + for folder in default_settings["folder"].keys(): + if folder in exclude or folder in exclude_by_default: + continue + + add_to_zip(settings.global_get_basefolder(folder), + "basedir/" + folder.replace("_", "/"), + ignored=[own_folder,]) + + # backup anything else that might be lying around in our basedir + add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ]) + + # add list of installed plugins + plugins = [] + plugin_folder = settings.global_get_basefolder("plugins") + for key, plugin in plugin_manager.plugins.items(): + if plugin.bundled or (isinstance(plugin.origin, FolderOrigin) and plugin.origin.folder == plugin_folder): + # ignore anything bundled or from the plugins folder we already include in the backup + continue + + plugins.append(dict(key=plugin.key, + name=plugin.name, + url=plugin.url)) + + if len(plugins): + zip.writestr("plugin_list.json", json.dumps(plugins)) + + shutil.move(temporary_path, final_path) + + if callable(on_backup_done): + on_backup_done(name, final_path, exclude) + except Exception as exc: ## noqa: F841 + # TODO py3: use the exception, not sys.exc_info() + if callable(on_backup_error): + exc_info = sys.exc_info() + try: + on_backup_error(name, exc_info) + finally: + del exc_info + raise + + @classmethod + def _restore_backup(cls, path, + settings=None, + plugin_manager=None, + datafolder=None, + on_install_plugins=None, + on_report_unknown_plugins=None, + on_invalid_backup=None, + on_log_progress=None, + on_log_error=None, + on_restore_start=None, + on_restore_done=None, + on_restore_failed=None): + if not is_os_compatible(["!windows"]): + if callable(on_log_error): + on_log_error("Restore is not supported on this operating system") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + restart_command = settings.global_get(["server", "commands", "serverRestartCommand"]) + + basedir = settings._basedir + cls._clean_dir_backup(basedir, + on_log_progress=on_log_progress) + + plugin_repo = dict() + repo_url = settings.global_get(["plugins", "pluginmanager", "repository"]) + if repo_url: + plugin_repo = cls._get_plugin_repository_data(repo_url) + + if callable(on_restore_start): + on_restore_start(path) + + try: + + with zipfile.ZipFile(path, "r") as zip: + # read metadata + try: + metadata_zipinfo = zip.getinfo("metadata.json") + except KeyError: + if callable(on_invalid_backup): + on_invalid_backup("Not an OctoPrint backup, lacks metadata.json") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + metadata_bytes = zip.read(metadata_zipinfo) + metadata = json.loads(metadata_bytes) + + backup_version = get_comparable_version(metadata["version"], base=True) + if backup_version > get_octoprint_version(base=True): + if callable(on_invalid_backup): + on_invalid_backup("Backup is from a newer version of OctoPrint and cannot be applied") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + # unzip to temporary folder + temp = tempfile.mkdtemp() + try: + if callable(on_log_progress): + on_log_progress("Unpacking backup to {}...".format(temp)) + abstemp = os.path.abspath(temp) + for member in zip.infolist(): + abspath = os.path.abspath(os.path.join(temp, member.filename)) + if abspath.startswith(abstemp): + zip.extract(member, temp) + + # sanity check + configfile = os.path.join(temp, "basedir", "config.yaml") + if not os.path.exists(configfile): + if callable(on_invalid_backup): + on_invalid_backup("Backup lacks config.yaml") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + import yaml + + with io.open(configfile, "rt", encoding="utf-8") as f: + configdata = yaml.safe_load(f) + + if configdata.get("accessControl", dict()).get("enabled", True): + userfile = os.path.join(temp, "basedir", "users.yaml") + if not os.path.exists(userfile): + if callable(on_invalid_backup): + on_invalid_backup("Backup lacks users.yaml") + if callable(on_restore_failed): + on_restore_failed(path) + return False + + if callable(on_log_progress): + on_log_progress("Unpacked") + + # install available plugins + plugins = [] + plugin_list_file = os.path.join(temp, "plugin_list.json") + if os.path.exists(plugin_list_file): + with io.open(os.path.join(temp, "plugin_list.json"), 'rb') as f: + plugins = json.load(f) + + known_plugins = [] + unknown_plugins = [] + if plugins: + if plugin_repo: + for plugin in plugins: + if plugin["key"] in plugin_manager.plugins: + # already installed + continue + + if plugin["key"] in plugin_repo: + # not installed, can be installed from repository url + known_plugins.append(plugin_repo[plugin["key"]]) + else: + # not installed, not installable + unknown_plugins.append(plugin) + + else: + # no repo, all plugins are not installable + unknown_plugins = plugins + + if callable(on_log_progress): + if known_plugins: + on_log_progress("Known and installable plugins: {}".format(", ".join(map(lambda x: x["id"], known_plugins)))) + if unknown_plugins: + on_log_progress("Unknown plugins: {}".format(", ".join(map(lambda x: x["key"], unknown_plugins)))) + + if callable(on_install_plugins): + on_install_plugins(known_plugins) + + if callable(on_report_unknown_plugins): + on_report_unknown_plugins(unknown_plugins) + + # move config data + basedir_backup = basedir + ".bck" + basedir_extracted = os.path.join(temp, "basedir") + + if callable(on_log_progress): + on_log_progress("Renaming {} to {}...".format(basedir, basedir_backup)) + shutil.move(basedir, basedir_backup) + + try: + if callable(on_log_progress): + on_log_progress("Moving {} to {}...".format(basedir_extracted, basedir)) + shutil.move(basedir_extracted, basedir) + except Exception: + if callable(on_log_error): + on_log_error("Error while restoring config data", exc_info=sys.exc_info()) + on_log_error("Rolling back old config data") + + shutil.move(basedir_backup, basedir) + + if callable(on_restore_failed): + on_restore_failed(path) + return False + + if unknown_plugins: + if callable(on_log_progress): + on_log_progress("Writing info file about unknown plugins") + + if not os.path.isdir(datafolder): + os.makedirs(datafolder) + + unknown_plugins_path = os.path.join(datafolder, UNKNOWN_PLUGINS_FILE) + try: + with io.open(unknown_plugins_path, mode='wb') as f: + f.write(to_bytes(json.dumps(unknown_plugins))) + except Exception: + if callable(on_log_error): + on_log_error("Could not persist list of unknown plugins to {}".format(unknown_plugins_path), + exc_info = sys.exc_info()) + + finally: + if callable(on_log_progress): + on_log_progress("Removing temporary unpacked folder") + shutil.rmtree(temp) + + except Exception: + exc_info = sys.exc_info() + try: + if callable(on_log_error): + on_log_error("Error while running restore", exc_info=exc_info) + if callable(on_restore_failed): + on_restore_failed(path) + finally: + del exc_info + return False + + finally: + # remove zip + if callable(on_log_progress): + on_log_progress("Removing temporary zip") + os.remove(path) + + # restart server + if restart_command: + import sarge + + if callable(on_log_progress): + on_log_progress("Restarting...") + if callable(on_restore_done): + on_restore_done(path) + + try: + sarge.run(restart_command, async_=True) + except Exception: + if callable(on_log_error): + on_log_error("Error while restarting via command {}".format(restart_command), + exc_info=sys.exc_info()) + on_log_error("Please restart OctoPrint manually") + return False + + else: + if callable(on_restore_done): + on_restore_done(path) + + return True + + + def _send_client_message(self, message, payload=None): + if payload is None: + payload = dict() + payload["type"] = message + self._plugin_manager.send_plugin_message(self._identifier, payload) + + + +class InsufficientSpace(Exception): + pass + +__plugin_name__ = "Backup & Restore" +__plugin_author__ = "Gina Häußge" +__plugin_description__ = "Backup & restore your OctoPrint settings and data" +__plugin_disabling_discouraged__ = gettext("Without this plugin you will no longer be able to backup " + "& restore your OctoPrint settings and data.") +__plugin_license__ = "AGPLv3" +__plugin_implementation__ = BackupPlugin() +__plugin_hooks__ = { + "octoprint.server.http.routes": __plugin_implementation__.route_hook, + "octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook, + "octoprint.cli.commands": __plugin_implementation__.cli_commands_hook, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions +} diff --git a/src/octoprint/plugins/backup/static/clientjs/backup.js b/src/octoprint/plugins/backup/static/clientjs/backup.js new file mode 100644 index 000000000..5f2ee6e62 --- /dev/null +++ b/src/octoprint/plugins/backup/static/clientjs/backup.js @@ -0,0 +1,52 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintBackupClient = function(base) { + this.base = base; + this.url = this.base.getBlueprintUrl("backup"); + }; + + OctoPrintBackupClient.prototype.get = function(refresh, opts) { + return this.base.get(this.url, opts); + }; + + OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) { + exclude = exclude || []; + + var data = { + exclude: exclude + }; + + return this.base.postJson(this.url + "backup", data, opts); + }; + + OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) { + return this.base.delete(this.url + "backup/" + backup, opts); + }; + + OctoPrintBackupClient.prototype.restoreBackup = function(backup, opts) { + var data = { + path: backup + }; + + return this.base.postJson(this.url + "restore", data, opts); + }; + + OctoPrintBackupClient.prototype.restoreBackupFromUpload = function (file, data) { + data = data || {}; + + var filename = data.filename || undefined; + return this.base.upload(this.url + "restore", file, filename, data); + }; + + OctoPrintBackupClient.prototype.deleteUnknownPlugins = function (opts) { + return this.base.delete(this.url + "unknown_plugins", opts); + }; + + OctoPrintClient.registerPluginComponent("backup", OctoPrintBackupClient); + return OctoPrintBackupClient; +}); diff --git a/src/octoprint/plugins/backup/static/css/backup.css b/src/octoprint/plugins/backup/static/css/backup.css new file mode 100644 index 000000000..f3561ce93 --- /dev/null +++ b/src/octoprint/plugins/backup/static/css/backup.css @@ -0,0 +1 @@ +#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:75px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:#000}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox{text-align:center;width:10px}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox input[type=checkbox]{margin-top:0}#settings_plugin_backup_restoredialog_output .message{font-weight:700}#settings_plugin_backup_restoredialog_output .error{font-weight:700;color:#900}#settings_plugin_backup_restoredialog_output .stdout{color:#333}#settings_plugin_backup_restoredialog_output .stderr{color:#900}#settings_plugin_backup_restoredialog_output .call{color:#009} \ No newline at end of file diff --git a/src/octoprint/plugins/backup/static/js/backup.js b/src/octoprint/plugins/backup/static/js/backup.js new file mode 100644 index 000000000..26929ec57 --- /dev/null +++ b/src/octoprint/plugins/backup/static/js/backup.js @@ -0,0 +1,289 @@ +$(function() { + function BackupViewModel(parameters) { + var self = this; + + self.loginState = parameters[0]; + self.settings = parameters[1]; + + self.backups = new ItemListHelper( + "plugin.backup.backups", + { + "date": function (a, b) { + // sorts descending + if (a["date"] > b["date"]) return -1; + if (a["date"] < b["date"]) return 1; + return 0; + } + }, + { + }, + "date", + [], + [], + 10 + ); + + self.markedForBackupDeletion = ko.observableArray([]); + + self.excludeFromBackup = ko.observableArray([]); + self.backupInProgress = ko.observable(false); + self.restoreSupported = ko.observable(true); + + self.backupUploadButton = $("#settings-backup-upload"); + self.backupUploadData = undefined; + self.backupUploadButton.fileupload({ + dataType: "json", + maxNumberOfFiles: 1, + autoUpload: false, + headers: OctoPrint.getRequestHeaders(), + add: function(e, data) { + if (data.files.length === 0) { + // no files? ignore + return false; + } + + self.backupUploadName(data.files[0].name); + self.backupUploadData = data; + }, + done: function(e, data) { + self.backupUploadName(undefined); + self.backupUploadData = undefined; + } + }); + self.backupUploadName = ko.observable(); + self.restoreInProgress = ko.observable(false); + self.restoreTitle = ko.observable(); + self.restoreDialog = undefined; + self.restoreOutput = undefined; + self.unknownPlugins = ko.observableArray([]); + + self.loglines = ko.observableArray([]); + + self.requestData = function() { + OctoPrint.plugins.backup.get() + .done(self.fromResponse); + }; + + self.fromResponse = function(response) { + self.backups.updateItems(response.backups); + self.unknownPlugins(response.unknown_plugins); + self.restoreSupported(response.restore_supported); + }; + + self.createBackup = function() { + var excluded = self.excludeFromBackup(); + OctoPrint.plugins.backup.createBackup(excluded) + .done(function() { + self.excludeFromBackup([]); + }) + }; + + self.removeBackup = function(backup) { + var perform = function() { + OctoPrint.plugins.backup.deleteBackup(backup) + .done(function() { + self.requestData(); + }); + }; + showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: backup}), + perform); + }; + + self.restoreBackup = function(backup) { + if (!self.restoreSupported()) return; + + var perform = function() { + self.restoreInProgress(true); + self.loglines.removeAll(); + self.loglines.push({line: "Preparing to restore...", stream: "message"}); + self.loglines.push({line: " ", stream: "message"}); + self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true}); + + OctoPrint.plugins.backup.restoreBackup(backup); + }; + showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}), + perform); + }; + + self.performRestoreFromUpload = function() { + if (self.backupUploadData === undefined) return; + + var perform = function() { + self.restoreInProgress(true); + self.loglines.removeAll(); + self.loglines.push({line: "Uploading backup, this can take a while. Please wait...", stream: "message"}); + self.loglines.push({line: " ", stream: "message"}); + self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true}); + + self.backupUploadData.submit(); + }; + showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}), + perform); + }; + + self.deleteUnknownPluginRecord = function() { + var perform = function() { + OctoPrint.plugins.backup.deleteUnknownPlugins() + .done(function() { + self.requestData(); + }); + }; + showConfirmationDialog(gettext("You are about to delete the record of plugins unknown during the last restore."), + perform); + }; + + self.markFilesOnPage = function() { + self.markedForBackupDeletion(_.uniq(self.markedForBackupDeletion().concat(_.map(self.backups.paginatedItems(), "name")))); + }; + + self.markAllFiles = function() { + self.markedForBackupDeletion(_.map(self.backups.allItems, "name")); + }; + + self.clearMarkedFiles = function() { + self.markedForBackupDeletion.removeAll(); + }; + + self.removeMarkedFiles = function() { + var perform = function() { + self._bulkRemove(self.markedForBackupDeletion()) + .done(function() { + self.markedForBackupDeletion.removeAll(); + }); + }; + + showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d backups."), {count: self.markedForBackupDeletion().length}), + perform); + }; + + self.onStartup = function() { + self.restoreDialog = $("#settings_plugin_backup_restoredialog"); + self.restoreOutput = $("#settings_plugin_backup_restoredialog_output"); + }; + + self.onSettingsShown = function() { + self.requestData(); + }; + + self.onDataUpdaterPluginMessage = function(plugin, data) { + if (plugin !== "backup") return; + + if (data.type === "backup_done") { + self.requestData(); + self.backupInProgress(false); + new PNotify({ + title: gettext("Backup created successfully"), + type: "success" + }); + } else if (data.type === "backup_started") { + self.backupInProgress(true); + } else if (data.type === "backup_error") { + self.requestData(); + self.backupInProgress(false); + new PNotify({ + title: gettext("Creating the backup failed"), + text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult octoprint.log for details. Error: %(error)s"), {error:data.error}), + type: "error", + hide: false + }); + } else if (data.type === "restore_started") { + self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"}); + self.loglines.push({line: " ", stream: "message"}); + } else if (data.type === "restore_failed") { + self.loglines.push({line: " ", stream: "message"}); + self.loglines.push({line: gettext("Restore failed! Check the above output and octoprint.log for reasons as to why."), stream: "error"}); + self.restoreInProgress(false); + } else if (data.type === "restore_done") { + self.loglines.push({line: " ", stream: "message"}); + self.loglines.push({line: gettext("Restore successful! The server will now be restarted!"), stream: "message"}); + self.restoreInProgress(false); + } else if (data.type === "install_plugin") { + self.loglines.push({line: " ", stream: "message"}); + self.loglines.push({ + line: _.sprintf(gettext("Installing plugin \"%(plugin)s}\"..."), {plugin: data.plugin.name}), + stream: "message" + }); + } else if (data.type === "plugin_incompatible") { + self.loglines.push({line: " ", stream: "message"}); + self.loglines.push({ + line: _.sprintf(gettext("Cannot install plugin \"%(plugin)s\" due to it being incompatible to this OctoPrint version and/or underlying operating system"), {plugin: data.plugin.key}), + stream: "stderr" + }); + } else if (data.type === "unknown_plugins") { + if (data.plugins.length > 0) { + self.loglines.push({line: " ", stream: "message"}); + self.loglines.push({line: _.sprintf(gettext("There are %(count)d plugins you'll need to install manually since they aren't registered on the repository:"), {count: data.plugins.length}), stream: "message"}); + _.each(data.plugins, function(plugin) { + self.loglines.push({line: plugin.name + ": " + plugin.url, stream: "message"}); + }); + self.loglines.push({line: " ", stream: "message"}); + self.unknownPlugins(data.plugins); + } + } else if (data.type === "logline") { + self.loglines.push(self._preprocessLine({line: data.line, stream: data.stream})); + self._scrollRestoreOutputToEnd(); + } + }; + + self._scrollRestoreOutputToEnd = function() { + self.restoreOutput.scrollTop(self.restoreOutput[0].scrollHeight - self.restoreOutput.height()); + }; + + 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)) { + line.stream = "stdout"; + } + return line; + }; + + self._bulkRemove = function(files) { + var title, message, handler; + + title = gettext("Deleting backups"); + message = _.sprintf(gettext("Deleting %(count)d backups..."), {count: files.length}); + handler = function(filename) { + return OctoPrint.plugins.backup.deleteBackup(filename) + .done(function() { + deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true); + }) + .fail(function(jqXHR) { + var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename}); + var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText}); + deferred.notify(short, long, false); + }); + }; + + var deferred = $.Deferred(); + + var promise = deferred.promise(); + + var options = { + title: title, + message: message, + max: files.length, + output: true + }; + showProgressModal(options, promise); + + var requests = []; + _.each(files, function(filename) { + var request = handler(filename); + requests.push(request) + }); + $.when.apply($, _.map(requests, wrapPromiseWithAlways)) + .done(function() { + deferred.resolve(); + self.requestData(); + }); + + return promise; + }; + } + + OCTOPRINT_VIEWMODELS.push({ + construct: BackupViewModel, + dependencies: ["loginStateViewModel", "settingsViewModel"], + elements: ["#settings_plugin_backup"] + }); +}); diff --git a/src/octoprint/plugins/backup/static/less/backup.less b/src/octoprint/plugins/backup/static/less/backup.less new file mode 100644 index 000000000..6f90681ff --- /dev/null +++ b/src/octoprint/plugins/backup/static/less/backup.less @@ -0,0 +1,52 @@ +#settings_plugin_backup_backup_table { + .settings_plugin_backup_name { + } + .settings_plugin_backup_actions { + width: 75px; + text-align: center; + + a { + color: black; + } + } + .settings_plugin_backup_date { + width: 200px; + text-align: right; + } + .settings_plugin_backup_size { + width: 100px; + text-align: right; + } + + .settings_plugin_backup_checkbox { + text-align: center; + width: 10px; + + input[type="checkbox"] { + margin-top: 0; + } + } +} + +#settings_plugin_backup_restoredialog_output { + .message { + font-weight: bold; + } + + .error { + font-weight: bold; + color: #990000; + } + + .stdout { + color: #333333; + } + + .stderr { + color: #990000; + } + + .call { + color: #000099; + } +} diff --git a/src/octoprint/plugins/backup/templates/backup_settings.jinja2 b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 new file mode 100644 index 000000000..e9546adb2 --- /dev/null +++ b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 @@ -0,0 +1,135 @@ +
+ {% trans %} + Some plugins during the last restore could not be identified and hence not automatically installed. + Please install them manually, they are listed below including their stated homepages: + {% endtrans %} +
    +
  • :
  • +
+ {{ _('Delete record of unknown plugins') }} +
+ + +

{{ _('Existing backups') }}

+ +
+

{{ _('There are no backups. Maybe create one below?') }}

+
+
+

{{ _('These are the backups of your settings and files that already exist on this OctoPrint instance. You may delete, download or restore them.') }}

+ + + + + + + + + + + + + + + + + + + + + +
{{ _('Name') }}{{ _('Date') }}{{ _('Size') }}{{ _('Action') }}
 |  | 
+ +
+ +

{{ _('Create backup') }}

+ +

{{ _('Create a new backup of the current state.') }}

+ +
+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+ +
+

{{ _('Restore from uploaded backup') }}

+ +

{{ _('Restore settings & files from an uploaded backup archive.') }}

+ +
+
+ +
+
+ + {{ _('Browse...') }} + + + +
+
+
+ +
+
+ +
+
+
+
+ +
+ {{ _('Please note that the operating system that this OctoPrint server is running on does not support automatically restoring backups. You will have to restore your backups manually for now.', url='https://faq.octoprint.org/manual-restore') }} +
+ + diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index 2b817d541..64047f5ff 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/src/octoprint/plugins/corewizard/subwizards.py b/src/octoprint/plugins/corewizard/subwizards.py index 550b701a2..97244ee39 100644 --- a/src/octoprint/plugins/corewizard/subwizards.py +++ b/src/octoprint/plugins/corewizard/subwizards.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -9,7 +9,8 @@ import octoprint.plugin import sys import inspect from flask_babel import gettext - +from octoprint.access import ADMIN_GROUP, USER_GROUP +from octoprint.util import to_native_str # noinspection PyUnresolvedReferences,PyMethodMayBeStatic class ServerCommandsSubwizard(object): @@ -55,7 +56,7 @@ class AclSubwizard(object): return True def _is_acl_wizard_required(self): - return self._user_manager.enabled and not self._user_manager.hasBeenCustomized() + return self._user_manager.enabled and not self._user_manager.has_been_customized() def _get_acl_wizard_details(self): return dict(required=self._is_acl_wizard_required()) @@ -71,7 +72,7 @@ class AclSubwizard(object): 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(): + if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.has_been_customized(): abort(404) data = request.get_json() @@ -79,19 +80,16 @@ class AclSubwizard(object): 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"]: + "user" in data and "pass1" in data and \ + "pass2" in data 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: + + self._user_manager.add_user(data["user"], data["pass1"], True, [], [USER_GROUP, ADMIN_GROUP], overwrite=True) + elif "ac" in data 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 @@ -148,7 +146,7 @@ class PrinterProfileSubwizard(object): return gettext("Default Printer Profile") -Subwizards = type("Subwizwards", +Subwizards = type(to_native_str("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_acl_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_acl_wizard.jinja2 index 58cd4bfa7..823e65212 100644 --- a/src/octoprint/plugins/corewizard/templates/corewizard_acl_wizard.jinja2 +++ b/src/octoprint/plugins/corewizard/templates/corewizard_acl_wizard.jinja2 @@ -1,14 +1,22 @@

{{ _('Access Control') }}

-{% trans %}

+{% trans safe_remote_url='https://octoprint.org/blog/2018/09/03/safe-remote-access/' %}

Please read the following, it is very important for your printer's health!

OctoPrint by default ships with Access Control enabled, meaning you won't be able to do anything with the printer unless you login first as a configured user. This is to prevent strangers - possibly with - malicious intent - to gain access to your printer via the internet or another untrustworthy network + malicious intent - to gain access to your printer via an untrustworthy network and using it in such a way that it is damaged or worse (i.e. causes a fire).

+

+ If you plan on accessing OctoPrint remotely over the internet, you should not only rely on the built-in + Access Control mechanisms however - + take additional precautions. + Your OctoPrint enabled printer is a critical home appliance you really should not give anyone who happens to be + connected to the internet access to - even read-only! An instance available publicly on the internet + will be found, and people will try to break it open. +

It looks like you haven't configured access control yet. Please set up a username and password for the initial administrator account who will have full access to both the printer and OctoPrint's settings, then click @@ -36,12 +44,12 @@ {% trans %}

- Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't + Note: In case that your OctoPrint installation is only accessible from within a trustworthy local network and you don't need Access Control for other reasons, you may alternatively disable Access Control. You should only do this if you are absolutely certain that only people you know and trust will be able to connect to it.

- Do NOT underestimate the risk of an unsecured access from the internet to your printer! + Do NOT underestimate the risk of access from the internet to your printer and OctoPrint instance!

{% endtrans %}
diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py deleted file mode 100644 index 79bcd31c9..000000000 --- a/src/octoprint/plugins/cura/__init__.py +++ /dev/null @@ -1,532 +0,0 @@ -# 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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" - -import logging -import logging.handlers -import os -import flask -import math - -import octoprint.plugin -import octoprint.util -import octoprint.slicing -import octoprint.settings - -from octoprint.util.paths import normalize as normalize_path -from octoprint.util import to_unicode - -from .profile import Profile -from .profile import GcodeFlavors -from .profile import parse_gcode_flavor - -class CuraPlugin(octoprint.plugin.SlicerPlugin, - octoprint.plugin.SettingsPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.BlueprintPlugin, - octoprint.plugin.StartupPlugin, - octoprint.plugin.WizardPlugin): - - # noinspection PyMissingConstructor - def __init__(self): - self._logger = logging.getLogger("octoprint.plugins.cura") - self._cura_logger = logging.getLogger("octoprint.plugins.cura.engine") - - # setup job tracking across threads - import threading - self._slicing_commands = dict() - self._cancelled_jobs = [] - self._job_mutex = threading.Lock() - - def _is_engine_configured(self, cura_engine=None): - if cura_engine is None: - cura_engine = normalize_path(self._settings.get(["cura_engine"])) - return cura_engine is not None and os.path.isfile(cura_engine) and os.access(cura_engine, os.X_OK) - - def _is_profile_available(self): - return bool(self._slicing_manager.all_profiles("cura", require_configured=False)) - - ##~~ TemplatePlugin API - - def get_template_vars(self): - return dict( - homepage=__plugin_url__ - ) - - ##~~ WizardPlugin API - - def is_wizard_required(self): - return not self._is_engine_configured() or not self._is_profile_available() - - def get_wizard_details(self): - return dict( - engine=self._is_engine_configured(), - profile=self._is_profile_available() - ) - - ##~~ StartupPlugin API - - def on_startup(self, host, port): - # setup our custom logger - from octoprint.logging.handlers import CleaningTimedRotatingFileHandler - cura_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="engine"), when="D", backupCount=3) - cura_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) - cura_logging_handler.setLevel(logging.DEBUG) - - self._cura_logger.addHandler(cura_logging_handler) - self._cura_logger.setLevel(logging.DEBUG if 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"]) - def import_cura_profile(self): - import datetime - - input_name = "file" - input_upload_name = input_name + "." + self._settings.global_get(["server", "uploads", "nameSuffix"]) - input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"]) - - if input_upload_name in flask.request.values and input_upload_path in flask.request.values: - filename = flask.request.values[input_upload_name] - try: - profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path]) - except Exception as e: - 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(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(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 = 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 - - # overrides - from octoprint.server.api import valid_boolean_trues - if "name" in flask.request.values: - profile_name = flask.request.values["name"] - if "displayName" in flask.request.values: - profile_display_name = flask.request.values["displayName"] - if "description" in flask.request.values: - profile_description = flask.request.values["description"] - if "allowOverwrite" in flask.request.values: - profile_allow_overwrite = flask.request.values["allowOverwrite"] in valid_boolean_trues - if "default" in flask.request.values: - profile_make_default = flask.request.values["default"] in valid_boolean_trues - - try: - self._slicing_manager.save_profile("cura", - profile_name, - profile_dict, - allow_overwrite=profile_allow_overwrite, - display_name=profile_display_name, - description=profile_description) - except octoprint.slicing.ProfileAlreadyExists: - self._logger.warn(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(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), - name=profile_name, - displayName=profile_display_name, - description=profile_description - ) - r = flask.make_response(flask.jsonify(result), 201) - r.headers["Location"] = result["resource"] - return r - - ##~~ AssetPlugin API - - def get_assets(self): - return { - "js": ["js/cura.js"], - "less": ["less/cura.less"], - "css": ["css/cura.css"] - } - - ##~~ 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) - else: - self._cura_logger.setLevel(logging.CRITICAL) - - def get_settings_defaults(self): - return dict( - cura_engine=None, - default_profile=None, - debug_logging=False - ) - - ##~~ SlicerPlugin API - - def is_slicer_configured(self): - cura_engine = normalize_path(self._settings.get(["cura_engine"])) - return self._is_engine_configured(cura_engine=cura_engine) - - def get_slicer_properties(self): - return dict( - type="cura", - name="CuraEngine", - same_device=True, - progress_report=True, - source_file_types=["stl"], - destination_extensions=["gco", "gcode", "g"] - ) - - def get_slicer_default_profile(self): - path = self._settings.get(["default_profile"]) - if not path: - path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "profiles", "default.profile.yaml") - return self.get_slicer_profile(path) - - def get_slicer_profile(self, path): - profile_dict = self._load_profile(path) - - display_name = None - description = None - if "_display_name" in profile_dict: - display_name = profile_dict["_display_name"] - del profile_dict["_display_name"] - if "_description" in profile_dict: - description = profile_dict["_description"] - del profile_dict["_description"] - - properties = self.get_slicer_properties() - return octoprint.slicing.SlicingProfile(properties["type"], "unknown", profile_dict, display_name=display_name, description=description) - - def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None): - new_profile = Profile.merge_profile(profile.data, overrides=overrides) - - if profile.display_name is not None: - new_profile["_display_name"] = profile.display_name - if profile.description is not None: - new_profile["_description"] = profile.description - - self._save_profile(path, new_profile, allow_overwrite=allow_overwrite) - - 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): - try: - with self._job_mutex: - if not profile_path: - profile_path = self._settings.get(["default_profile"]) - if not machinecode_path: - path, _ = os.path.splitext(model_path) - machinecode_path = path + ".gco" - - if position and isinstance(position, dict) and "x" in position and "y" in position: - pos_x = position["x"] - pos_y = position["y"] - else: - pos_x = None - pos_y = None - - if on_progress: - if not on_progress_args: - on_progress_args = () - if not on_progress_kwargs: - on_progress_kwargs = dict() - - self._cura_logger.info(u"### Slicing {} to {} using profile stored at {}" - .format(to_unicode(model_path, errors="replace"), - to_unicode(machinecode_path, errors="replace"), - to_unicode(profile_path, errors="replace"))) - - executable = normalize_path(self._settings.get(["cura_engine"])) - if not executable: - return False, u"Path to CuraEngine is not configured " - - working_dir = os.path.dirname(executable) - - slicing_profile = Profile(self._load_profile(profile_path), printer_profile, pos_x, pos_y) - - # NOTE: We can assume an extruder count of 1 here since the only way we currently - # support dual extrusion in this implementation is by using the second extruder for support (which - # the engine conversion will automatically detect and adapt accordingly). - # - # We currently do only support STL files as sliceables, which by default can only contain one mesh, - # so no risk of having to slice multi-objects at the moment, which would necessitate a full analysis - # of the objects to slice to determine amount of needed extruders to use here. If we ever decide to - # also support dual extrusion slicing (including composition from multiple STLs or support for OBJ or - # AMF files and the like), this code needs to be adapted! - # - # The extruder count is needed to decide which start/end gcode will be used from the Cura profile. - # Stock Cura implementation counts the number of objects in the scene for this (and also takes a look - # at the support usage, like the engine conversion here does). We only ever have one object. - engine_settings = self._convert_to_engine(profile_path, printer_profile, - pos_x=pos_x, pos_y=pos_y, - used_extruders=1) - - # Start building the argument list for the CuraEngine command execution - args = [executable, '-v', '-p'] - - # Add the settings (sorted alphabetically) to the command - for k, v in sorted(engine_settings.items(), key=lambda s: s[0]): - args += ["-s", "%s=%s" % (k, str(v))] - args += ["-o", machinecode_path, model_path] - - self._logger.info(u"Running {!r} in {}".format(u" ".join(map(lambda x: to_unicode(x, errors="replace"), - args)), - working_dir)) - - import sarge - p = sarge.run(args, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture()) - p.wait_events() - self._slicing_commands[machinecode_path] = p.commands[0] - - try: - layer_count = None - step_factor = dict( - inset=0, - skin=1, - export=2 - ) - analysis = None - while p.returncode is None: - line = p.stderr.readline(timeout=0.5) - if not line: - p.commands[0].poll() - continue - - line = to_unicode(line, errors="replace") - self._cura_logger.debug(line.strip()) - - if on_progress is not None: - # The Cura slicing process has three individual steps, each consisting of substeps: - # - # - inset - # - skin - # - export - # - # So each layer will be processed three times, once for each step, resulting in a total amount of - # substeps of 3 * . - # - # The CuraEngine reports the calculated layer count and the continuous progress on stderr. - # The layer count gets reported right at the beginning in a line of the format: - # - # Layer count: - # - # The individual progress per each of the three steps gets reported on stderr in a line of - # the format: - # - # Progress::: - # - # Thus, for determining the overall progress the following formula applies: - # - # progress = * + / * 3 - # - # with being 0 for "inset", 1 for "skin" and 2 for "export". - - if line.startswith(u"Layer count:") and layer_count is None: - try: - layer_count = float(line[len(u"Layer count:"):].strip()) - except: - pass - - elif line.startswith(u"Progress:"): - split_line = line[len(u"Progress:"):].strip().split(":") - if len(split_line) == 3: - step, current_layer, _ = split_line - try: - current_layer = float(current_layer) - except: - pass - else: - if not step in step_factor: - continue - on_progress_kwargs["_progress"] = (step_factor[step] * layer_count + current_layer) / (layer_count * 3) - on_progress(*on_progress_args, **on_progress_kwargs) - - elif line.startswith(u"Print time:"): - try: - print_time = int(line[len(u"Print time:"):].strip()) - if analysis is None: - analysis = dict() - analysis["estimatedPrintTime"] = print_time - except: - pass - - # Get the filament usage - - elif line.startswith(u"Filament:") or line.startswith(u"Filament2:"): - if line.startswith(u"Filament:"): - filament_str = line[len(u"Filament:"):].strip() - tool_key = "tool0" - else: - filament_str = line[len(u"Filament2:"):].strip() - tool_key = "tool1" - - try: - filament = int(filament_str) - - if analysis is None: - analysis = dict() - if not "filament" in analysis: - analysis["filament"] = dict() - if not tool_key in analysis["filament"]: - analysis["filament"][tool_key] = dict() - - if slicing_profile.get_float("filament_diameter") is not None: - if slicing_profile.get("gcode_flavor") == GcodeFlavors.ULTIGCODE or slicing_profile.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME: - analysis["filament"][tool_key] = _get_usage_from_volume(filament, slicing_profile.get_float("filament_diameter")) - else: - analysis["filament"][tool_key] = _get_usage_from_length(filament, slicing_profile.get_float("filament_diameter")) - - except: - pass - finally: - p.close() - - with self._job_mutex: - if machinecode_path in self._cancelled_jobs: - self._cura_logger.info(u"### Cancelled") - raise octoprint.slicing.SlicingCancelled() - - self._cura_logger.info(u"### Finished, returncode %d" % p.returncode) - if p.returncode == 0: - return True, dict(analysis=analysis) - else: - self._logger.warn(u"Could not slice via Cura, got return code %r" % p.returncode) - return False, "Got returncode %r" % p.returncode - - except octoprint.slicing.SlicingCancelled as e: - raise e - except: - self._logger.exception(u"Could not slice via Cura, got an unknown error") - return False, "Unknown error, please consult the log file" - - finally: - with self._job_mutex: - if machinecode_path in self._cancelled_jobs: - self._cancelled_jobs.remove(machinecode_path) - if machinecode_path in self._slicing_commands: - del self._slicing_commands[machinecode_path] - - self._cura_logger.info("-" * 40) - - def cancel_slicing(self, machinecode_path): - with self._job_mutex: - if machinecode_path in self._slicing_commands: - self._cancelled_jobs.append(machinecode_path) - command = self._slicing_commands[machinecode_path] - if command is not None: - command.terminate() - self._logger.info(u"Cancelled slicing of {}" - .format(to_unicode(machinecode_path, errors="replace"))) - - def _load_profile(self, path): - import yaml - profile_dict = dict() - with open(path, "r") as f: - try: - profile_dict = yaml.safe_load(f) - except: - 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"]) - self._save_profile(path, profile_dict) - - return profile_dict - - def _save_profile(self, path, profile, allow_overwrite=True): - import yaml - with octoprint.util.atomic_write(path, "wb", max_permissions=0o666) as f: - yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True) - - def _convert_to_engine(self, profile_path, printer_profile, pos_x=None, pos_y=None, used_extruders=1): - profile = Profile(self._load_profile(profile_path), printer_profile, pos_x, pos_y) - return profile.convert_to_engine(used_extruders=used_extruders) - -def _sanitize_name(name): - if name is None: - return None - - if "/" in name or "\\" in name: - raise ValueError(u"name must not contain / or \\") - - import string - valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits) - sanitized_name = ''.join(c for c in name if c in valid_chars) - sanitized_name = sanitized_name.replace(" ", "_") - return sanitized_name.lower() - -def _get_usage_from_volume(filament_volume, filament_diameter): - - # filament_volume is expressed in mm^3 - # usage["volume"] is in cm^3 and usage["length"] is in mm - - usage = dict() - usage["volume"] = filament_volume / 1000.0 - - radius_in_mm = filament_diameter / 2.0 - usage["length"] = filament_volume / (math.pi * radius_in_mm * radius_in_mm) - - return usage - -def _get_usage_from_length(filament_length, filament_diameter): - - # filament_length is expressed in mm - # usage["volume"] is in cm^3 and usage["length"] is in mm - - usage = dict() - usage["length"] = filament_length - - radius_in_cm = (filament_diameter / 10.0) / 2.0 - length_in_cm = filament_length / 10.0 - usage["volume"] = length_in_cm * math.pi * radius_in_cm * radius_in_cm - - return usage - - -__plugin_name__ = "CuraEngine (<= 15.04)" -__plugin_author__ = "Gina Häußge" -__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/cura.html" -__plugin_description__ = "Adds support for slicing via CuraEngine versions up to and including version 15.04 from within OctoPrint" -__plugin_license__ = "AGPLv3" -__plugin_implementation__ = CuraPlugin() - - - diff --git a/src/octoprint/plugins/cura/profile.py b/src/octoprint/plugins/cura/profile.py deleted file mode 100644 index 7b74fcdde..000000000 --- a/src/octoprint/plugins/cura/profile.py +++ /dev/null @@ -1,1032 +0,0 @@ -# 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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" - - -import re - -# noinspection PyCompatibility -from builtins import range -# noinspection PyCompatibility -from past.builtins import basestring - -class SupportLocationTypes(object): - NONE = "none" - TOUCHING_BUILDPLATE = "buildplate" - EVERYWHERE = "everywhere" - -class SupportDualTypes(object): - BOTH = "both" - FIRST = "first" - SECOND = "second" - -class SupportTypes(object): - GRID = "grid" - LINES = "lines" - -class PlatformAdhesionTypes(object): - NONE = "none" - BRIM = "brim" - RAFT = "raft" - -class MachineShapeTypes(object): - SQUARE = "square" - CIRCULAR = "circular" - -class RetractionCombingTypes(object): - OFF = "off" - ALL = "all" - NO_SKIN = "no skin" - -class GcodeFlavors(object): - REPRAP = (0, "reprap") - ULTIGCODE = (1, "ultigcode") - MAKERBOT = (2, "makerbot") - BFB = (3, "bfb") - MACH3 = (4, "mach3") - REPRAP_VOLUME = (5, "reprap_volume") - - -defaults = dict( - layer_height=0.1, - wall_thickness=0.8, - solid_layer_thickness=0.6, - print_temperature=[220, 0, 0, 0], - print_bed_temperature=0, - platform_adhesion=PlatformAdhesionTypes.NONE, - filament_diameter=[2.85, 0, 0, 0], - filament_flow=100.0, - bottom_thickness=0.3, - first_layer_width_factor=100.0, - object_sink=0.0, - - fill_density=20, - solid_top=True, - solid_bottom=True, - fill_overlap=15, - perimeter_before_infill=False, - - # speeds - print_speed=50.0, - travel_speed=150.0, - bottom_layer_speed=20.0, - infill_speed=0.0, - solidarea_speed=0.0, - outer_shell_speed=0.0, - inner_shell_speed=0.0, - - # dual extrusion - overlap_dual=0.15, - wipe_tower=False, - wipe_tower_volume=15, - ooze_shield=False, - - # retraction - retraction_enable=True, - retraction_speed=40.0, - retraction_amount=4.5, - retraction_dual_amount=16.5, - retraction_min_travel=1.5, - retraction_combing=True, - retraction_minimal_extrusion=0.02, - retraction_hop=0.0, - - # cooling - cool_min_layer_time=5, - fan_enabled=True, - fan_full_height=0.5, - fan_speed=100, - fan_speed_max=100, - cool_min_feedrate=10, - cool_head_lift=False, - - # support - support=SupportLocationTypes.NONE, - support_type=SupportTypes.GRID, - support_angle=60.0, - support_fill_rate=15, - support_xy_distance=0.7, - support_z_distance=0.15, - support_dual_extrusion=SupportDualTypes.BOTH, - - # platform adhesion - skirt_line_count=1, - skirt_gap=3.0, - skirt_minimal_length=150.0, - brim_line_count=20, - raft_margin=5.0, - raft_line_spacing=3.0, - raft_base_thickness=0.3, - raft_base_linewidth=1.0, - raft_interface_thickness=0.27, - raft_interface_linewidth=0.4, - raft_airgap_all=0.0, - raft_airgap=0.22, - raft_surface_layers=2, - raft_surface_thickness=0.27, - raft_surface_linewidth=0.4, - - # repairing - fix_horrible_union_all_type_a=True, - fix_horrible_union_all_type_b=False, - fix_horrible_use_open_bits=False, - fix_horrible_extensive_stitching=False, - - # extras - spiralize=False, - follow_surface=False, - - machine_width=205, - machine_depth=205, - machine_center_is_zero=False, - has_heated_bed=False, - gcode_flavor=GcodeFlavors.REPRAP, - extruder_amount=1, - steps_per_e=0, - start_gcode=[ - # 1 extruder - """;Sliced at: {day} {date} {time} -;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} -;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line -;M109 S{print_temperature} ;Uncomment to add your own temperature line -G21 ;metric values -G90 ;absolute positioning -M82 ;set extruder to absolute mode -M107 ;start with the fan off - -G28 X0 Y0 ;move X/Y to min endstops -G28 Z0 ;move Z to min endstops - -G1 Z15.0 F{travel_speed} ;move the platform down 15mm - -G92 E0 ;zero the extruded length -G1 F200 E3 ;extrude 3mm of feed stock -G92 E0 ;zero the extruded length again -G1 F{travel_speed} -;Put printing message on LCD screen -M117 Printing... -""", - # 2 extruders - """;Sliced at: {day} {date} {time} -;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} -;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line -;M104 S{print_temperature} ;Uncomment to add your own temperature line -;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line -;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line -G21 ;metric values -G90 ;absolute positioning -M107 ;start with the fan off - -G28 X0 Y0 ;move X/Y to min endstops -G28 Z0 ;move Z to min endstops - -G1 Z15.0 F{travel_speed} ;move the platform down 15mm - -T1 ;Switch to the 2nd extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F200 E-{retraction_dual_amount} - -T0 ;Switch to the first extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F{travel_speed} -;Put printing message on LCD screen -M117 Printing... -""", - # 3 extruders - """;Sliced at: {day} {date} {time} -;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} -;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line -;M104 S{print_temperature} ;Uncomment to add your own temperature line -;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line -;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line -G21 ;metric values -G90 ;absolute positioning -M107 ;start with the fan off - -G28 X0 Y0 ;move X/Y to min endstops -G28 Z0 ;move Z to min endstops - -G1 Z15.0 F{travel_speed} ;move the platform down 15mm - -T2 ;Switch to the 2nd extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F200 E-{retraction_dual_amount} - -T1 ;Switch to the 2nd extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F200 E-{retraction_dual_amount} - -T0 ;Switch to the first extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F{travel_speed} -;Put printing message on LCD screen -M117 Printing... -""", - # 4 extruders - """;Sliced at: {day} {date} {time} -;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} -;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line -;M104 S{print_temperature} ;Uncomment to add your own temperature line -;M109 T2 S{print_temperature2} ;Uncomment to add your own temperature line -;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line -;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line -G21 ;metric values -G90 ;absolute positioning -M107 ;start with the fan off - -G28 X0 Y0 ;move X/Y to min endstops -G28 Z0 ;move Z to min endstops - -G1 Z15.0 F{travel_speed} ;move the platform down 15mm - -T3 ;Switch to the 4th extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F200 E-{retraction_dual_amount} - -T2 ;Switch to the 3th extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F200 E-{retraction_dual_amount} - -T1 ;Switch to the 2nd extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F200 E-{retraction_dual_amount} - -T0 ;Switch to the first extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F{travel_speed} -;Put printing message on LCD screen -M117 Printing... -""" - ], - end_gcode=[ - # 1 extruder - """;End GCode -M104 S0 ;extruder heater off -M140 S0 ;heated bed heater off (if you have it) - -G91 ;relative positioning -G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure -G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more -G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way - -M84 ;steppers off -G90 ;absolute positioning -;{profile_string} -""", - # 2 extruders - """;End GCode -M104 T0 S0 ;extruder heater off -M104 T1 S0 ;extruder heater off -M140 S0 ;heated bed heater off (if you have it) - -G91 ;relative positioning -G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure -G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more -G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way - -M84 ;steppers off -G90 ;absolute positioning -;{profile_string} -""", - # 3 extruders - """;End GCode -M104 T0 S0 ;extruder heater off -M104 T1 S0 ;extruder heater off -M104 T2 S0 ;extruder heater off -M140 S0 ;heated bed heater off (if you have it) - -G91 ;relative positioning -G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure -G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more -G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way - -M84 ;steppers off -G90 ;absolute positioning -;{profile_string} -""", - # 4 extruders - """;End GCode -M104 T0 S0 ;extruder heater off -M104 T1 S0 ;extruder heater off -M104 T2 S0 ;extruder heater off -M104 T3 S0 ;extruder heater off -M140 S0 ;heated bed heater off (if you have it) - -G91 ;relative positioning -G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure -G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more -G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way - -M84 ;steppers off -G90 ;absolute positioning -;{profile_string} -""" - ], - preSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders. -;This code is added before the T(n) -""", - postSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders. -;This code is added after the T(n) -""" -) - - -class Profile(object): - - regex_extruder_offset = re.compile("extruder_offset_([xy])(\d)") - regex_filament_diameter = re.compile("filament_diameter(\d?)") - regex_print_temperature = re.compile("print_temperature(\d?)") - regex_strip_comments = re.compile(";.*$", flags=re.MULTILINE) - - @classmethod - def from_cura_ini(cls, path): - import logging - logger = logging.getLogger("octoprint.plugin.cura.profile") - - import os - if not os.path.exists(path) or not os.path.isfile(path): - logger.warn("Path {path} does not exist or is not a file, cannot import".format(**locals())) - return None - - import ConfigParser - config = ConfigParser.ConfigParser() - try: - config.read(path) - except: - logger.exception("Error while reading profile INI file from {path}".format(**locals())) - return None - - arrayified_options = ["print_temperature", "filament_diameter", "start.gcode", "end.gcode"] - translated_options = dict( - inset0_speed="outer_shell_speed", - insetx_speed="inner_shell_speed", - layer0_width_factor="first_layer_width_factor", - simple_mode="follow_surface", - ) - translated_options["start.gcode"] = "start_gcode" - translated_options["end.gcode"] = "end_gcode" - value_conversions = dict( - platform_adhesion={ - "None": PlatformAdhesionTypes.NONE, - "Brim": PlatformAdhesionTypes.BRIM, - "Raft": PlatformAdhesionTypes.RAFT - }, - support={ - "None": SupportLocationTypes.NONE, - "Touching buildplate": SupportLocationTypes.TOUCHING_BUILDPLATE, - "Everywhere": SupportLocationTypes.EVERYWHERE - }, - support_type={ - "Lines": SupportTypes.LINES, - "Grid": SupportTypes.GRID - }, - support_dual_extrusion={ - "Both": SupportDualTypes.BOTH, - "First extruder": SupportDualTypes.FIRST, - "Second extruder": SupportDualTypes.SECOND - }, - retraction_combing={ - "Off": RetractionCombingTypes.OFF, - "All": RetractionCombingTypes.ALL, - "No Skin": RetractionCombingTypes.NO_SKIN - } - ) - - result = dict() - for section in config.sections(): - - if not section in ("profile", "alterations", "machine"): - continue - - for option in config.options(section): - ignored = False - key = option - - if section == "machine" and key != "gcode_flavor": - continue - - # try to fetch the value in the correct type - try: - value = config.getboolean(section, option) - except: - # no boolean, try int - try: - value = config.getint(section, option) - except: - # no int, try float - try: - value = config.getfloat(section, option) - except: - # no float, use str - value = config.get(section, option) - index = None - - for opt in arrayified_options: - # if there's a period, the index comes before it - optsplit = opt.split('.') - keysplit = key.split('.') - if key.startswith(optsplit[0]) and keysplit[1:] == optsplit[1:]: - if key == opt: - index = 0 - else: - try: - # try to convert the target index, e.g. print_temperature2 => print_temperature[1] - index = int(keysplit[0][len(optsplit[0]):]) - 1 - except ValueError: - # ignore entries for which that fails - ignored = True - key = opt - break - if ignored: - continue - - if key in translated_options: - # if the key has to be translated to a new value, do that now - key = translated_options[key] - - if key in value_conversions and value in value_conversions[key]: - value = value_conversions[key][value] - - if key == "gcode_flavor": - value = parse_gcode_flavor(value) - - if index is not None: - # if we have an array to fill, make sure the target array exists and has the right size - if not key in result: - result[key] = [] - if len(result[key]) <= index: - for n in range(index - len(result[key]) + 1): - result[key].append(None) - result[key][index] = value - else: - # just set the value if there's no array to fill - result[key] = value - - # merge it with our default settings, the imported profile settings taking precedence - return cls.merge_profile(result) - - - @classmethod - def merge_profile(cls, profile, overrides=None): - result = dict() - for key in defaults.keys(): - r = cls.merge_profile_key(key, profile, overrides=overrides) - if r is not None: - result[key] = r - return result - - @classmethod - def merge_profile_key(cls, key, profile, overrides=None): - profile_value = None - override_value = None - - if not key in defaults: - return None - import copy - result = copy.deepcopy(defaults[key]) - - if key in profile: - profile_value = profile[key] - if overrides and key in overrides: - override_value = overrides[key] - - if profile_value is None and override_value is None: - # neither override nor profile, no need to handle this key further - return None - - if key in ("filament_diameter", "print_temperature", "start_gcode", "end_gcode"): - # the array fields need some special treatment. Basically something like this: - # - # override_value: [None, "b"] - # profile_value : ["a" , None, "c"] - # default_value : ["d" , "e" , "f", "g"] - # - # should merge to something like this: - # - # ["a" , "b" , "c", "g"] - # - # So override > profile > default, if neither override nor profile value are available - # the default value should just be left as is - - for x in range(len(result)): - if override_value is not None and x < len(override_value) and override_value[x] is not None: - # we have an override value for this location, so we use it - result[x] = override_value[x] - elif profile_value is not None and x < len(profile_value) and profile_value[x] is not None: - # we have a profile value for this location, so we use it - result[x] = profile_value[x] - - else: - # just change the result value to the override_value if available, otherwise to the profile_value if - # that is given, else just leave as is - if override_value is not None: - result = override_value - elif profile_value is not None: - result = profile_value - - return result - - def __init__(self, profile, printer_profile, posX, posY, overrides=None): - self._profile = self.__class__.merge_profile(profile, overrides=overrides) - self._printer_profile = printer_profile - self._posX = posX - self._posY = posY - - def profile(self): - import copy - return copy.deepcopy(self._profile) - - def get(self, key): - if key in ("machine_width", "machine_depth", "machine_center_is_zero"): - if key == "machine_width": - return self._printer_profile["volume"]["width"] - elif key == "machine_depth": - return self._printer_profile["volume"]["depth"] - elif key == "machine_height": - return self._printer_profile["volume"]["height"] - elif key == "machine_center_is_zero": - return self._printer_profile["volume"]["formFactor"] == "circular" or self._printer_profile["volume"]["origin"] == "center" - else: - return None - - elif key == "extruder_amount": - return self._printer_profile["extruder"]["count"] - - elif key.startswith("extruder_offset_"): - extruder_offsets = self._printer_profile["extruder"]["offsets"] - match = Profile.regex_extruder_offset.match(key) - if not match: - return 0.0 - - axis, number = match.groups() - axis = axis.lower() - number = int(number) - - if not axis in ("x", "y"): - return 0.0 - if number >= len(extruder_offsets): - return 0.0 - - if axis == "x": - return extruder_offsets[number][0] - elif axis == "y": - return extruder_offsets[number][1] - else: - return 0.0 - - elif key == "has_heated_bed": - return self._printer_profile["heatedBed"] - - elif key.startswith("filament_diameter"): - match = Profile.regex_filament_diameter.match(key) - if not match: - return 0.0 - - diameters = self._get("filament_diameter") - if not match.group(1): - return diameters[0] - index = int(match.group(1)) - 1 - if index >= len(diameters) or index < 0: - return 0.0 - return diameters[index] - - elif key.startswith("print_temperature"): - match = Profile.regex_print_temperature.match(key) - if not match: - return 0.0 - - temperatures = self._get("print_temperature") - if not match.group(1): - return temperatures[0] - index = int(match.group(1)) - 1 - if index >= len(temperatures) or index < 0: - return 0.0 - return temperatures[index] - - else: - return self._get(key) - - def _get(self, key): - if key in self._profile: - return self._profile[key] - elif key in defaults: - return defaults[key] - else: - return None - - def get_int(self, key, default=None): - value = self.get(key) - if value is None: - return default - - try: - return int(value) - except ValueError: - return default - - def get_float(self, key, default=None): - value = self.get(key) - if value is None: - return default - - if isinstance(value, (str, unicode, basestring)): - value = value.replace(",", ".").strip() - - try: - return float(value) - except ValueError: - return default - - def get_boolean(self, key, default=None): - value = self.get(key) - if value is None: - return default - - if isinstance(value, bool): - return value - elif isinstance(value, (str, unicode, basestring)): - return value.lower() == "true" or value.lower() == "yes" or value.lower() == "on" or value == "1" - elif isinstance(value, (int, float)): - return value > 0 - else: - return value == True - - def get_microns(self, key, default=None): - value = self.get_float(key, default=None) - if value is None: - return default - return int(value * 1000) - - def get_gcode_template(self, key, extruder_count=1): - if key in self._profile: - gcode = self._profile[key] - else: - gcode = defaults[key] - - if key in ("start_gcode", "end_gcode"): - return gcode[extruder_count-1] - else: - return gcode - - def get_profile_string(self): - import base64 - import zlib - - import copy - profile = copy.deepcopy(defaults) - profile.update(self._profile) - for key in ("print_temperature", "print_temperature2", "print_temperature3", "print_temperature4", - "filament_diameter", "filament_diameter2", "filament_diameter3", "filament_diameter4"): - profile[key] = self.get(key) - - result = [] - for k, v in profile.items(): - if isinstance(v, (str, unicode)): - result.append("{k}={v}".format(k=k, v=v.encode("utf-8"))) - else: - result.append("{k}={v}".format(k=k, v=v)) - - return base64.b64encode(zlib.compress("\b".join(result), 9)) - - def replaceTagMatch(self, m): - import time - - pre = m.group(1) - tag = m.group(2) - - if tag == 'time': - return pre + time.strftime('%H:%M:%S') - if tag == 'date': - return pre + time.strftime('%d-%m-%Y') - if tag == 'day': - return pre + ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][int(time.strftime('%w'))] - if tag == 'profile_string': - return pre + 'CURA_OCTO_PROFILE_STRING:%s' % (self.get_profile_string()) - - if pre == 'F' and tag == 'max_z_speed': - f = self.get_float("travel_speed") * 60 - elif pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'bottom_layer_speed', 'cool_min_feedrate']: - f = self.get_float(tag) * 60 - elif self.get(tag): - f = self.get(tag) - else: - return '%s?%s?' % (pre, tag) - - if (f % 1) == 0: - return pre + str(int(f)) - - return pre + str(f) - - def get_gcode(self, key, extruder_count=1): - prefix = "" - postfix = "" - - if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE: - if key == "end_gcode": - return "M25 ;Stop reading from this point on.\n;CURA_OCTO_PROFILE_STRING:%s\n" % (self.get_profile_string()) - return "" - - if key == "start_gcode": - contents = self.get_gcode_template("start_gcode", extruder_count=extruder_count) - prefix += self.get_start_gcode_prefix(contents) - - else: - contents = self.get_gcode_template(key, extruder_count=extruder_count) - - return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n' - - def get_start_gcode_prefix(self, contents): - extruder_count = self.get_int("extruder_amount") - - prefix = "" - - gcode_parameter_key = "S" - if self.get("gcode_flavor") == GcodeFlavors.MACH3: - gcode_parameter_key = "P" - - e_steps = self.get_float("steps_per_e") - if e_steps > 0: - prefix += "M92 E{e_steps}\n".format(e_steps=e_steps) - temp = self.get_float("print_temperature") - - bed_temp = 0 - if self.get_boolean("has_heated_bed"): - bed_temp = self.get_float("print_bed_temperature") - include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents) - - if include_bed_temp: - prefix += "M140 {param}{bed_temp}\n".format(param=gcode_parameter_key, bed_temp=bed_temp) - - if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents): - if extruder_count > 0: - def temp_line(temp, extruder, param, template): - t = temp - if extruder > 0: - print_temp = self.get_float("print_temperature%d" % (extruder + 1)) - if print_temp > 0: - t = print_temp - return template.format(extruder=extruder, temp=t, param=param) - - prefix_preheat = "" - prefix_waitheat = "" - for n in range(0, extruder_count): - if n > 0: - prefix_preheat += temp_line(temp, n, gcode_parameter_key, "M104 T{extruder} {param}{temp}\n") - prefix_waitheat += temp_line(temp, n, gcode_parameter_key, "M109 T{extruder} {param}{temp}\n") - prefix += prefix_preheat + prefix_waitheat + "T0\n" - else: - prefix += "M109 {param}{temp}\n".format(param=gcode_parameter_key, temp=temp) - - if include_bed_temp: - prefix += "M190 {param}{bed_temp}\n".format(param=gcode_parameter_key, bed_temp=bed_temp) - - return prefix - - def calculate_edge_width_and_line_count(self): - wall_thickness = self.get_float("wall_thickness") - nozzle_size = self._printer_profile["extruder"]["nozzleDiameter"] - - if self.get_boolean("spiralize") or self.get_boolean("follow_surface"): - return wall_thickness, 1 - if wall_thickness < 0.01: - return nozzle_size, 0 - if wall_thickness < nozzle_size: - return wall_thickness, 1 - - edge_width = None - line_count = int(wall_thickness / (nozzle_size - 0.0001)) - if line_count < 1: - edge_width = nozzle_size - line_count = 1 - line_width = wall_thickness / line_count - line_width_alt = wall_thickness / (line_count + 1) - if line_width > nozzle_size * 1.5: - return line_width_alt, line_count + 1 - if not edge_width: - edge_width = line_width - return edge_width, line_count - - def calculate_solid_layer_count(self): - layer_height = self.get_float("layer_height") - solid_thickness = self.get_float("solid_layer_thickness") - if layer_height == 0.0: - return 1 - import math - return int(math.ceil((solid_thickness - 0.0001) / layer_height)) - - def calculate_minimal_extruder_count(self): - extruder_count = self.get("extruder_amount") - if extruder_count < 2: - return 1 - if self.get("support") == SupportLocationTypes.NONE: - return 1 - if self.get("support_dual_extrusion") == SupportDualTypes.SECOND: - return 2 - return 1 - - def get_pos_x(self): - if self._posX is not None: - try: - return int(float(self._posX)) - except ValueError: - pass - - return int(self.get_float("machine_width") / 2.0 ) if not self.get_boolean("machine_center_is_zero") else 0.0 - - def get_pos_y(self): - if self._posY is not None: - try: - return int(float(self._posY)) - except ValueError: - pass - - return int(self.get_float("machine_depth") / 2.0) if not self.get_boolean("machine_center_is_zero") else 0.0 - - def convert_to_engine(self, used_extruders=1): - - edge_width, line_count = self.calculate_edge_width_and_line_count() - solid_layer_count = self.calculate_solid_layer_count() - - extruder_count = self.get_int("extruder_amount") - minimal_extruder_count = self.calculate_minimal_extruder_count() - actual_extruder_count = max(minimal_extruder_count, used_extruders) - - settings = { - "layerThickness": self.get_microns("layer_height"), - "initialLayerThickness": self.get_microns("bottom_thickness") if self.get_float("bottom_thickness") > 0.0 else self.get_microns("layer_height"), - "filamentDiameter": self.get_microns("filament_diameter"), - "filamentFlow": self.get_int("filament_flow"), - "extrusionWidth": edge_width * 1000, - "layer0extrusionWidth": int(edge_width * self.get_float("first_layer_width_factor") / 100 * 1000), - "insetCount": line_count, - "downSkinCount": solid_layer_count if self.get_boolean("solid_bottom") else 0, - "upSkinCount": solid_layer_count if self.get_boolean("solid_top") else 0, - "infillOverlap": self.get_int("fill_overlap"), - "perimeterBeforeInfill": 1 if self.get_boolean("perimeter_before_infill") else 0, - "initialSpeedupLayers": int(4), - "initialLayerSpeed": self.get_int("bottom_layer_speed"), - "printSpeed": self.get_int("print_speed"), - "infillSpeed": self.get_int("infill_speed") if self.get_int("infill_speed") > 0 else self.get_int("print_speed"), - "inset0Speed": self.get_int("outer_shell_speed") if self.get_int("outer_shell_speed") > 0 else self.get_int("print_speed"), - "insetXSpeed": self.get_int("inner_shell_speed") if self.get_int("inner_shell_speed") > 0 else self.get_int("print_speed"), - "skinSpeed": self.get_int("solidarea_speed") if self.get_int("solidarea_speed") > 0 > 0 else self.get_int("print_speed"), - "moveSpeed": self.get_int("travel_speed"), - "fanSpeedMin": self.get_int("fan_speed") if self.get_boolean("fan_enabled") else 0, - "fanSpeedMax": self.get_int("fan_speed_max") if self.get_boolean("fan_enabled") else 0, - "supportAngle": int(-1) if self.get("support") == SupportLocationTypes.NONE else self.get_int("support_angle"), - "supportEverywhere": int(1) if self.get("support") == SupportLocationTypes.EVERYWHERE else int(0), - "supportLineDistance": int(100 * edge_width * 1000 / self.get_float("support_fill_rate")) if self.get_float("support_fill_rate") > 0 else -1, - "supportXYDistance": int(1000 * self.get_float("support_xy_distance")), - "supportZDistance": int(1000 * self.get_float("support_z_distance")), - "supportExtruder": 0 if self.get("support_dual_extrusion") == SupportDualTypes.FIRST else (1 if self.get("support_dual_extrusion") == SupportDualTypes.SECOND and minimal_extruder_count > 1 else -1), - "retractionAmount": self.get_microns("retraction_amount") if self.get_boolean("retraction_enable") else 0, - "retractionSpeed": self.get_int("retraction_speed"), - "retractionMinimalDistance": self.get_microns("retraction_min_travel"), - "retractionAmountExtruderSwitch": self.get_microns("retraction_dual_amount"), - "retractionZHop": self.get_microns("retraction_hop"), - "minimalExtrusionBeforeRetraction": self.get_microns("retraction_minimal_extrusion"), - "multiVolumeOverlap": self.get_microns("overlap_dual"), - "objectSink": max(0, self.get_microns("object_sink")), - "minimalLayerTime": self.get_int("cool_min_layer_time"), - "minimalFeedrate": self.get_int("cool_min_feedrate"), - "coolHeadLift": 1 if self.get_boolean("cool_head_lift") else 0, - - "enableCombing": 1 if self.get("retraction_combing") == RetractionCombingTypes.ALL else (2 if self.get("retraction_combing") == RetractionCombingTypes.NO_SKIN else 0), - - # model positioning - "posx": self.get_pos_x() * 1000, # in microns - "posy": self.get_pos_y() * 1000, # in microns - - # gcodes - "startCode": self.get_gcode("start_gcode", extruder_count=actual_extruder_count), - "endCode": self.get_gcode("end_gcode", extruder_count=actual_extruder_count), - "preSwitchExtruderCode": self.get_gcode("preSwitchExtruder_gcode", extruder_count=actual_extruder_count), - "postSwitchExtruderCode": self.get_gcode("postSwitchExtruder_gcode", extruder_count=actual_extruder_count), - - # fixing - "fixHorrible": 0, - } - - for extruder in range(1, extruder_count): - for axis in ("x", "y"): - settings["extruderOffset[{extruder}].{axis}".format(extruder=extruder, axis=axis.upper())] = self.get("extruder_offset_{axis}{extruder}".format(extruder=extruder, axis=axis.lower())) - - fanFullHeight = self.get_microns("fan_full_height") - settings["fanFullOnLayerNr"] = (fanFullHeight - settings["initialLayerThickness"] - 1) // settings["layerThickness"] + 1 - if settings["fanFullOnLayerNr"] < 0: - settings["fanFullOnLayerNr"] = 0 - - if self.get("support_type") == SupportTypes.LINES: - settings["supportType"] = 1 - - # infill - if self.get_float("fill_density") == 0: - settings["sparseInfillLineDistance"] = -1 - - elif self.get_float("fill_density") == 100: - settings["sparseInfillLineDistance"] = settings["extrusionWidth"] - settings["downSkinCount"] = 10000 - settings["upSkinCount"] = 10000 - - else: - settings["sparseInfillLineDistance"] = int(100 * edge_width * 1000 / self.get_float("fill_density")) - - # brim/raft/skirt - if self.get("platform_adhesion") == PlatformAdhesionTypes.BRIM: - settings["skirtDistance"] = 0 - settings["skirtLineCount"] = self.get_int("brim_line_count") - - elif self.get("platform_adhesion") == PlatformAdhesionTypes.RAFT: - settings["skirtDistance"] = 0 - settings["skirtLineCount"] = 0 - settings["raftMargin"] = self.get_microns("raft_margin") - settings["raftLineSpacing"] = self.get_microns("raft_line_spacing") - settings["raftBaseThickness"] = self.get_microns("raft_base_thickness") - settings["raftBaseLinewidth"] = self.get_microns("raft_base_linewidth") - settings["raftInterfaceThickness"] = self.get_microns("raft_interface_thickness") - settings["raftInterfaceLinewidth"] = self.get_microns("raft_interface_linewidth") - settings["raftInterfaceLineSpacing"] = self.get_microns("raft_interface_linewidth") * 2 - settings["raftAirGapLayer0"] = self.get_microns("raft_airgap") + self.get_microns("raft_airgap_all") - settings["raftAirGap"] = self.get_microns("raft_airgap_all") - settings["raftBaseSpeed"] = self.get_int("bottom_layer_speed") - settings["raftFanSpeed"] = 0 - settings["raftSurfaceThickness"] = self.get_microns("raft_surface_thickness") - settings["raftSurfaceLinewidth"] = self.get_microns("raft_surface_linewidth") - settings["raftSurfaceLineSpacing"] = self.get_microns("raft_surface_linewidth") - settings["raftSurfaceLayers"] = self.get_int("raft_surface_layers") - settings["raftSurfaceSpeed"] = self.get_int("bottom_layer_speed") - - else: - settings["skirtDistance"] = self.get_microns("skirt_gap") - settings["skirtLineCount"] = self.get_int("skirt_line_count") - settings["skirtMinLength"] = self.get_microns("skirt_minimal_length") - - # fixing - if self.get_boolean("fix_horrible_union_all_type_a"): - settings["fixHorrible"] |= 0x01 - if self.get_boolean("fix_horrible_union_all_type_b"): - settings["fixHorrible"] |= 0x02 - if self.get_boolean("fix_horrible_use_open_bits"): - settings["fixHorrible"] |= 0x10 - if self.get_boolean("fix_horrible_extensive_stitching"): - settings["fixHorrible"] |= 0x04 - - if settings["layerThickness"] <= 0: - settings["layerThickness"] = 1000 - - # gcode flavor - settings["gcodeFlavor"] = self.get("gcode_flavor")[0] - - # extras - if self.get_boolean("spiralize"): - settings["spiralizeMode"] = 1 - if self.get_boolean("follow_surface"): - settings["simpleMode"] = 1 - - # dual extrusion - if self.get_boolean("wipe_tower") and extruder_count > 1: - import math - settings["wipeTowerSize"] = int(math.sqrt(self.get_float("wipe_tower_volume") * 1000 * 1000 * 1000 / settings["layerThickness"])) - if self.get_boolean("ooze_shield"): - settings["enableOozeShield"] = 1 - - return settings - - -def parse_gcode_flavor(value): - - value = value.lower() - - if "reprap" in value and ("volume" in value or "volumatric" in value): - return GcodeFlavors.REPRAP_VOLUME - elif "ultigcode" in value: - return GcodeFlavors.ULTIGCODE - elif "makerbot" in value: - return GcodeFlavors.MAKERBOT - elif "bfb" in value: - return GcodeFlavors.BFB - elif "mach3" in value: - return GcodeFlavors.MACH3 - else: - return GcodeFlavors.REPRAP diff --git a/src/octoprint/plugins/cura/profiles/default.profile.yaml b/src/octoprint/plugins/cura/profiles/default.profile.yaml deleted file mode 100644 index d53fabc61..000000000 --- a/src/octoprint/plugins/cura/profiles/default.profile.yaml +++ /dev/null @@ -1,4 +0,0 @@ -layer_height: 0.2 -print_temperature: -- 220.0 -- 220.0 \ No newline at end of file diff --git a/src/octoprint/plugins/cura/static/css/cura.css b/src/octoprint/plugins/cura/static/css/cura.css deleted file mode 100644 index f35eab40a..000000000 --- a/src/octoprint/plugins/cura/static/css/cura.css +++ /dev/null @@ -1 +0,0 @@ -table th.settings_plugin_cura_profiles_key,table td.settings_plugin_cura_profiles_key{text-overflow:ellipsis;text-align:left;width:200px}table th.settings_plugin_cura_profiles_name,table td.settings_plugin_cura_profiles_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_cura_profiles_actions,table td.settings_plugin_cura_profiles_actions{text-align:center;width:100px}table th.settings_plugin_cura_profiles_actions a,table td.settings_plugin_cura_profiles_actions a{text-decoration:none;color:#000}table th.settings_plugin_cura_profiles_actions a.disabled,table td.settings_plugin_cura_profiles_actions a.disabled{color:#ccc;cursor:default} \ No newline at end of file diff --git a/src/octoprint/plugins/cura/static/js/cura.js b/src/octoprint/plugins/cura/static/js/cura.js deleted file mode 100644 index a435065cb..000000000 --- a/src/octoprint/plugins/cura/static/js/cura.js +++ /dev/null @@ -1,319 +0,0 @@ -$(function() { - function CuraViewModel(parameters) { - var self = this; - - self.loginState = parameters[0]; - self.settingsViewModel = parameters[1]; - self.slicingViewModel = parameters[2]; - - self.pathBroken = ko.observable(false); - self.pathOk = ko.observable(false); - self.pathText = ko.observable(); - self.pathHelpVisible = ko.pureComputed(function() { - return self.pathBroken() || self.pathOk(); - }); - - self.fileName = ko.observable(); - - self.placeholderName = ko.observable(); - self.placeholderDisplayName = ko.observable(); - self.placeholderDescription = ko.observable(); - - self.profileName = ko.observable(); - self.profileDisplayName = ko.observable(); - 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(); }); - self.profileDisplayName.subscribe(function() { - if (self.profileDisplayName()) { - self.placeholderName(self._sanitize(self.profileDisplayName()).toLowerCase()); - } - self.copyProfileMetadata(); - }); - self.profileDescription.subscribe(function() { self.copyProfileMetadata(); }); - self.profileAllowOverwrite.subscribe(function() { self.copyProfileMetadata(); }); - self.profileMakeDefault.subscribe(function() { self.copyProfileMetadata(); }); - - self.unconfiguredCuraEngine = ko.observable(); - self.unconfiguredSlicingProfile = ko.observable(); - - self.uploadDialog = $("#settings_plugin_cura_import"); - self.uploadElement = $("#settings-cura-import"); - self.uploadData = ko.observable(undefined); - self.uploadBusy = ko.observable(false); - - self.uploadEnabled = ko.pureComputed(function() { - return self.fieldsEnabled(); - }); - self.fieldsEnabled = ko.pureComputed(function() { - return self.uploadData() && !self.uploadBusy() - && (self.profileName() || self.placeholderName()) - && (self.profileDisplayName() || self.placeholderDisplayName()) - && (self.profileDescription() || self.placeholderDescription()); - }); - - self.profiles = new ItemListHelper( - "plugin_cura_profiles", - { - "id": function(a, b) { - if (a["key"].toLocaleLowerCase() < b["key"].toLocaleLowerCase()) return -1; - if (a["key"].toLocaleLowerCase() > b["key"].toLocaleLowerCase()) return 1; - return 0; - }, - "name": function(a, b) { - // sorts ascending - var aName = a.name(); - if (aName === undefined) { - aName = ""; - } - var bName = b.name(); - if (bName === undefined) { - bName = ""; - } - - if (aName.toLocaleLowerCase() < bName.toLocaleLowerCase()) return -1; - if (aName.toLocaleLowerCase() > bName.toLocaleLowerCase()) return 1; - return 0; - } - }, - {}, - "id", - [], - [], - 5 - ); - - self._sanitize = function(name) { - return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_"); - }; - - self.performUpload = function() { - if (self.uploadData()) { - self.uploadData().submit(); - } - }; - - self.copyProfileMetadata = function(form) { - form = form || (self.uploadData() ? self.uploadData().formData : {}); - - if (self.profileName() !== undefined) { - form["name"] = self.profileName(); - } else if (self.placeholderName() !== undefined) { - form["name"] = self.placeholderName(); - } - - if (self.profileDisplayName() !== undefined) { - form["displayName"] = self.profileDisplayName(); - } else if (self.placeholderDisplayName() !== undefined) { - form["displayName"] = self.placeholderDisplayName(); - } - - if (self.profileDescription() !== undefined) { - form["description"] = self.profileDescription(); - } else if (self.placeholderDescription() !== undefined) { - form["description"] = self.placeholderDescription(); - } - - if (self.profileMakeDefault()) { - form["default"] = true; - } - - return form; - }; - - self.clearUpload = function() { - self.uploadData(undefined); - self.fileName(undefined); - self.placeholderName(undefined); - self.placeholderDisplayName(undefined); - self.placeholderDescription(undefined); - self.profileName(undefined); - self.profileDisplayName(undefined); - self.profileDescription(undefined); - self.profileAllowOverwrite(true); - - var firstProfile = self.profiles.items().length === 0; - self.profileMakeDefault(firstProfile); - self.profileFirst(firstProfile); - }; - - self.uploadElement.fileupload({ - dataType: "json", - maxNumberOfFiles: 1, - autoUpload: false, - headers: OctoPrint.getRequestHeaders(), - add: function(e, data) { - if (data.files.length == 0) { - // no files? ignore - return false; - } - if (self.uploadData()) { - // data already defined? ignore (should never happen) - return false; - } - - self.fileName(data.files[0].name); - - var name = self.fileName().substr(0, self.fileName().lastIndexOf(".")); - self.placeholderName(self._sanitize(name).toLowerCase()); - self.placeholderDisplayName(name); - self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000)); - - var form = { - allowOverwrite: self.profileAllowOverwrite() - }; - data.formData = self.copyProfileMetadata(form); - - self.uploadData(data); - }, - submit: function(e, data) { - self.copyProfileMetadata(); - self.uploadBusy(true); - }, - done: function(e, data) { - self.uploadBusy(false); - self.clearUpload(); - - self.uploadDialog.modal("hide"); - self.requestData(); - self.slicingViewModel.requestData(); - } - }); - - self.removeProfile = function(data) { - if (!data.resource) { - return; - } - - self.profiles.removeItem(function(item) { - return (item.key == data.key); - }); - - OctoPrint.slicing.deleteProfileForSlicer("cura", data.key, {url: data.resource()}) - .done(function() { - self.requestData(); - self.slicingViewModel.requestData(); - }); - }; - - self.makeProfileDefault = function(data) { - if (!data.resource) { - return; - } - - _.each(self.profiles.items(), function(item) { - item.isdefault(false); - }); - var item = self.profiles.getItem(function(item) { - return item.key == data.key; - }); - if (item !== undefined) { - item.isdefault(true); - } - - OctoPrint.slicing.updateProfileForSlicer("cura", data.key, {default: true}, {url: data.resource()}) - .done(function() { - self.requestData(); - }); - }; - - self.showImportProfileDialog = function() { - self.clearUpload(); - self.uploadDialog.modal("show"); - }; - - self.testEnginePath = function() { - OctoPrint.util.testExecutable(self.settings.plugins.cura.cura_engine()) - .done(function(response) { - if (!response.result) { - if (!response.exists) { - self.pathText(gettext("The path doesn't exist")); - } else if (!response.typeok) { - self.pathText(gettext("The path is not a file")); - } else if (!response.access) { - self.pathText(gettext("The path is not an executable")); - } - } else { - self.pathText(gettext("The path is valid")); - } - self.pathOk(response.result); - self.pathBroken(!response.result); - }); - }; - - self.requestData = function() { - self.slicingViewModel.requestData(); - }; - - self.fromResponse = function(data) { - var profiles = []; - _.each(_.keys(data), function(key) { - profiles.push({ - key: key, - name: ko.observable(data[key].displayName), - description: ko.observable(data[key].description), - isdefault: ko.observable(data[key].default), - resource: ko.observable(data[key].resource) - }); - }); - self.profiles.updateItems(profiles); - }; - - self.onBeforeBinding = function () { - self.settings = self.settingsViewModel.settings; - }; - - self.onAllBound = function() { - self.uploadDialog.on("hidden", function(event) { - if (event.target.id == "settings_plugin_cura_import") { - self.clearUpload(); - } - }); - }; - - self.onSettingsShown = function() { - self.requestData(); - }; - - self.onSettingsHidden = function() { - self.resetPathTest(); - }; - - self.onSlicingData = function(data) { - if (data && data.hasOwnProperty("cura") && data.cura.hasOwnProperty("profiles")) { - self.fromResponse(data.cura.profiles); - } - }; - - self.resetPathTest = function() { - self.pathBroken(false); - self.pathOk(false); - self.pathText(""); - }; - - self.onWizardDetails = function(response) { - if (!response.hasOwnProperty("cura") || !response.cura.required) return; - - if (response.cura.details.hasOwnProperty("engine")) { - self.unconfiguredCuraEngine(!response.cura.details.engine); - } - if (response.cura.details.hasOwnProperty("profile")) { - self.unconfiguredSlicingProfile(!response.cura.details.profile); - } - }; - - self.onWizardFinish = function() { - self.resetPathTest(); - }; - } - - OCTOPRINT_VIEWMODELS.push({ - construct: CuraViewModel, - dependencies: ["loginStateViewModel", "settingsViewModel", "slicingViewModel"], - elements: ["#settings_plugin_cura", "#wizard_plugin_cura"] - }); -}); diff --git a/src/octoprint/plugins/cura/static/less/cura.less b/src/octoprint/plugins/cura/static/less/cura.less deleted file mode 100644 index 0d28da219..000000000 --- a/src/octoprint/plugins/cura/static/less/cura.less +++ /dev/null @@ -1,29 +0,0 @@ -table { - th, td { - &.settings_plugin_cura_profiles_key { - text-overflow: ellipsis; - text-align: left; - width: 200px; - } - - &.settings_plugin_cura_profiles_name { - text-overflow: ellipsis; - text-align: left; - } - - &.settings_plugin_cura_profiles_actions { - text-align: center; - width: 100px; - - a { - text-decoration: none; - color: #000; - - &.disabled { - color: #ccc; - cursor: default; - } - } - } - } -} \ No newline at end of file diff --git a/src/octoprint/plugins/cura/templates/cura_settings.jinja2 b/src/octoprint/plugins/cura/templates/cura_settings.jinja2 deleted file mode 100644 index 51a5e31fd..000000000 --- a/src/octoprint/plugins/cura/templates/cura_settings.jinja2 +++ /dev/null @@ -1,25 +0,0 @@ -

{{ _('General') }}

- -

{% trans %} - Specify the path to the CuraEngine binary. Note that only - versions up to and including 15.04 are supported. - CuraEngine version 15.06 or newer is not - compatible with this plugin. -{% endtrans %}

- -
- {% include "snippets/settings/cura/enginePath.jinja2" %} - {% include "snippets/settings/cura/engineLog.jinja2" %} -
- -

{{ _('Profiles') }}

- -{% include "snippets/settings/cura/profiles.jinja2" %} - - - -
- {% trans %}For more information on configuration and usage please see the Plugin's homepage.{% endtrans %} -
- -{% include "snippets/settings/cura/profileImporter.jinja2" %} diff --git a/src/octoprint/plugins/cura/templates/cura_wizard.jinja2 b/src/octoprint/plugins/cura/templates/cura_wizard.jinja2 deleted file mode 100644 index 55f4f7725..000000000 --- a/src/octoprint/plugins/cura/templates/cura_wizard.jinja2 +++ /dev/null @@ -1,36 +0,0 @@ -
-

{{ _('Configure CuraEngine') }}

-

{% trans %} - The path to CuraEngine has not yet been set up, in order to be able to use - CuraEngine for slicing it needs to be specified. - {% endtrans %}

- -
-
- {% include "snippets/settings/cura/enginePath.jinja2" %} -
-
-
- -
-

{{ _('Set up a slicing profile') }}

-

{% trans %}You haven't imported a slicing profile to use for slicing with CuraEngine - yet. If you plan on slicing from within OctoPrint then you should do this now. - Otherwise just skip this step.{% endtrans %}

- -
- {% include "snippets/settings/cura/profiles.jinja2" %} -
- - - -
- {% trans %} - Don't know where to get a profile? In order to export - a slicing profile from the Cura desktop UI up to and including version 15.04.06 (not versions - 2.1 and later which are actually newer than 15.04), open it, set up your profile, then click - on "File" and there on "Save Profile". You can import the .ini file this creates - via the "Import Profile" button. - {% endtrans %} -
-
diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 deleted file mode 100644 index 690f1490d..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 +++ /dev/null @@ -1,7 +0,0 @@ -
-
- -
-
diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 deleted file mode 100644 index b2e6a522d..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 +++ /dev/null @@ -1,10 +0,0 @@ -
- -
-
- - -
- -
-
diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 deleted file mode 100644 index ddf48eb2b..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 +++ /dev/null @@ -1,64 +0,0 @@ - diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 deleted file mode 100644 index f5d85ea3e..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 +++ /dev/null @@ -1,34 +0,0 @@ -
- - - - - - - - - - - - - - - - -
{{ _('Identifier') }}{{ _('Name') }}{{ _('Actions') }}
-  |  -
- -
diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index 604e6337e..2b20cf577 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -20,8 +20,9 @@ import octoprint.plugin import octoprint.util try: + # TODO: looks like pybonjour is py2 only - find alternatives or port? import pybonjour -except: +except ImportError: pybonjour = False @@ -194,8 +195,20 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, params["txtRecord"] = pybonjour.TXTRecord(txt_record) key = (reg_type, port) - self._sd_refs[key] = pybonjour.DNSServiceRegister(**params) - self._logger.info(u"Registered {name} for {reg_type}".format(**locals())) + + counter = 1 + while True: + try: + self._sd_refs[key] = pybonjour.DNSServiceRegister(**params) + self._logger.info("Registered '{name}' for {regtype}".format(**params)) + return True + except pybonjour.BonjourError as be: + if be.errorCode == pybonjour.kDNSServiceErr_NameConflict: + # Name already registered by different service, let's try a counter postfix. See #2852 + counter += 1 + params["name"] = "{} ({})".format(name, counter) + else: + raise def zeroconf_unregister(self, reg_type, port=None): """ @@ -220,7 +233,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, try: sd_ref.close() self._logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port)) - except: + except Exception: self._logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port)) def zeroconf_browse(self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5): @@ -366,7 +379,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, def browse_callback(results): for result in results: - print "Location: {}".format(result) + print("Location: {}".format(result)) :param query: the SSDP query to send, e.g. "upnp:rootdevice" to search for all devices :param block: whether to block, defaults to True @@ -378,10 +391,16 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, """ import threading - - import httplib import io - class Response(httplib.HTTPResponse): + + try: + # noinspection PyCompatibility + from http.client import HTTPResponse # py3 + except ImportError: + # noinspection PyCompatibility + from httplib import HTTPResponse # py2 + + class Response(HTTPResponse): def __init__(self, response_text): self.fp = io.BytesIO(response_text) self.debuglevel = 0 @@ -419,7 +438,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, mcast_addr=self.__class__.ssdp_multicast_addr, mcast_port=self.__class__.ssdp_multicast_port) for _ in range(2): - sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port)) + sock.sendto(message.encode("utf-8"), (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port)) try: data = sock.recv(1024) @@ -429,7 +448,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, response = Response(data) result.append(response.getheader("Location")) - except: + except Exception: pass if callback: @@ -587,8 +606,8 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, mcast_port=self.__class__.ssdp_multicast_port) for _ in range(2): # send twice, stuff might get lost, it's only UDP - sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port)) - except: + sock.sendto(message.encode("utf-8"), (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port)) + except Exception: pass self._ssdp_last_notify = time.time() @@ -601,8 +620,14 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, alive message """ - from BaseHTTPServer import BaseHTTPRequestHandler - from StringIO import StringIO + try: + # noinspection PyCompatibility + from http.server import BaseHTTPRequestHandler + except ImportError: + # noinspection PyCompatibility + from BaseHTTPServer import BaseHTTPRequestHandler + + from io import BytesIO import socket socket.setdefaulttimeout(timeout) @@ -617,8 +642,9 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, class Request(BaseHTTPRequestHandler): + # noinspection PyMissingConstructor def __init__(self, request_text): - self.rfile = StringIO(request_text) + self.rfile = BytesIO(request_text) self.raw_requestline = self.rfile.readline() self.error_code = self.error_message = None self.parse_request() @@ -634,22 +660,23 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.__class__.ssdp_multicast_addr) + socket.inet_aton('0.0.0.0')) - self._logger.info(u"Registered {} for SSDP".format(self.get_instance_name())) + self._logger.info("Registered {} for SSDP".format(self.get_instance_name())) self._ssdp_notify(alive=True) try: - while (self._ssdp_monitor_active): + while self._ssdp_monitor_active: try: data, address = sock.recvfrom(4096) request = Request(data) if not request.error_code and request.command == "M-SEARCH" and request.path == "*" and (request.headers["ST"] == "upnp:rootdevice" or request.headers["ST"] == "ssdp:all") and request.headers["MAN"] == '"ssdp:discover"': interface_address = octoprint.util.address_for_client(*address) if not interface_address: - self._logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address)) + self._logger.warning("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address)) continue - message = location_message.format(uuid=self.get_uuid(), location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port)) - sock.sendto(message, address) + message = location_message.format(uuid=self.get_uuid(), + location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port)) + sock.sendto(message.encode("utf-8"), address) self._logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address)) except socket.timeout: pass @@ -658,7 +685,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, finally: try: sock.close() - except: + except Exception: pass ##~~ helpers @@ -675,10 +702,10 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, def get_instance_name(self): name = self._settings.global_get(["appearance", "name"]) if name: - return u"OctoPrint instance \"{}\"".format(name) + return "OctoPrint instance \"{}\"".format(name) else: import socket - return u"OctoPrint instance on {}".format(socket.gethostname()) + return "OctoPrint instance on {}".format(socket.gethostname()) __plugin_name__ = "Discovery" diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index 9e06b4dd6..5a9b1e65d 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -8,7 +8,8 @@ import octoprint.plugin from octoprint.settings import settings from octoprint.server import NO_CONTENT -from octoprint.server.util.flask import redirect_to_tornado, require_firstrun +from octoprint.server.util.flask import redirect_to_tornado, no_firstrun_access +from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions from flask import request, jsonify, url_for, make_response @@ -18,6 +19,7 @@ from werkzeug.utils import secure_filename from werkzeug.exceptions import BadRequest import yaml +import io import os try: @@ -37,11 +39,12 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, dict(key="MANAGE", name="Logging management", description=gettext("Allows to download and delete log files and list and set log levels."), + default_groups=[ADMIN_GROUP], roles=["manage"]) ] @octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def get_all(self): files = self._getLogFiles() @@ -52,7 +55,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, setup=dict(loggers=loggers, levels=levels)) @octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def get_log_files(self): files = self._getLogFiles() @@ -60,13 +63,13 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, return jsonify(files=files, free=free, total=total) @octoprint.plugin.BlueprintPlugin.route("/logs/", methods=["GET"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def download_log(self, filename): return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename) @octoprint.plugin.BlueprintPlugin.route("/logs/", methods=["DELETE"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def delete_log(self, filename): secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename)) @@ -78,7 +81,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, return NO_CONTENT @octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def get_logging_setup(self): loggers = self._get_available_loggers() @@ -86,13 +89,13 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, return jsonify(loggers=loggers, levels=levels) @octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def get_logging_levels_api(self): return jsonify(self._get_logging_levels()) @octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def set_logging_levels_api(self): if not "application/json" in request.headers["Content-Type"]: @@ -113,12 +116,12 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, def _get_usage(self): import psutil - usage = psutil.disk_usage(settings().getBaseFolder("logs")) + usage = psutil.disk_usage(settings().getBaseFolder("logs", check_writable=False)) return usage.free, usage.total def _getLogFiles(self): files = [] - basedir = settings().getBaseFolder("logs") + basedir = settings().getBaseFolder("logs", check_writable=False) for entry in scandir(basedir): files.append({ "name": entry.name, @@ -133,7 +136,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, return files def _get_available_loggers(self): - return filter(lambda x: self._is_managed_logger(x), self._logger.manager.loggerDict.keys()) + return list(filter(lambda x: self._is_managed_logger(x), self._logger.manager.loggerDict.keys())) def _get_logging_file(self): # TODO this might not be the logging config we are actually using here (command line parameter...) @@ -145,7 +148,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, config_from_file = {} if os.path.exists(logging_file) and os.path.isfile(logging_file): import yaml - with open(logging_file, "r") as f: + with io.open(logging_file, 'rt', encoding='utf-8') as f: config_from_file = yaml.safe_load(f) return config_from_file @@ -164,23 +167,25 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, config = self._get_logging_config() # clear all configured logging levels - if config.has_key("loggers"): + if "loggers" in config: purge = [] - for component in config["loggers"]: + for component, data in config["loggers"].items(): if not self._is_managed_logger(component): continue try: - del config["loggers"][component]["level"] + del data["level"] self._logger.manager.loggerDict[component].setLevel(logging.INFO) - except: + except KeyError: pass - if len(config["loggers"][component]) == 0: + if len(data) == 0: purge.append(component) + for component in purge: + del config["loggers"][component] else: config["loggers"] = dict() # update all logging levels for logger, level in new_levels.items(): - if not config["loggers"].has_key(logger): + if logger not in config["loggers"]: config["loggers"][logger] = dict() config["loggers"][logger]["level"] = level @@ -188,8 +193,8 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, config["loggers"] = {k: v for k, v in config["loggers"].items() if len(v)} # save - with octoprint.util.atomic_write(self._get_logging_file(), "wb", max_permissions=0o666) as f: - yaml.safe_dump(config, f, default_flow_style=False, indent=" ", allow_unicode=True) + with octoprint.util.atomic_write(self._get_logging_file(), mode='wt', max_permissions=0o666) as f: + yaml.safe_dump(config, f, default_flow_style=False, indent=2, allow_unicode=True) # set runtime logging levels now for logger, level in new_levels.items(): @@ -208,6 +213,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, def get_assets(self): return dict(js=["js/logging.js"], + clientjs=["clientjs/logging.js"], less=["less/logging.less"], css=["css/logging.css"]) diff --git a/src/octoprint/plugins/logging/static/clientjs/logging.js b/src/octoprint/plugins/logging/static/clientjs/logging.js new file mode 100644 index 000000000..23b90f85d --- /dev/null +++ b/src/octoprint/plugins/logging/static/clientjs/logging.js @@ -0,0 +1,68 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + + var OctoPrintLoggingClient = function(base) { + this.base = base; + + this.baseUrl = this.base.getBlueprintUrl("logging"); + this.logsUrl = this.baseUrl + "logs"; + this.setupUrl = this.baseUrl + "setup"; + }; + + OctoPrintLoggingClient.prototype.get = function(opts) { + return this.base.get(this.baseUrl, opts); + }; + + OctoPrintLoggingClient.prototype.listLogs = function(opts) { + return this.base.get(this.logsUrl, opts); + }; + + OctoPrintLoggingClient.prototype.deleteLog = function(file, opts) { + var fileUrl = this.logsUrl + "/" + file; + return this.base.delete(fileUrl, opts); + }; + + OctoPrintLoggingClient.prototype.downloadLog = function(file, opts) { + var fileUrl = this.logsUrl + "/" + file; + return this.base.download(fileUrl, opts); + }; + + OctoPrintLoggingClient.prototype.updateLevels = function(config, opts) { + return this.base.putJson(this.setupUrl + "/levels", config, opts); + }; + + //~~ wrapper for backwards compatibility + + var DeprecatedOctoPrintLogsClient = function(base) { + this.base = base; + this.wrapped = this.base.plugins.logging; + }; + + DeprecatedOctoPrintLogsClient.prototype.list = function(opts) { + log.warn("OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead"); + return this.wrapped.listLogs(opts); + }; + + DeprecatedOctoPrintLogsClient.prototype.delete = function(file, opts) { + log.warn("OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead"); + return this.wrapped.deleteLog(file, opts); + }; + + DeprecatedOctoPrintLogsClient.prototype.download = function(file, opts) { + log.warn("OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead"); + return this.wrapped.downloadLog(file, opts); + }; + + // register plugin component + OctoPrintClient.registerPluginComponent("logging", OctoPrintLoggingClient); + + // also register deprecated client under old endpoint + OctoPrintClient.registerComponent("logs", DeprecatedOctoPrintLogsClient); + + return OctoPrintLoggingClient; +}); diff --git a/src/octoprint/plugins/logging/static/css/logging.css b/src/octoprint/plugins/logging/static/css/logging.css index 31603a340..ac69c3e52 100644 --- a/src/octoprint/plugins/logging/static/css/logging.css +++ b/src/octoprint/plugins/logging/static/css/logging.css @@ -1 +1 @@ -table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default} \ No newline at end of file +table td.settings_logs_checkbox,table th.settings_logs_checkbox{text-align:center;width:10px}table td.settings_logs_checkbox input[type=checkbox],table th.settings_logs_checkbox input[type=checkbox]{margin-top:0}table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default} \ No newline at end of file diff --git a/src/octoprint/plugins/logging/static/js/logging.js b/src/octoprint/plugins/logging/static/js/logging.js index c4131debb..f465b5fe7 100644 --- a/src/octoprint/plugins/logging/static/js/logging.js +++ b/src/octoprint/plugins/logging/static/js/logging.js @@ -1,72 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - - var OctoPrintLoggingClient = function(base) { - this.base = base; - - this.baseUrl = this.base.getBlueprintUrl("logging"); - this.logsUrl = this.baseUrl + "logs"; - this.setupUrl = this.baseUrl + "setup"; - }; - - OctoPrintLoggingClient.prototype.get = function(opts) { - return this.base.get(this.baseUrl, opts); - }; - - OctoPrintLoggingClient.prototype.listLogs = function(opts) { - return this.base.get(this.logsUrl, opts); - }; - - OctoPrintLoggingClient.prototype.deleteLog = function(file, opts) { - var fileUrl = this.logsUrl + "/" + file; - return this.base.delete(fileUrl, opts); - }; - - OctoPrintLoggingClient.prototype.downloadLog = function(file, opts) { - var fileUrl = this.logsUrl + "/" + file; - return this.base.download(fileUrl, opts); - }; - - OctoPrintLoggingClient.prototype.updateLevels = function(config, opts) { - return this.base.putJson(this.setupUrl + "/levels", config, opts); - }; - - //~~ wrapper for backwards compatibility - - var DeprecatedOctoPrintLogsClient = function(base) { - this.base = base; - this.wrapped = this.base.plugins.logging; - }; - - DeprecatedOctoPrintLogsClient.prototype.list = function(opts) { - log.warn("OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead"); - return this.wrapped.listLogs(opts); - }; - - DeprecatedOctoPrintLogsClient.prototype.delete = function(file, opts) { - log.warn("OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead"); - return this.wrapped.deleteLog(file, opts); - }; - - DeprecatedOctoPrintLogsClient.prototype.download = function(file, opts) { - log.warn("OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead"); - return this.wrapped.downloadLog(file, opts); - }; - - // register plugin component - OctoPrintClient.registerPluginComponent("logging", OctoPrintLoggingClient); - - // also register deprecated client under old endpoint - OctoPrintClient.registerComponent("logs", DeprecatedOctoPrintLogsClient); - - return OctoPrintLoggingClient; -}); - $(function() { function LoggingViewModel(parameters) { var self = this; @@ -78,6 +9,8 @@ $(function() { self.configuredLoggers = ko.observableArray(); self.configuredLoggersChanged = false; + self.markedForDeletion = ko.observableArray([]); + self.availableLoggersSorted = ko.computed(function() { return _.sortBy(self.availableLoggers()); }); @@ -183,8 +116,37 @@ $(function() { }; self.removeFile = function(filename) { - OctoPrint.plugins.logging.deleteLog(filename) - .done(self.requestData); + var perform = function() { + OctoPrint.plugins.logging.deleteLog(filename) + .done(self.requestData); + }; + + showConfirmationDialog(_.sprintf(gettext("You are about to delete log file \"%(name)s\"."), {name: filename}), + perform); + }; + + self.markFilesOnPage = function() { + self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.listHelper.paginatedItems(), "name")))); + }; + + self.markAllFiles = function() { + self.markedForDeletion(_.map(self.listHelper.allItems, "name")); + }; + + self.clearMarkedFiles = function() { + self.markedForDeletion.removeAll(); + }; + + self.removeMarkedFiles = function() { + var perform = function() { + self._bulkRemove(self.markedForDeletion(), "files") + .done(function() { + self.markedForDeletion.removeAll(); + }); + }; + + showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d log files."), {count: self.markedForDeletion().length}), + perform); }; self.onSettingsShown = function() { @@ -203,6 +165,47 @@ $(function() { console.log("ConfiguredLoggers has not changed. Not saving."); } }; + + self._bulkRemove = function(files) { + var title = gettext("Deleting log files"); + var message = _.sprintf(gettext("Deleting %(count)d log files..."), {count: files.length}); + var handler = function(filename) { + return OctoPrint.plugins.logging.deleteLog(filename) + .done(function() { + deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true); + }) + .fail(function(jqXHR) { + var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename}); + var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText}); + deferred.notify(short, long, false); + }); + }; + + var deferred = $.Deferred(); + + var promise = deferred.promise(); + + var options = { + title: title, + message: message, + max: files.length, + output: true + }; + showProgressModal(options, promise); + + var requests = []; + _.each(files, function(filename) { + var request = handler(filename); + requests.push(request) + }); + $.when.apply($, _.map(requests, wrapPromiseWithAlways)) + .done(function() { + deferred.resolve(); + self.requestData(); + }); + + return promise; + }; } OCTOPRINT_VIEWMODELS.push({ diff --git a/src/octoprint/plugins/logging/static/less/logging.less b/src/octoprint/plugins/logging/static/less/logging.less index dfcb1c1f7..ac8b34dac 100644 --- a/src/octoprint/plugins/logging/static/less/logging.less +++ b/src/octoprint/plugins/logging/static/less/logging.less @@ -1,5 +1,14 @@ table { th, td { + &.settings_logs_checkbox { + text-align: center; + width: 10px; + + input[type="checkbox"] { + margin-top: 0; + } + } + &.settings_logs_name { text-overflow: ellipsis; text-align: left; diff --git a/src/octoprint/plugins/logging/templates/logging_settings.jinja2 b/src/octoprint/plugins/logging/templates/logging_settings.jinja2 index 7a082ec6b..7d427324b 100644 --- a/src/octoprint/plugins/logging/templates/logging_settings.jinja2 +++ b/src/octoprint/plugins/logging/templates/logging_settings.jinja2 @@ -1,13 +1,31 @@

{{ _('Logs') }}

+ + @@ -16,6 +34,7 @@ + diff --git a/src/octoprint/plugins/octopi_support/__init__.py b/src/octoprint/plugins/octopi_support/__init__.py deleted file mode 100644 index 3885b6525..000000000 --- a/src/octoprint/plugins/octopi_support/__init__.py +++ /dev/null @@ -1,175 +0,0 @@ -# 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 flask -import os - -from flask_babel import gettext - -import octoprint.plugin - -_OCTOPI_VERSION_PATH = "/etc/octopi_version" -_CPUINFO_PATH = "/proc/cpuinfo" - -# based on https://elinux.org/RPi_HardwareHistory#Which_Pi_have_I_got.3F -_RPI_REVISION_MAP = { - "Beta": "1B (Beta)", - "0002": "1B", - "0003": "1B", - "0004": "1B", - "0005": "1B", - "0006": "1B", - "0007": "1A", - "0008": "1A", - "0009": "1A", - "000d": "1B", - "000e": "1B", - "000f": "1B", - "0010": "B+", - "0011": "CM1", - "0012": "A+", - "0013": "B+", - "0014": "CM1", - "0015": "A+", - "a01040": "2B", - "a01041": "2B", - "a21041": "2B", - "a22042": "2B", - "900021": "A+", - "900032": "B+", - "900092": "Zero", - "900093": "Zero", - "920093": "Zero", - "9000c1": "Zero W", - "a02082": "3B", - "a020a0": "CM3", - "a22082": "3B", - "a32082": "3B", -} - - -def get_octopi_version(): - with open(_OCTOPI_VERSION_PATH, "r") as f: - version_line = f.readline() - return version_line.strip() - - -def get_pi_cpuinfo(): - fields = dict(revision="Revision", - hardware="Hardware", - serial="Serial") - - result = dict() - with open(_CPUINFO_PATH) as f: - for line in f: - if not line: - continue - - for key, prefix in fields.items(): - if line.startswith(prefix): - result[key] = line[line.index(":") + 1:].strip() - - return result - - -def get_pi_model(hardware, revision): - if hardware not in ("BCM2835",): - return "unknown" - - if revision.startswith("1000"): - # strip flag for over-volted (https://elinux.org/RPi_HardwareHistory#Which_Pi_have_I_got.3F) - revision = revision[4:] - - return _RPI_REVISION_MAP.get(revision.lower(), "unknown") - - -class OctoPiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin, - octoprint.plugin.SimpleApiPlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.TemplatePlugin): - - # noinspection PyMissingConstructor - def __init__(self): - self._version = None - self._cpuinfo = None - self._model = None - - #~~ EnvironmentDetectionPlugin - - def get_additional_environment(self): - return dict(version=self._get_version(), - revision=self._get_cpuinfo().get("revision", "unknown"), - model=self._get_model()) - - #~~ SimpleApiPlugin - - def on_api_get(self, request): - return flask.jsonify(version=self._get_version()) - - #~~ AssetPlugin - - def get_assets(self): - return dict( - js=["js/octopi_support.js"], - css=["css/octopi_support.css"] - ) - - #~~ TemplatePlugin - - def get_template_configs(self): - return [ - dict(type="about", name="About OctoPi", template="octopi_support_about.jinja2") - ] - - def get_template_vars(self): - return dict(version=self._get_version()) - - #~~ Helpers - - def _get_version(self): - if self._version is None: - try: - self._version = get_octopi_version() - except: - self._logger.exception("Error while reading OctoPi version from file {}".format(_OCTOPI_VERSION_PATH)) - self._version = "unknown" - return self._version - - def _get_model(self): - if self._model is None: - try: - cpuinfo = self._get_cpuinfo() - self._model = get_pi_model(cpuinfo.get("hardware", "unknown"), - cpuinfo.get("revision", "unknown")) - except: - self._logger.exception("Error while detecting RPi model") - self._model = "unknown" - return self._model - - def _get_cpuinfo(self): - if self._cpuinfo is None: - try: - self._cpuinfo = get_pi_cpuinfo() - except: - self._logger.exception("Error while fetching cpu info") - self._cpuinfo = dict() - return self._cpuinfo - -__plugin_name__ = "OctoPi Support Plugin" -__plugin_author__ = "Gina Häußge" -__plugin_description__ = "Provides additional information about your OctoPi instance in the UI." -__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to " - "provide additional information about your OctoPi instance," - "which will make it more tricky to help you if you need support.") -__plugin_license__ = "AGPLv3" - -def __plugin_check__(): - from octoprint.util.platform import get_os - return get_os() == "linux" and os.path.exists(_OCTOPI_VERSION_PATH) - -def __plugin_load__(): - global __plugin_implementation__ - __plugin_implementation__ = OctoPiSupportPlugin() diff --git a/src/octoprint/plugins/octopi_support/static/css/octopi_support.css b/src/octoprint/plugins/octopi_support/static/css/octopi_support.css deleted file mode 100644 index 61b3a10ef..000000000 --- a/src/octoprint/plugins/octopi_support/static/css/octopi_support.css +++ /dev/null @@ -1,3 +0,0 @@ -#octopi_support_footer { - white-space: nowrap; -} diff --git a/src/octoprint/plugins/octopi_support/static/js/octopi_support.js b/src/octoprint/plugins/octopi_support/static/js/octopi_support.js deleted file mode 100644 index b27e32c96..000000000 --- a/src/octoprint/plugins/octopi_support/static/js/octopi_support.js +++ /dev/null @@ -1,50 +0,0 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintOctoPiSupportClient = function(base) { - this.base = base; - }; - - OctoPrintOctoPiSupportClient.prototype.get = function(opts) { - return this.base.get(this.base.getSimpleApiUrl("octopi_support")); - }; - - OctoPrintClient.registerPluginComponent("octopi_support", OctoPrintOctoPiSupportClient); - return OctoPrintOctoPiSupportClient; -}); - -$(function() { - - function OctoPiSupportViewModel(parameters) { - var self = this; - - self.requestData = function() { - OctoPrint.plugins.octopi_support.get() - .done(function(response) { - $("#octopi_support_footer").remove(); - if (!response.version) return; - - var octoPrintVersion = $(".footer span.version"); - var octoPiVersion = $(" " + gettext("running on") + " " + gettext("OctoPi") - + " " + response.version + "") - $(octoPiVersion).insertAfter(octoPrintVersion); - }) - }; - - self.onStartup = function() { - self.requestData(); - }; - - self.onServerReconnect = function() { - self.requestData(); - }; - } - - OCTOPRINT_VIEWMODELS.push({ - construct: OctoPiSupportViewModel - }); -}); diff --git a/src/octoprint/plugins/pi_support/__init__.py b/src/octoprint/plugins/pi_support/__init__.py new file mode 100644 index 000000000..22f3a3ada --- /dev/null +++ b/src/octoprint/plugins/pi_support/__init__.py @@ -0,0 +1,333 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import flask +import io +import os +import sarge + +from flask_babel import gettext +from octoprint.util import RepeatedTimer + +import octoprint.plugin +import octoprint.events + +_PROC_DT_MODEL_PATH = "/proc/device-tree/model" +_OCTOPI_VERSION_PATH = "/etc/octopi_version" +_VCGENCMD_THROTTLE = "/usr/bin/vcgencmd get_throttled" + +### uncomment for local debugging +#import sys +#base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes")) +#_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt") +#_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt") +#_VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py")) +#import itertools +#_VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70000")) + + +# see https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=147781&start=50#p972790 +_FLAG_UNDERVOLTAGE = 1 << 0 +_FLAG_FREQ_CAPPED = 1 << 1 +_FLAG_THROTTLED = 1 << 2 +_FLAG_PAST_UNDERVOLTAGE = 1 << 16 +_FLAG_PAST_FREQ_CAPPED = 1 << 17 +_FLAG_PAST_THROTTLED = 1 << 18 + +class ThrottleState(object): + @classmethod + def from_value(cls, value=0): + if value == 0: + return ThrottleState() + + kwargs = dict(undervoltage=_FLAG_UNDERVOLTAGE & value == _FLAG_UNDERVOLTAGE, + freq_capped=_FLAG_FREQ_CAPPED & value == _FLAG_FREQ_CAPPED, + throttled=_FLAG_THROTTLED & value == _FLAG_THROTTLED, + past_undervoltage=_FLAG_PAST_UNDERVOLTAGE & value == _FLAG_PAST_UNDERVOLTAGE, + past_freq_capped=_FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED, + past_throttled=_FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED, + raw_value=value) + return ThrottleState(**kwargs) + + def __init__(self, **kwargs): + self._raw_value = kwargs.get('raw_value', -1) + self._undervoltage = False + self._freq_capped = False + self._throttled = False + self._past_undervoltage = False + self._past_freq_capped = False + self._past_throttled = False + + for key, value in kwargs.items(): + local_key = "_{}".format(key) + if hasattr(self, local_key) and isinstance(value, bool): + setattr(self, local_key, value) + + @property + def undervoltage(self): + return self.current_undervoltage or self.past_undervoltage + + @property + def current_undervoltage(self): + return self._undervoltage + + @property + def past_undervoltage(self): + return self._past_undervoltage + + @property + def overheat(self): + return self.current_overheat or self.past_overheat + + @property + def current_overheat(self): + return self._freq_capped + + @property + def past_overheat(self): + return self._past_freq_capped + + @property + def issue(self): + return self.current_issue or self.past_issue + + @property + def current_issue(self): + return self._undervoltage or self._freq_capped or self._throttled + + @property + def past_issue(self): + return self._past_undervoltage or self._past_freq_capped or self._past_throttled + + def __eq__(self, other): + if not isinstance(other, ThrottleState): + return False + + return self._undervoltage == other._undervoltage \ + and self._freq_capped == other._freq_capped \ + and self._throttled == other._throttled \ + and self._past_undervoltage == other._past_undervoltage \ + and self._past_freq_capped == other._past_freq_capped \ + and self._past_throttled == other._past_throttled + + def as_dict(self): + return dict(raw_value=self._raw_value, + current_undervoltage=self.current_undervoltage, + past_undervoltage=self.past_undervoltage, + current_overheat=self.current_overheat, + past_overheat=self.past_overheat, + current_issue=self.current_issue, + past_issue=self.past_issue) + + +_proc_dt_model = None +def get_proc_dt_model(): + global _proc_dt_model + + if _proc_dt_model is None: + with io.open(_PROC_DT_MODEL_PATH, 'rt', encoding='utf-8') as f: + _proc_dt_model = f.readline().strip(" \t\r\n\0") + + return _proc_dt_model + + +def get_vcgencmd_throttled_state(command): + output = sarge.get_stdout(command) + #output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # for local debugging + if not "throttled=0x" in output: + raise ValueError("cannot parse \"{}\" output: {}".format(command, output)) + + value = output[len("throttled="):].strip(" \t\r\n\0") + value = int(value, 0) + return ThrottleState.from_value(value) + + +def is_octopi(): + return os.path.exists(_OCTOPI_VERSION_PATH) + + +_octopi_version = None +def get_octopi_version(): + global _octopi_version + + if _octopi_version is None: + with io.open(_OCTOPI_VERSION_PATH, 'rt', encoding='utf-8') as f: + _octopi_version = f.readline().strip(" \t\r\n\0") + + return _octopi_version + + +class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.StartupPlugin, + octoprint.plugin.SettingsPlugin): + + # noinspection PyMissingConstructor + def __init__(self): + self._throttle_state = ThrottleState() + self._throttle_check = None + self._throttle_undervoltage = False + self._throttle_overheat = False + self._throttle_functional = True + + #~~ EnvironmentDetectionPlugin + + def get_additional_environment(self): + result = dict(model=get_proc_dt_model()) + + if is_octopi(): + result.update(dict(octopi_version=get_octopi_version())) + + return result + + #~~ SimpleApiPlugin + + def on_api_get(self, request): + result = dict(throttle_state=self._throttle_state.as_dict()) + result.update(self.get_additional_environment()) + return flask.jsonify(**result) + + #~~ AssetPlugin + + def get_assets(self): + return dict( + js=["js/pi_support.js"], + clientjs=["clientjs/pi_support.js"], + css=["css/pi_support.css"] + ) + + #~~ TemplatePlugin + + def get_template_configs(self): + configs = [dict(type="settings", name=gettext("Pi Support"), template="pi_support_settings.jinja2", custom_bindings=False)] + + if is_octopi(): + configs.append(dict(type="about", name="About OctoPi", template="pi_support_about_octopi.jinja2")) + + return configs + + def get_template_vars(self): + return self.get_additional_environment() + + #~~ StartupPlugin + + def on_startup(self, *args, **kwargs): + if self._settings.get_boolean(["vcgencmd_throttle_check_enabled"]): + self._check_throttled_state() + self._throttle_check = RepeatedTimer(self._check_throttled_state_interval, + self._check_throttled_state, + condition=self._check_throttled_state_condition) + self._throttle_check.start() + + #~~ SettingsPlugin + + def get_settings_defaults(self): + return dict(vcgencmd_throttle_check_enabled=True, + vcgencmd_throttle_check_command=_VCGENCMD_THROTTLE) + + def get_settings_restricted_paths(self): + return dict(admin=[["vcgencmd_throttle_check_enabled"], ["vcgencmd_throttle_check_command"]]) + + #~~ Helpers + + def _check_throttled_state_interval(self): + if self._throttle_state.current_issue: + # check state every 30s if something's currently amiss + return 30 + else: + # check state every 5min if nothing's currently amiss + return 300 + + def _check_throttled_state_condition(self): + return self._throttle_functional + + def get_throttle_state(self, run_now=False): + """Exposed as public helper.""" + if run_now: + self._check_throttled_state() + + if not self._throttle_functional: + return False + + return self._throttle_state.as_dict() + + def _check_throttled_state(self): + command = self._settings.get(["vcgencmd_throttle_check_command"]) + + self._logger.debug("Retrieving throttle state via \"{}\"".format(command)) + try: + state = get_vcgencmd_throttled_state(command) + except ValueError: + self._logger.warning("Fetching the current throttle state via \"{}\" doesn't work".format(command)) + self._throttle_functional = False + return + + if self._throttle_state == state: + # no change + return + + self._throttle_state = state + + if (not self._throttle_undervoltage and self._throttle_state.undervoltage) \ + or (not self._throttle_overheat and self._throttle_state.overheat): + message = "This Raspberry Pi is reporting problems that might lead to bad performance or errors caused " \ + "by overheating or insufficient power." + + if self._throttle_state.undervoltage: + self._throttle_undervoltage = True + message += "\n!!! UNDERVOLTAGE REPORTED !!! Make sure that the power supply and power cable are " \ + "capable of supplying enough voltage and current to your Pi." + + if self._throttle_state.overheat: + self._throttle_overheat = True + message += "\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's " \ + "CPU and GPU." + + self._logger.warning(message) + + self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state", + state=self._throttle_state.as_dict())) + + # noinspection PyUnresolvedReferences + self._event_bus.fire(octoprint.events.Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE, self._throttle_state.as_dict()) + + +def register_custom_events(*args, **kwargs): + return ["throttle_state",] + + +__plugin_name__ = "Pi Support Plugin" +__plugin_author__ = "Gina Häußge" +__plugin_description__ = "Provides additional information about your Pi in the UI." +__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to " + "provide additional information about your Pi," + "which will make it more tricky to help you if you need support.") +__plugin_license__ = "AGPLv3" + +def __plugin_check__(): + try: + proc_dt_model = get_proc_dt_model() + if proc_dt_model is None: + return False + except Exception: + return False + + return "raspberry pi" in proc_dt_model.lower() + +def __plugin_load__(): + plugin = PiSupportPlugin() + global __plugin_implementation__ + __plugin_implementation__ = plugin + + global __plugin_hooks__ + __plugin_hooks__ = { + "octoprint.events.register_custom_events": register_custom_events + } + + global __plugin_helpers__ + __plugin_helpers__ = dict(get_throttled=plugin.get_throttle_state) diff --git a/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js b/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js new file mode 100644 index 000000000..7c216aa0f --- /dev/null +++ b/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js @@ -0,0 +1,19 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintPiSupportClient = function(base) { + this.base = base; + }; + + OctoPrintPiSupportClient.prototype.get = function(opts) { + return this.base.get(this.base.getSimpleApiUrl("pi_support")); + }; + + OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient); + return OctoPrintPiSupportClient; +}); + diff --git a/src/octoprint/plugins/pi_support/static/css/pi_support.css b/src/octoprint/plugins/pi_support/static/css/pi_support.css new file mode 100644 index 000000000..c6065b7ed --- /dev/null +++ b/src/octoprint/plugins/pi_support/static/css/pi_support.css @@ -0,0 +1,8 @@ +#octopi_support_footer { + white-space: nowrap; +} + +.pi_support_state_pulsate { + animation: pulsate 1s ease-out; + animation-iteration-count: infinite; +} diff --git a/src/octoprint/plugins/pi_support/static/js/pi_support.js b/src/octoprint/plugins/pi_support/static/js/pi_support.js new file mode 100644 index 000000000..e4b08b8e5 --- /dev/null +++ b/src/octoprint/plugins/pi_support/static/js/pi_support.js @@ -0,0 +1,94 @@ +$(function() { + + function PiSupportViewModel(parameters) { + var self = this; + + self.model = ko.observable(); + + self.currentUndervoltage = ko.observable(false); + self.currentOverheat = ko.observable(false); + self.pastUndervoltage = ko.observable(false); + self.pastOverheat = ko.observable(false); + self.currentIssue = ko.observable(false); + self.pastIssue = ko.observable(false); + + self.requestData = function() { + OctoPrint.plugins.pi_support.get() + .done(function(response) { + // Raspberry Pi model + self.model(response.model); + + // Throttle state + self.fromThrottleState(response.throttle_state); + + // OctoPi version + $("#octopi_support_footer").remove(); + if (!response.octopi_version) return; + + var octoPrintVersion = $(".footer span.version"); + var octoPiVersion = $(" " + gettext("running on") + " " + gettext("OctoPi") + + " " + response.octopi_version + ""); + $(octoPiVersion).insertAfter(octoPrintVersion); + }) + }; + + self.fromThrottleState = function(state) { + self.currentUndervoltage(state.current_undervoltage); + self.pastUndervoltage(state.past_undervoltage); + self.currentOverheat(state.current_overheat); + self.pastOverheat(state.past_overheat); + self.currentIssue(state.current_issue); + self.pastIssue(state.past_issue); + }; + + self.popoverContent = ko.pureComputed(function() { + var undervoltageParagraphClasses = "muted"; + var undervoltageSymbolClasses = ""; + + var overheatParagraphClasses = "muted"; + var overheatSymbolClasses = ""; + + if (self.currentUndervoltage()) { + undervoltageSymbolClasses = "text-error pi_support_state_pulsate"; + undervoltageParagraphClasses = ""; + } else if (self.pastUndervoltage()) { + undervoltageSymbolClasses = "text-error"; + undervoltageParagraphClasses = ""; + } + + if (self.currentOverheat()) { + overheatSymbolClasses = "text-error pi_support_state_pulsate"; + overheatParagraphClasses = ""; + } else if (self.pastOverheat()) { + overheatSymbolClasses = "text-error"; + overheatParagraphClasses = ""; + } + + return "

- " + gettext("Undervoltage. Make sure your power supply and cabling are providing enough power to the Pi.") + "

" + + "

- " + gettext("Frequency capping due to overheating. Improve cooling of the CPU and GPU.") + "

" + + "

" + gettext("A blinking symbol indicates a current issue, a non blinking symbol one that was observed some time since the Pi booted up.") + "

" + + "

" + gettext("Click the symbol in the navbar for more information.") + "

"; + }); + + self.onStartup = function() { + self.requestData(); + }; + + self.onServerReconnect = function() { + self.requestData(); + }; + + self.onDataUpdaterPluginMessage = function(plugin, data) { + if (plugin !== "pi_support") return; + if (!data.hasOwnProperty("state") || !data.hasOwnProperty("type")) return; + if (data.type !== "throttle_state") return; + + self.fromThrottleState(data.state); + } + } + + OCTOPRINT_VIEWMODELS.push({ + construct: PiSupportViewModel, + elements: ["#navbar_plugin_pi_support"] + }); +}); diff --git a/src/octoprint/plugins/octopi_support/templates/octopi_support_about.jinja2 b/src/octoprint/plugins/pi_support/templates/pi_support_about_octopi.jinja2 similarity index 81% rename from src/octoprint/plugins/octopi_support/templates/octopi_support_about.jinja2 rename to src/octoprint/plugins/pi_support/templates/pi_support_about_octopi.jinja2 index 6dcb2d674..b3a43aaaa 100644 --- a/src/octoprint/plugins/octopi_support/templates/octopi_support_about.jinja2 +++ b/src/octoprint/plugins/pi_support/templates/pi_support_about_octopi.jinja2 @@ -2,10 +2,10 @@

The ready-to-go Raspberry Pi image with OctoPrint

-

Version {{ plugin_octopi_support_version }}

+

Version {{ plugin_pi_support_octopi_version }}, running on {{ plugin_pi_support_model }}

diff --git a/src/octoprint/plugins/pi_support/templates/pi_support_navbar.jinja2 b/src/octoprint/plugins/pi_support/templates/pi_support_navbar.jinja2 new file mode 100644 index 000000000..6349f9180 --- /dev/null +++ b/src/octoprint/plugins/pi_support/templates/pi_support_navbar.jinja2 @@ -0,0 +1,4 @@ + + + + diff --git a/src/octoprint/plugins/pi_support/templates/pi_support_settings.jinja2 b/src/octoprint/plugins/pi_support/templates/pi_support_settings.jinja2 new file mode 100644 index 000000000..83cd07fea --- /dev/null +++ b/src/octoprint/plugins/pi_support/templates/pi_support_settings.jinja2 @@ -0,0 +1,31 @@ +

{{ _('Pi Support') }}

+ +

{{ _('Please restart OctoPrint after changing any of this plugin\'s settings.') }}

+ + +
+
+ + {{ _('This will regularly check with the Pi if something is amiss either with power regulation or CPU/GPU temperature.') }} +
+
+ +
+ +
+ +
+ +
+ + {{ _('Defaults to /usr/bin/vcgencmd get_throttled. You usually shouldn\'t have to change this.') }} +
+
+ +
+
+ + + diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 44c684290..1f5032df4 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -11,15 +11,19 @@ import octoprint.plugin import octoprint.plugin.core from octoprint.settings import valid_boolean_trues -from octoprint.server.util.flask import require_firstrun, with_revalidation_checking, check_etag +from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag +from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions +from octoprint.util import to_bytes from octoprint.util.pip import LocalPipCaller from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible -from octoprint.util.platform import get_os +from octoprint.util.platform import get_os, is_os_compatible +from octoprint.events import Events from flask import jsonify, make_response from flask_babel import gettext +import io import logging import sarge import sys @@ -33,6 +37,35 @@ import threading _DATA_FORMAT_VERSION = "v2" + +def map_repository_entry(entry): + result = copy.deepcopy(entry) + + if not "follow_dependency_links" in result: + result["follow_dependency_links"] = False + + result["is_compatible"] = dict( + octoprint=True, + os=True + ) + + if "compatibility" in entry: + if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance( + entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]): + result["is_compatible"]["octoprint"] = is_octoprint_compatible(*entry["compatibility"]["octoprint"]) + + if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance( + entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]): + result["is_compatible"]["os"] = is_os_compatible(entry["compatibility"]["os"]) + + return result + + +already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)" +success_string = "Successfully installed" +failure_string = "Could not install" + + class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.AssetPlugin, @@ -105,10 +138,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, dict(key="MANAGE", name="Manage plugins", description=gettext("Allows to enable, disable and uninstall installed plugins."), + default_groups=[ADMIN_GROUP], roles=["manage"]), dict(key="INSTALL", name="Install new plugins", description=gettext("Allows to install new plugins. Includes the \"Manage plugins\" permission."), + default_groups=[ADMIN_GROUP], roles=["install"], permissions=["PLUGIN_PLUGINMANAGER_MANAGE"], dangerous=True) @@ -127,7 +162,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._console_logger.propagate = False # decouple repository fetching from server startup - self._fetch_all_data(async=True) + self._fetch_all_data(do_async=True) ##~~ SettingsPlugin @@ -155,6 +190,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def get_assets(self): return dict( js=["js/pluginmanager.js"], + clientjs=["clientjs/pluginmanager.js"], css=["css/pluginmanager.css"], less=["less/pluginmanager.less"] ) @@ -171,7 +207,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, plugins = sorted(self._get_plugins(), key=lambda x: x["name"].lower()) return dict( all=plugins, - thirdparty=filter(lambda p: not p["bundled"], plugins), + thirdparty=list(filter(lambda p: not p["bundled"], plugins)), archive_extensions=self.__class__.ARCHIVE_EXTENSIONS ) @@ -183,7 +219,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, ##~~ BlueprintPlugin @octoprint.plugin.BlueprintPlugin.route("/upload_archive", methods=["POST"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_PLUGINMANAGER_INSTALL.require(403) def upload_archive(self): import flask @@ -197,7 +233,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, upload_path = flask.request.values[input_upload_path] upload_name = flask.request.values[input_upload_name] - exts = filter(lambda x: upload_name.lower().endswith(x), self.__class__.ARCHIVE_EXTENSIONS) + exts = list(filter(lambda x: upload_name.lower().endswith(x), self.__class__.ARCHIVE_EXTENSIONS)) if not len(exts): return flask.make_response("File doesn't have a valid extension for a plugin archive", 400) @@ -216,7 +252,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, try: os.remove(archive.name) except Exception as e: - self._logger.warn("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e))) + self._logger.warning("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e))) ##~~ EventHandlerPlugin @@ -224,7 +260,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, from octoprint.events import Events if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False): return - self._fetch_all_data(async=True) + self._fetch_all_data(do_async=True) ##~~ SimpleApiPlugin @@ -274,14 +310,18 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def etag(): import hashlib hash = hashlib.sha1() - hash.update(repr(self._get_plugins())) - hash.update(str(self._repository_available)) - hash.update(repr(self._repository_plugins)) - hash.update(str(self._notices_available)) - hash.update(repr(self._notices)) - hash.update(repr(safe_mode)) - hash.update(repr(self._connectivity_checker.online)) - hash.update(repr(_DATA_FORMAT_VERSION)) + def hash_update(value): + value = value.encode('utf-8') + hash.update(value) + + hash_update(repr(self._get_plugins())) + hash_update(str(self._repository_available)) + hash_update(repr(self._repository_plugins)) + hash_update(str(self._notices_available)) + hash_update(repr(self._notices)) + hash_update(repr(safe_mode)) + hash_update(repr(self._connectivity_checker.online)) + hash_update(repr(_DATA_FORMAT_VERSION)) return hash.hexdigest() def condition(): @@ -351,17 +391,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, raise ValueError("Either URL or path must be provided") self._logger.info("Installing plugin from {}".format(source)) - pip_args = ["install", sarge.shell_quote(source), '--no-cache-dir'] + pip_args = ["--disable-pip-version-check", "install", sarge.shell_quote(source), "--no-cache-dir"] if dependency_links or self._settings.get_boolean(["dependency_links"]): pip_args.append("--process-dependency-links") all_plugins_before = self._plugin_manager.find_plugins(existing=dict()) - already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)" - success_string = "Successfully installed" - failure_string = "Could not install" - try: returncode, stdout, stderr = self._call_pip(pip_args) @@ -383,7 +419,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._logger.info("Plugin to be installed from {} was already installed, forcing a reinstall".format(source)) self._log_message("Looks like the plugin was already installed. Forcing a reinstall.") force = True - except: + except Exception: self._logger.exception("Could not install plugin from %s" % url) return make_response("Could not install plugin from URL, see the log for more details", 500) else: @@ -393,14 +429,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"] try: returncode, stdout, stderr = self._call_pip(pip_args) - except: + except Exception: self._logger.exception("Could not install plugin from {}".format(source)) return make_response("Could not install plugin from source {}, see the log for more details" .format(source), 500) try: - result_line = filter(lambda x: x.startswith(success_string) or x.startswith(failure_string), - stdout)[-1] + result_line = list(filter(lambda x: x.startswith(success_string) or x.startswith(failure_string), + stdout))[-1] except IndexError: self._logger.error("Installing the plugin from {} failed, could not parse output from pip. " "See plugin_pluginmanager_console.log for generated output".format(source)) @@ -443,12 +479,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._send_result_notification("install", result) return jsonify(result) - installed = map(lambda x: x.strip(), result_line[len(success_string):].split(" ")) + installed = list(map(lambda x: x.strip(), result_line[len(success_string):].split(" "))) all_plugins_after = self._plugin_manager.find_plugins(existing=dict(), ignore_uninstalled=False) new_plugin = self._find_installed_plugin(installed, plugins=all_plugins_after) if new_plugin is None: - self._logger.warn("The plugin was installed successfully, but couldn't be found afterwards to " + self._logger.warning("The plugin was installed successfully, but couldn't be found afterwards to " "initialize properly during runtime. Please restart OctoPrint.") result = dict(result=True, source=source, @@ -477,6 +513,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.log_all_plugins() self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version)) + + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, dict(id=new_plugin.key, + version=new_plugin.version, + source=source, + source_type=source_type)) + result = dict(result=True, source=source, source_type=source_type, @@ -499,7 +542,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return make_response("Bundled plugins cannot be uninstalled", 403) if plugin.origin is None: - self._logger.warn(u"Trying to uninstall plugin {plugin} but origin is unknown".format(**locals())) + self._logger.warning("Trying to uninstall plugin {plugin} but origin is unknown".format(**locals())) return make_response("Could not uninstall plugin, its origin is unknown") if plugin.origin.type == "entry_point": @@ -508,11 +551,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if origin is None: origin = plugin.origin[2] - pip_args = ["uninstall", "--yes", origin] + pip_args = ["--disable-pip-version-check", "uninstall", "--yes", origin] try: self._call_pip(pip_args) - except: - self._logger.exception(u"Could not uninstall plugin via pip") + except Exception: + self._logger.exception("Could not uninstall plugin via pip") return make_response("Could not uninstall plugin via pip, see the log for more details", 500) elif plugin.origin.type == "folder": @@ -522,10 +565,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if os.path.isdir(full_path): # plugin is installed via a plugin folder, need to use rmtree to get rid of it - self._log_stdout(u"Deleting plugin from {folder}".format(folder=plugin.location)) + self._log_stdout("Deleting plugin from {folder}".format(folder=plugin.location)) shutil.rmtree(full_path) elif os.path.isfile(full_path): - self._log_stdout(u"Deleting plugin from {file}".format(file=plugin.location)) + self._log_stdout("Deleting plugin from {file}".format(file=plugin.location)) os.remove(full_path) if full_path.endswith(".py"): @@ -534,7 +577,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, os.remove(pyc_file) else: - self._logger.warn(u"Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals())) + self._logger.warning("Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals())) return make_response("Could not uninstall plugin, its origin is unknown") needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) @@ -551,7 +594,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if plugin.enabled: self._plugin_manager.disable_plugin(plugin.key, plugin=plugin) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception(u"Problem disabling plugin {name}".format(name=plugin.key)) + self._logger.exception("Problem disabling plugin {name}".format(name=plugin.key)) result = dict(result=False, uninstalled=True, disabled=False, unloaded=False, reason=e.reason) self._send_result_notification("uninstall", result) return jsonify(result) @@ -560,13 +603,17 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if plugin.loaded: self._plugin_manager.unload_plugin(plugin.key) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception(u"Problem unloading plugin {name}".format(name=plugin.key)) + self._logger.exception("Problem unloading plugin {name}".format(name=plugin.key)) result = dict(result=False, uninstalled=True, disabled=True, unloaded=False, reason=e.reason) self._send_result_notification("uninstall", result) return jsonify(result) self._plugin_manager.reload_plugins() + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN, dict(id=plugin.key, + version=plugin.version)) + result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, @@ -596,7 +643,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif command == "enable": self._mark_plugin_enabled(plugin, needs_restart=needs_restart) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception(u"Problem toggling enabled state of {name}: {reason}".format(name=plugin.key, reason=e.reason)) + self._logger.exception("Problem toggling enabled state of {name}: {reason}".format(name=plugin.key, reason=e.reason)) result = dict(result=False, reason=e.reason) except octoprint.plugin.core.PluginNeedsRestart: result = dict(result=True, @@ -651,10 +698,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def _call_pip(self, args): if self._pip_caller is None or not self._pip_caller.available: - raise RuntimeError(u"No pip available, can't operate".format(**locals())) + raise RuntimeError("No pip available, can't operate".format(**locals())) if "--process-dependency-links" in args: - self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version") + self._log_message("Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version") additional_args = self._settings.get(["pip_args"]) @@ -670,27 +717,30 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return self._pip_caller.execute(*args) def _log_message(self, *lines): - self._log(lines, prefix=u"*", stream="message") + self._log(lines, prefix="*", stream="message") def _log_call(self, *lines): - self._log(lines, prefix=u" ", stream="call") + self._log(lines, prefix=" ", stream="call") def _log_stdout(self, *lines): - self._log(lines, prefix=u">", stream="stdout") + self._log(lines, prefix=">", stream="stdout") def _log_stderr(self, *lines): - self._log(lines, prefix=u"!", stream="stderr") + self._log(lines, prefix="!", stream="stderr") def _log(self, lines, prefix=None, stream=None, strip=True): if strip: - lines = map(lambda x: x.strip(), lines) + lines = list(map(lambda x: x.strip(), lines)) - self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines", loglines=[dict(line=line, stream=stream) for line in lines])) + self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines", + loglines=[dict(line=line, stream=stream) for line in lines])) for line in lines: - self._console_logger.debug(u"{prefix} {line}".format(**locals())) + self._console_logger.debug("{prefix} {line}".format(**locals())) def _mark_plugin_enabled(self, plugin, needs_restart=False): - disabled_list = list(self._settings.global_get(["plugins", "_disabled"])) + disabled_list = list(self._settings.global_get(["plugins", "_disabled"], + validator=lambda x: isinstance(x, list), + fallback=[])) if plugin.key in disabled_list: disabled_list.remove(plugin.key) self._settings.global_set(["plugins", "_disabled"], disabled_list) @@ -704,8 +754,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif not plugin.enabled and plugin.key not in self._pending_enable: self._pending_enable.add(plugin.key) + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, dict(id=plugin.key, + version=plugin.version)) + def _mark_plugin_disabled(self, plugin, needs_restart=False): - disabled_list = list(self._settings.global_get(["plugins", "_disabled"])) + disabled_list = list(self._settings.global_get(["plugins", "_disabled"], + validator=lambda x: isinstance(x, list), + fallback=[])) if not plugin.key in disabled_list: disabled_list.append(plugin.key) self._settings.global_set(["plugins", "_disabled"], disabled_list) @@ -719,12 +775,16 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif (plugin.enabled or plugin.forced_disabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key not in self._pending_disable: self._pending_disable.add(plugin.key) - def _fetch_all_data(self, async=False): + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN, dict(id=plugin.key, + version=plugin.version)) + + def _fetch_all_data(self, do_async=False): def run(): self._repository_available = self._fetch_repository_from_disk() self._notices_available = self._fetch_notices_from_disk() - if async: + if do_async: thread = threading.Thread(target=run) thread.daemon = True thread.start() @@ -739,10 +799,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if mtime + self._repository_cache_ttl >= time.time() > mtime: try: import json - with open(self._repository_cache_path) as f: + with io.open(self._repository_cache_path, 'rt', encoding='utf-8') as f: repo_data = json.load(f) self._logger.info("Loaded plugin repository data from disk, was still valid") - except: + except Exception: self._logger.exception("Error while loading repository data from {}".format(self._repository_cache_path)) return self._refresh_repository(repo_data=repo_data) @@ -765,8 +825,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, try: import json - with octoprint.util.atomic_write(self._repository_cache_path, "wb") as f: - json.dump(repo_data, f) + with octoprint.util.atomic_write(self._repository_cache_path, mode='wb') as f: + f.write(to_bytes(json.dumps(repo_data))) except Exception as e: self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e))) @@ -778,31 +838,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if repo_data is None: return False - current_os = get_os() - octoprint_version = get_octoprint_version(base=True) - - def map_repository_entry(entry): - result = copy.deepcopy(entry) - - if not "follow_dependency_links" in result: - result["follow_dependency_links"] = False - - result["is_compatible"] = dict( - octoprint=True, - os=True - ) - - if "compatibility" in entry: - if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]): - result["is_compatible"]["octoprint"] = is_octoprint_compatible(*entry["compatibility"]["octoprint"], - octoprint_version=octoprint_version) - - if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]): - result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"]) - - return result - - self._repository_plugins = map(map_repository_entry, repo_data) + self._repository_plugins = list(map(map_repository_entry, repo_data)) return True def _fetch_notices_from_disk(self): @@ -813,10 +849,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if mtime + self._notices_cache_ttl >= time.time() > mtime: try: import json - with open(self._notices_cache_path) as f: + with io.open(self._notices_cache_path, 'rt', encoding='utf-8') as f: notice_data = json.load(f) self._logger.info("Loaded notice data from disk, was still valid") - except: + except Exception: self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path)) return self._refresh_notices(notice_data=notice_data) @@ -839,8 +875,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, try: import json - with octoprint.util.atomic_write(self._notices_cache_path, "wb") as f: - json.dump(notice_data, f) + with octoprint.util.atomic_write(self._notices_cache_path, mode="wb") as f: + f.write(to_bytes(json.dumps(notice_data))) except Exception as e: self._logger.exception("Error while saving notices to {}: {}".format(self._notices_cache_path, str(e))) return notice_data @@ -862,7 +898,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, parsed_date = dateutil.parser.parse(notice["date"]) notice["timestamp"] = parsed_date.timetuple() except Exception as e: - self._logger.warn("Error while parsing date {!r} for plugin notice " + self._logger.warning("Error while parsing date {!r} for plugin notice " "of plugin {}, ignoring notice: {}".format(notice["date"], key, str(e))) continue @@ -873,30 +909,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._notices = notices return True - @staticmethod - def _is_os_compatible(current_os, compatibility_entries): - """ - Tests if the ``current_os`` or ``sys.platform`` are blacklisted or whitelisted in ``compatibility_entries`` - """ - if len(compatibility_entries) == 0: - # shortcut - no compatibility info means we are compatible - return True - - negative_entries = map(lambda x: x[1:], filter(lambda x: x.startswith("!"), compatibility_entries)) - positive_entries = filter(lambda x: not x.startswith("!"), compatibility_entries) - - negative_match = False - if negative_entries: - # check if we are blacklisted - negative_match = current_os in negative_entries or any(map(lambda x: sys.platform.startswith(x), negative_entries)) - - positive_match = True - if positive_entries: - # check if we are whitelisted - positive_match = current_os in positive_entries or any(map(lambda x: sys.platform.startswith(x), positive_entries)) - - return positive_match and not negative_match - @property def _reconnect_hooks(self): reconnect_hooks = self.__class__.RECONNECT_HOOKS @@ -907,7 +919,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, result = hook() if isinstance(result, (list, tuple)): reconnect_hooks.extend(filter(lambda x: isinstance(x, basestring), result)) - except: + except Exception: self._logger.exception("Error while retrieving additional hooks for which a " "reconnect is required from plugin {name}".format(**locals())) @@ -969,10 +981,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def map_notification(notification): return self._to_external_notification(key, notification) - return filter(lambda x: x is not None, - map(map_notification, - filter(filter_relevant, - plugin_notifications))) + return list(filter(lambda x: x is not None, + map(map_notification, + filter(filter_relevant, + plugin_notifications)))) def _to_external_notification(self, key, notification): return dict(key=key, @@ -983,6 +995,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, important=notification.get("important", False)) +def _register_custom_events(*args, **kwargs): + return ["install_plugin", "uninstall_plugin", "enable_plugin", "disable_plugin"] + __plugin_name__ = "Plugin Manager" __plugin_author__ = "Gina Häußge" @@ -998,5 +1013,6 @@ def __plugin_load__(): __plugin_hooks__ = { "octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize, "octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types, + "octoprint.events.register_custom_events": _register_custom_events, "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions } diff --git a/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js new file mode 100644 index 000000000..acaaf3590 --- /dev/null +++ b/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js @@ -0,0 +1,82 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintPluginManagerClient = function(base) { + this.base = base; + }; + + OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) { + var refresh_repo, refresh_notices; + if (_.isPlainObject(refresh)) { + refresh_repo = refresh.repo || false; + refresh_notices = refresh.notices || false; + } else { + refresh_repo = refresh; + refresh_notices = false; + } + + var query = []; + if (refresh_repo) query.push("refresh_repository=true"); + if (refresh_notices) query.push("refresh_notices=true"); + + return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts); + }; + + OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) { + return this.get(true, opts); + }; + + OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function(opts) { + return this.get(false, opts); + }; + + OctoPrintPluginManagerClient.prototype.install = function(pluginUrl, dependencyLinks, opts) { + var data = { + url: pluginUrl, + dependency_links: !!dependencyLinks + }; + return this.base.simpleApiCommand("pluginmanager", "install", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) { + var data = { + url: pluginUrl, + dependency_links: !!dependencyLinks, + reinstall: plugin, + force: true + }; + return this.base.simpleApiCommand("pluginmanager", "install", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) { + var data = { + plugin: plugin + }; + return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) { + var data = { + plugin: plugin + }; + return this.base.simpleApiCommand("pluginmanager", "enable", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) { + var data = { + plugin: plugin + }; + return this.base.simpleApiCommand("pluginmanager", "disable", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.upload = function(file) { + return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file); + }; + + OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient); + return OctoPrintPluginManagerClient; +}); diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index ba8291d03..aafc746a1 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -1,86 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintPluginManagerClient = function(base) { - this.base = base; - }; - - OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) { - var refresh_repo, refresh_notices; - if (_.isPlainObject(refresh)) { - refresh_repo = refresh.repo || false; - refresh_notices = refresh.notices || false; - } else { - refresh_repo = refresh; - refresh_notices = false; - } - - var query = []; - if (refresh_repo) query.push("refresh_repository=true"); - if (refresh_notices) query.push("refresh_notices=true"); - - return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts); - }; - - OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) { - return this.get(true, opts); - }; - - OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function(opts) { - return this.get(false, opts); - }; - - OctoPrintPluginManagerClient.prototype.install = function(pluginUrl, dependencyLinks, opts) { - var data = { - url: pluginUrl, - dependency_links: !!dependencyLinks - }; - return this.base.simpleApiCommand("pluginmanager", "install", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) { - var data = { - url: pluginUrl, - dependency_links: !!dependencyLinks, - reinstall: plugin, - force: true - }; - return this.base.simpleApiCommand("pluginmanager", "install", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) { - var data = { - plugin: plugin - }; - return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) { - var data = { - plugin: plugin - }; - return this.base.simpleApiCommand("pluginmanager", "enable", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) { - var data = { - plugin: plugin - }; - return this.base.simpleApiCommand("pluginmanager", "disable", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.upload = function(file) { - return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file); - }; - - OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient); - return OctoPrintPluginManagerClient; -}); - $(function() { function PluginManagerViewModel(parameters) { var self = this; diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index d324b4eaa..713a444b9 100644 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ b/src/octoprint/plugins/printer_safety_check/__init__.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -26,32 +26,43 @@ Learn more at https://faq.octoprint.org/warning-{warning_type} """ # Anet A8 -ANETA8_M115_TEST = lambda name, data: name and name.lower().startswith("anet_a8_") +ANETA8_M115_TEST = ("aneta8", lambda name, data: name and name.lower().startswith("anet_a8_")) # Anycubic MEGA ANYCUBIC_AUTHOR1 = "| Author: (Jolly, xxxxxxxx.CO.)".lower() ANYCUBIC_AUTHOR2 = "| Author: (**Jolly, xxxxxxxx.CO.**)".lower() -ANYCUBIC_RECEIVED_TEST = lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower() or ANYCUBIC_AUTHOR2 in line.lower()) +ANYCUBIC_RECEIVED_TEST = ("anycubic", lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower() or ANYCUBIC_AUTHOR2 in line.lower())) # Creality CR-10s CR10S_AUTHOR = " | Author: (CR-10Slanguage)".lower() -CR10S_RECEIVED_TEST = lambda line: line and CR10S_AUTHOR in line.lower() +CR10S_RECEIVED_TEST = ("cr10s", lambda line: line and CR10S_AUTHOR in line.lower()) -# Malyan M200 aka Monoprice Select Mini -MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200" +# Creality Ender 3 +ENDER3_AUTHOR = " | Author: (Ender3)".lower() +ENDER3_RECEIVED_TEST = ("ender3", lambda line: line and ENDER3_AUTHOR in line.lower()) + +# iMe on Micro3D +IME_M115_TEST = ("ime", lambda name, data: name and name.lower().startswith("ime")) + +# Malyan M200 aka Monoprice Select Mini, versions less than 4.0 +MALYANM200_M115_TEST = ("malyan_m200", lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200" and get_comparable_version(data.get("VER", "0")) < get_comparable_version("4.0")) + +# Stock Micro3D +MICRO3D_M115_TEST = ("micro3d", lambda name, data: name and name.lower().startswith("micro3d")) # Any Repetier versions < 0.92 -REPETIER_BEFORE_092_M115_TEST = lambda name, data: name and name.lower().startswith("repetier") and extract_repetier_version(name) is not None and extract_repetier_version(name) < get_comparable_version("0.92") +REPETIER_BEFORE_092_M115_TEST = ("repetier_before_092", lambda name, data: name and name.lower().startswith("repetier") and extract_repetier_version(name) is not None and extract_repetier_version(name) < get_comparable_version("0.92")) # THERMAL_PROTECTION capability reported as disabled -THERMAL_PROTECTION_CAP_TEST = lambda cap, enabled: cap == "THERMAL_PROTECTION" and not enabled +THERMAL_PROTECTION_CAP_TEST = ("capability", lambda cap, enabled: cap == "THERMAL_PROTECTION" and not enabled) SAFETY_CHECKS = { - "firmware-unsafe": dict(m115=(ANETA8_M115_TEST, MALYANM200_M115_TEST, REPETIER_BEFORE_092_M115_TEST), - received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST), + "firmware-unsafe": dict(m115=(ANETA8_M115_TEST, IME_M115_TEST, MALYANM200_M115_TEST, MICRO3D_M115_TEST, + REPETIER_BEFORE_092_M115_TEST), + received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST, ENDER3_RECEIVED_TEST), cap=(THERMAL_PROTECTION_CAP_TEST,), - message=u"Your printer's firmware is known to lack mandatory safety features (e.g. " \ - u"thermal runaway protection). This is a fire risk.") + message=gettext("Your printer's firmware is known to lack mandatory safety features (e.g. " + "thermal runaway protection). This is a fire risk.")) } def extract_repetier_version(name): @@ -91,6 +102,7 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, def get_assets(self): return dict(js=("js/printer_safety_check.js",), + clientjs=("clientjs/printer_safety_check.js",), css=("css/printer_safety_check.css",), less=("less/printer_safety_check.less",)) @@ -147,9 +159,17 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, if not checks or not message: continue - if any(x(*args, **kwargs) for x in checks): - self._register_warning(warning_type, message) - changes = True + for check_name, check in checks: + if check(*args, **kwargs): + self._register_warning(warning_type, message) + + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PRINTER_SAFETY_CHECK_WARNING, dict(check_type=check_type, + check_name=check_name, + warning_type=warning_type)) + + changes = True + break if changes: self._ping_clients() @@ -171,6 +191,11 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, def _ping_clients(self): self._plugin_manager.send_plugin_message(self._identifier, dict(type="update")) + +def register_custom_events(*args, **kwargs): + return ["warning",] + + __plugin_name__ = "Printer Safety Check" __plugin_author__ = "Gina Häußge" __plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/printer_safety_check.html" @@ -184,6 +209,7 @@ __plugin_hooks__ = { "octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received, "octoprint.comm.protocol.firmware.info": __plugin_implementation__.on_firmware_info_received, "octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received, + "octoprint.events.register_custom_events": register_custom_events, "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions } diff --git a/src/octoprint/plugins/printer_safety_check/static/clientjs/printer_safety_check.js b/src/octoprint/plugins/printer_safety_check/static/clientjs/printer_safety_check.js new file mode 100644 index 000000000..5a52fc4f9 --- /dev/null +++ b/src/octoprint/plugins/printer_safety_check/static/clientjs/printer_safety_check.js @@ -0,0 +1,18 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintPrinterSafetyCheckClient = function(base) { + this.base = base; + }; + + OctoPrintPrinterSafetyCheckClient.prototype.get = function(opts) { + return this.base.get(this.base.getSimpleApiUrl("printer_safety_check"), opts); + }; + + OctoPrintClient.registerPluginComponent("printer_safety_check", OctoPrintPrinterSafetyCheckClient); + return OctoPrintPrinterSafetyCheckClient; +}); diff --git a/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js b/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js index c48ce229d..667a7999f 100644 --- a/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js +++ b/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js @@ -1,22 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintPrinterSafetyCheckClient = function(base) { - this.base = base; - }; - - OctoPrintPrinterSafetyCheckClient.prototype.get = function(opts) { - return this.base.get(this.base.getSimpleApiUrl("printer_safety_check"), opts); - }; - - OctoPrintClient.registerPluginComponent("printer_safety_check", OctoPrintPrinterSafetyCheckClient); - return OctoPrintPrinterSafetyCheckClient; -}); - $(function() { function PrinterSafetyCheckViewModel(parameters) { var self = this; @@ -43,7 +24,7 @@ $(function() { self.fromResponse = function(data) { var warnings = []; _.each(data, function(message, warning_type) { - warnings.push({type: warning_type, message: message}); + warnings.push({type: warning_type, message: gettext(message)}); }); self.warnings(warnings); }; diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index c4e71b35c..151fce98f 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import octoprint.plugin +import io +import copy import flask import os import threading @@ -23,13 +25,21 @@ from . import version_checks, updaters, exceptions, util, cli from flask_babel import gettext -from octoprint.server.util.flask import require_firstrun, with_revalidation_checking, check_etag +from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag from octoprint.server import VERSION, REVISION, BRANCH -from octoprint.access import USER_GROUP +from octoprint.access import USER_GROUP, ADMIN_GROUP from octoprint.access.permissions import Permissions from octoprint.util import dict_merge, to_unicode +from octoprint.util.version import get_comparable_version +from octoprint.util.pip import LocalPipCaller import octoprint.settings + +MINIMUM_PYTHON = "2.7.9" +MINIMUM_SETUPTOOLS = "5.5.1" +MINIMUM_PIP = "9.0.1" + + ##~~ Plugin class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, @@ -42,7 +52,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit") - DATA_FORMAT_VERSION = "v3" + DATA_FORMAT_VERSION = "v4" # noinspection PyMissingConstructor def __init__(self): @@ -61,6 +71,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._version_cache_dirty = False self._version_cache_timestamp = None + self._environment_supported = True + self._environment_versions = dict() + self._environment_ready = threading.Event() + self._console_logger = None def initialize(self): @@ -89,12 +103,15 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, dict(key="UPDATE", name="Update", description=gettext("Allows to perform software updates"), + default_groups=[ADMIN_GROUP], roles=["update"], dangerous=True) ] def on_startup(self, host, port): - console_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), maxBytes=2*1024*1024) + console_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), + maxBytes=2*1024*1024, + encoding="utf-8") console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) console_logging_handler.setLevel(logging.DEBUG) @@ -103,14 +120,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._console_logger.propagate = False def on_after_startup(self): - # refresh cache now if necessary so it's faster once the user connects to the instance - but decouple it from - # the server startup - def fetch_data(): - self.get_current_versions() - - thread = threading.Thread(target=fetch_data) - thread.daemon = True - thread.start() + self._check_environment() + self.get_current_versions() def _get_configured_checks(self): with self._configured_checks_mutex: @@ -120,20 +131,23 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config") check_providers = self._settings.get(["check_providers"], merged=True) + if not isinstance(check_providers, dict): + check_providers = dict() + effective_configs = dict() for name, hook in update_check_hooks.items(): try: hook_checks = hook() - except: + except Exception: self._logger.exception("Error while retrieving update information from plugin {name}".format(**locals())) else: for key, default_config in hook_checks.items(): if key in effective_configs or key == "octoprint": if key == name: - self._logger.warn("Software update hook {} provides check for itself but that was already registered by {} - overwriting that third party registration now!".format(name, check_providers.get(key, "unknown hook"))) + self._logger.warning("Software update hook {} provides check for itself but that was already registered by {} - overwriting that third party registration now!".format(name, check_providers.get(key, "unknown hook"))) else: - self._logger.warn("Software update hook {} tried to overwrite config for check {} but that was already configured elsewhere".format(name, key)) + self._logger.warning("Software update hook {} tried to overwrite config for check {} but that was already configured elsewhere".format(name, key)) continue check_providers[key] = name @@ -158,7 +172,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, if effective_config: effective_configs[key] = effective_config else: - self._logger.warn("Update for {} is empty or None, ignoring it".format(key)) + self._logger.warning("Update for {} is empty or None, ignoring it".format(key)) # finally set all our internal representations to our processed results for key, config in effective_configs.items(): @@ -172,24 +186,42 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, config_checks = self._settings.get(["checks"]) plugin_and_not_enabled = lambda k: k in check_providers and \ not check_providers[k] in self._plugin_manager.enabled_plugins - obsolete_plugin_checks = filter(plugin_and_not_enabled, - config_checks.keys()) + obsolete_plugin_checks = list(filter(plugin_and_not_enabled, + config_checks.keys())) for key in obsolete_plugin_checks: self._logger.debug("Check for key {} was provided by plugin {} that's no longer available, ignoring it".format(key, check_providers[key])) del self._configured_checks[key] return self._configured_checks + def _check_environment(self): + from platform import python_version + import pkg_resources + + local_pip = LocalPipCaller() + + # check python and setuptools version + versions = dict(python=python_version(), + setuptools=pkg_resources.get_distribution("setuptools").version, + pip=local_pip.version_string) + supported = get_comparable_version(versions["python"]) >= get_comparable_version(MINIMUM_PYTHON) \ + and get_comparable_version(versions["setuptools"]) >= get_comparable_version(MINIMUM_SETUPTOOLS) \ + and get_comparable_version(versions["pip"]) >= get_comparable_version(MINIMUM_PIP) + + self._environment_supported = supported + self._environment_versions = versions + self._environment_ready.set() + def _load_version_cache(self): if not os.path.isfile(self._version_cache_path): return import yaml try: - with open(self._version_cache_path) as f: + with io.open(self._version_cache_path, 'rt', encoding='utf-8') as f: data = yaml.safe_load(f) timestamp = os.stat(self._version_cache_path).st_mtime - except: + except Exception: self._logger.exception("Error while loading version cache from disk") else: try: @@ -213,7 +245,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._version_cache_dirty = False self._version_cache_timestamp = timestamp self._logger.info("Loaded version cache from disk") - except: + except Exception: self._logger.exception("Error parsing in version cache data") def _save_version_cache(self): @@ -224,8 +256,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, octoprint_version = get_versions()["version"] self._version_cache["__version"] = octoprint_version - with atomic_write(self._version_cache_path, max_permissions=0o666) as file_obj: - yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True) + with atomic_write(self._version_cache_path, mode='wt', max_permissions=0o666) as file_obj: + yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=2, allow_unicode=True) self._version_cache_dirty = False self._version_cache_timestamp = time.time() @@ -488,22 +520,28 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, #~~ BluePrint API @octoprint.plugin.BlueprintPlugin.route("/check", methods=["GET"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.require(403) def check_for_update(self): if "check" in flask.request.values: - check_targets = map(lambda x: x.strip(), flask.request.values["check"].split(",")) + check_targets = list(map(lambda x: x.strip(), flask.request.values["check"].split(","))) else: check_targets = None force = flask.request.values.get("force", "false") in octoprint.settings.valid_boolean_trues def view(): + self._environment_ready.wait(timeout=30.0) + try: information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force) - return flask.jsonify(dict(status="inProgress" if self._update_in_progress else "updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current", + return flask.jsonify(dict(status="inProgress" if self._update_in_progress else "updatePossible" if update_available and update_possible and self._environment_supported else "updateAvailable" if update_available else "current", information=information, - timestamp=self._version_cache_timestamp)) + timestamp=self._version_cache_timestamp, + environment=dict(supported=self._environment_supported, + versions=[dict(name=gettext("Python"), current=self._environment_versions.get("python", "unknown"), minimum=MINIMUM_PYTHON), + dict(name=gettext("pip"), current=self._environment_versions.get("pip", "unknown"), minimum=MINIMUM_PIP), + dict(name=gettext("setuptools"), current=self._environment_versions.get("setuptools", "unknown"), minimum=MINIMUM_SETUPTOOLS)]))) except exceptions.ConfigurationInvalid as e: return flask.make_response("Update not properly configured, can't proceed: %s" % e.message, 500) @@ -514,26 +552,30 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, if targets is None: targets = checks.keys() - import hashlib hash = hashlib.sha1() + def hash_update(value): + value = value.encode('utf-8') + hash.update(value) targets = sorted(targets) for target in targets: current_hash = self._get_check_hash(checks.get(target, dict())) if target in self._version_cache and not force: data = self._version_cache[target] - hash.update(current_hash) - hash.update(str(data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"])) - hash.update(repr(data["information"])) - hash.update(str(data["available"])) - hash.update(str(data["possible"])) - hash.update(str(data.get("online", None))) + hash_update(current_hash) + hash_update(str(data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"])) + hash_update(repr(data["information"])) + hash_update(str(data["available"])) + hash_update(str(data["possible"])) + hash_update(str(data.get("online", None))) - hash.update(",".join(targets)) - hash.update(str(self._version_cache_timestamp)) - hash.update(str(self._connectivity_checker.online)) - hash.update(str(self._update_in_progress)) - hash.update(self.DATA_FORMAT_VERSION) + hash_update(",".join(targets)) + + hash_update(str(self._environment_supported)) + hash_update(str(self._version_cache_timestamp)) + hash_update(str(self._connectivity_checker.online)) + hash_update(str(self._update_in_progress)) + hash_update(self.DATA_FORMAT_VERSION) return hash.hexdigest() def condition(): @@ -545,13 +587,16 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, @octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.require(403) def perform_update(self): if self._printer.is_printing() or self._printer.is_paused(): # do not update while a print job is running return flask.make_response("Printer is currently printing or paused", 409) + if not self._environment_supported: + return flask.make_response("Direct updates are not supported in this Python environment", 409) + if not "application/json" in flask.request.headers["Content-Type"]: return flask.make_response("Expected content-type JSON", 400) @@ -560,7 +605,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, return flask.make_response("Invalid JSON", 400) if "targets" in json_data: - targets = map(lambda x: x.strip(), json_data["targets"]) + targets = list(map(lambda x: x.strip(), json_data["targets"])) else: targets = None @@ -578,6 +623,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, return dict( css=["css/softwareupdate.css"], js=["js/softwareupdate.js"], + clientjs=["clientjs/softwareupdate.js"], less=["less/softwareupdate.less"] ) @@ -620,7 +666,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, checks = self._get_configured_checks() if check_targets is None: - check_targets = checks.keys() + check_targets = list(checks.keys()) update_available = False update_possible = False @@ -647,11 +693,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, future = executor.submit(self._get_current_version, target, populated_check, force=force) futures_to_result[future] = (target, populated_check) except exceptions.UnknownCheckType: - self._logger.warn("Unknown update check type for target {}: {}".format(target, + self._logger.warning("Unknown update check type for target {}: {}".format(target, check.get("type", ""))) continue - except: + except Exception: self._logger.exception("Could not check {} for updates".format(target)) continue @@ -664,6 +710,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, continue target_information, target_update_available, target_update_possible, target_online, target_error = future.result() + target_update_possible = target_update_possible and self._environment_supported target_information = dict_merge(dict(local=dict(name="?", value="?"), remote=dict(name="?", value="?", @@ -730,7 +777,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, return "{" + ", ".join(lines) + "}" hash = hashlib.md5() - hash.update(dict_to_sorted_repr(check)) + def hash_update(value): + value = value.encode('utf-8') + hash.update(value) + hash_update(dict_to_sorted_repr(check)) return hash.hexdigest() def _get_current_version(self, target, check, force=False, online=None): @@ -762,14 +812,14 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, update_possible = False information["needs_online"] = True except exceptions.UnknownCheckType: - self._logger.warn("Unknown check type %s for %s" % (check["type"], target)) + self._logger.warning("Unknown check type %s for %s" % (check["type"], target)) update_possible = False error = "unknown_check" except exceptions.NetworkError: - self._logger.warn("Could not check %s for updates due to a network error" % target) + self._logger.warning("Could not check %s for updates due to a network error" % target) update_possible = False error = "network" - except: + except Exception: self._logger.exception("Could not check %s for updates" % target) update_possible = False error = "unknown" @@ -777,7 +827,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, try: updater = self._get_updater(target, check) update_possible = updater.can_perform_update(target, check, online=online) - except: + except Exception: update_possible = False self._version_cache[target] = dict(timestamp=time.time(), @@ -797,6 +847,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, :param targets: an iterable defining the targets to update, if not supplied defaults to all targets """ + if not self._environment_supported: + self._logger.error("Direct updates are unsupported in this environment") + return [], dict() + targets = kwargs.get("targets", kwargs.get("check_targets", None)) checks = self._get_configured_checks() @@ -806,7 +860,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, populated_checks[target] = self._populated_check(target, check) except exceptions.UnknownCheckType: self._logger.debug("Ignoring unknown check type for target {}".format(target)) - except: + except Exception: self._logger.exception("Error while populating check prior to update for target {}".format(target)) if targets is None: @@ -910,12 +964,30 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, return False, None if not update_possible: - self._logger.warn("Cannot perform update for %s, update type is not fully configured" % target) + self._logger.warning("Cannot perform update for %s, update type is not fully configured" % target) return False, None # determine the target version to update to target_version = information["remote"]["value"] target_error = False + target_result = None + + def trigger_event(success, **additional_payload): + from octoprint.events import Events + + if success: + # noinspection PyUnresolvedReferences + event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED + else: + # noinspection PyUnresolvedReferences + event = Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED + + payload = copy.copy(additional_payload) + payload.update(dict(target=target, + from_version=information["local"]["value"], + to_version=target_version)) + + self._event_bus.fire(event, payload=payload) ### The actual update procedure starts here... @@ -930,18 +1002,21 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log, online=online) target_result = ("success", update_result) self._logger.info("Update of %s to %s successful!" % (target, target_version)) + trigger_event(True) except exceptions.UnknownUpdateType: - self._logger.warn("Update of %s can not be performed, unknown update type" % target) + self._logger.warning("Update of %s can not be performed, unknown update type" % target) self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="Unknown update type")) return False, None except exceptions.CannotUpdateOffline: - self._logger.warn("Update of %s can not be performed, it's not marked as 'offline' capable but we are apparently offline right now" % target) + self._logger.warning("Update of %s can not be performed, it's not marked as 'offline' capable but we are apparently offline right now" % target) self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="No internet connection")) except Exception as e: self._logger.exception("Update of %s can not be performed, please also check plugin_softwareupdate_console.log for possible causes of this" % target) + trigger_event(False) + if not "ignorable" in populated_check or not populated_check["ignorable"]: target_error = True @@ -979,11 +1054,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._logger.info("Restarting...") try: - util.execute(restart_command, evaluate_returncode=False, async=True) + util.execute(restart_command, evaluate_returncode=False, do_async=True) except exceptions.ScriptError as e: self._logger.exception("Error while restarting via command {}".format(restart_command)) - self._logger.warn("Restart stdout:\n{}".format(e.stdout)) - self._logger.warn("Restart stderr:\n{}".format(e.stderr)) + self._logger.warning("Restart stdout:\n{}".format(e.stdout)) + self._logger.warning("Restart stderr:\n{}".format(e.stderr)) raise exceptions.RestartFailed() def _populated_check(self, target, check): @@ -1005,7 +1080,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, result["displayVersion"] = to_unicode(check.get("displayVersion"), errors="replace") if result["displayVersion"] is None: # displayVersion missing or set to None - result["displayVersion"] = u"{octoprint_version}" + result["displayVersion"] = "{octoprint_version}" stable_branch = "master" release_branches = [] @@ -1059,7 +1134,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, result["displayVersion"] = to_unicode(check.get("displayVersion", check.get("current")), errors="replace") if result["displayVersion"] is None: # displayVersion AND current missing or None - result["displayVersion"] = u"unknown" + result["displayVersion"] = "unknown" if check["type"] in self.COMMIT_TRACKING_TYPES: result["current"] = check.get("current", None) @@ -1074,11 +1149,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, def _log(self, lines, prefix=None, stream=None, strip=True): if strip: - lines = map(lambda x: x.strip(), lines) + lines = list(map(lambda x: x.strip(), lines)) self._send_client_message("loglines", data=dict(loglines=[dict(line=line, stream=stream) for line in lines])) for line in lines: - self._console_logger.debug(u"{} {}".format(prefix, line)) + self._console_logger.debug("{} {}".format(prefix, line)) def _send_client_message(self, message_type, data=None): self._plugin_manager.send_plugin_message(self._identifier, dict(type=message_type, data=data)) @@ -1137,7 +1212,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, python_updater=updaters.python_updater, sleep_a_bit=updaters.sleep_a_bit) - method = self._get_update_method(target, check, valid_methods=mapping.keys()) + method = self._get_update_method(target, check, valid_methods=list(mapping.keys())) return mapping[method] def _get_octoprint_checkout_folder(self, checks=None): @@ -1155,6 +1230,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, return None +def _register_custom_events(*args, **kwargs): + return ["update_succeeded", "update_failed"] + + __plugin_name__ = "Software Update" __plugin_author__ = "Gina Häußge" __plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html" @@ -1178,7 +1257,6 @@ def __plugin_load__(): global __plugin_hooks__ __plugin_hooks__ = { "octoprint.cli.commands": cli.commands, + "octoprint.events.register_custom_events": _register_custom_events, "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions } - - diff --git a/src/octoprint/plugins/softwareupdate/cli.py b/src/octoprint/plugins/softwareupdate/cli.py index 42e7629b9..cad7a0de0 100644 --- a/src/octoprint/plugins/softwareupdate/cli.py +++ b/src/octoprint/plugins/softwareupdate/cli.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): import click + click.disable_unicode_literals_warning = True import sys import requests.exceptions from octoprint.cli.client import create_client, client_options @@ -124,7 +125,8 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): if targets: data["check"] = targets - client = create_client(apikey=apikey, + client = create_client(settings=cli_group.settings, + apikey=apikey, host=host, port=port, httpuser=httpuser, @@ -149,7 +151,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): plugin_message_data = plugin_message["data"] if plugin_message_type == "updating": - click.echo("Updating {} to {}...".format(plugin_message_data["name"], plugin_message_data["target"])) + click.echo("Updating {} to {}...".format(plugin_message_data.get("name", "unknown"), plugin_message_data.get("version", "n/a"))) elif plugin_message_type == "update_failed": click.echo("\t... failed :(") @@ -191,9 +193,9 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): flags["seen_close"] = True click.echo("Disconnected from server...") - socket = client.connect_socket(on_message=on_message, - on_open=on_open, - on_close=on_close) + socket = client.create_socket(on_message=on_message, + on_open=on_open, + on_close=on_close) r = client.post_json("plugin/softwareupdate/update", data=data) try: diff --git a/src/octoprint/plugins/softwareupdate/exceptions.py b/src/octoprint/plugins/softwareupdate/exceptions.py index 75f66d3b4..685317025 100644 --- a/src/octoprint/plugins/softwareupdate/exceptions.py +++ b/src/octoprint/plugins/softwareupdate/exceptions.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' diff --git a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py index 14574f45b..f8a541972 100644 --- a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py +++ b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py @@ -1,5 +1,6 @@ -#!/bin/env python2 -from __future__ import absolute_import, division, print_function +#!/bin/env python +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Haeussge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -11,6 +12,8 @@ import sys import traceback import time +from past.builtins import unicode + def _log_call(*lines): _log(lines, prefix=">", stream="call") @@ -29,20 +32,20 @@ def _log(lines, prefix=None, stream=None): output_stream = sys.stderr for line in lines: - to_print = _to_str(u"{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")), - errors="replace") + to_print = _to_bytes("{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")), + errors="replace") print(to_print, file=output_stream) def _to_unicode(s_or_u, encoding="utf-8", errors="strict"): """Make sure ``s_or_u`` is a unicode string.""" - if isinstance(s_or_u, str): + if isinstance(s_or_u, bytes): return s_or_u.decode(encoding, errors=errors) else: return s_or_u -def _to_str(s_or_u, encoding="utf-8", errors="strict"): +def _to_bytes(s_or_u, encoding="utf-8", errors="strict"): """Make sure ``s_or_u`` is a str.""" if isinstance(s_or_u, unicode): return s_or_u.encode(encoding, errors=errors) @@ -59,7 +62,9 @@ def _execute(command, **kwargs): joined_command = command _log_call(joined_command) - kwargs.update(dict(async=True, stdout=sarge.Capture(), stderr=sarge.Capture())) + kwargs.update(dict(async_=True, + stdout=sarge.Capture(), + stderr=sarge.Capture())) try: p = sarge.run(command, **kwargs) @@ -78,7 +83,7 @@ def _execute(command, **kwargs): # the process might have been set to None in case of any exception print("Error while trying to run command {}".format(joined_command), file=sys.stderr) return None, [], [] - except: + except Exception: print("Error while trying to run command {}".format(joined_command), file=sys.stderr) traceback.print_exc(file=sys.stderr) return None, [], [] @@ -89,28 +94,28 @@ def _execute(command, **kwargs): while p.commands[0].poll() is None: lines = p.stderr.readlines(timeout=0.5) if lines: - lines = map(lambda x: _to_unicode(x, errors="replace"), lines) + lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) _log_stderr(*lines) - all_stderr += list(lines) + all_stderr += lines lines = p.stdout.readlines(timeout=0.5) if lines: - lines = map(lambda x: _to_unicode(x, errors="replace"), lines) + lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) _log_stdout(*lines) - all_stdout += list(lines) + all_stdout += lines finally: p.close() lines = p.stderr.readlines() if lines: - lines = map(lambda x: _to_unicode(x, errors="replace"), lines) + lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) _log_stderr(*lines) all_stderr += lines lines = p.stdout.readlines() if lines: - lines = map(lambda x: _to_unicode(x, errors="replace"), lines) + lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) _log_stdout(*lines) all_stdout += lines @@ -142,7 +147,7 @@ def _git(args, cwd, git_executable=None): print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr) traceback.print_exc(file=sys.stderr) return None, [], [] - except: + except Exception: print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr) traceback.print_exc(file=sys.stderr) return None, [], [] @@ -157,7 +162,7 @@ def _python(args, cwd, python_executable, sudo=False): command = ["sudo"] + command try: return _execute(command, cwd=cwd) - except: + except Exception: import traceback print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr) traceback.print_exc(file=sys.stderr) @@ -170,7 +175,7 @@ def _to_error(*lines): lines = lines[0] elif not isinstance(lines[0], (str, unicode)): lines = [repr(lines[0]),] - return u"\n".join(map(lambda x: _to_unicode(x, errors="replace"), lines)) + return "\n".join(map(lambda x: _to_unicode(x, errors="replace"), lines)) def _rescue_changes(git_executable, folder): @@ -178,7 +183,7 @@ def _rescue_changes(git_executable, folder): returncode, stdout, stderr = _git(["diff", "--shortstat"], folder, git_executable=git_executable) if returncode is None or returncode != 0: raise RuntimeError("Could not update, \"git diff\" failed with returncode {}".format(returncode)) - if stdout and u"".join(stdout).strip(): + if stdout and "".join(stdout).strip(): # we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch import time import os @@ -190,8 +195,8 @@ def _rescue_changes(git_executable, folder): if returncode is None or returncode != 0: raise RuntimeError("Could not update, installation directory was dirty and state could not be persisted as a patch to {}".format(patch)) - import codecs - with codecs.open(patch, "w", encoding="utf-8", errors="replace") as f: + import io + with io.open(patch, "wt", encoding="utf-8", errors="replace") as f: for line in stdout: f.write(line) diff --git a/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js new file mode 100644 index 000000000..932dcf8ce --- /dev/null +++ b/src/octoprint/plugins/softwareupdate/static/clientjs/softwareupdate.js @@ -0,0 +1,84 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintSoftwareUpdateClient = function(base) { + this.base = base; + + var url = this.base.getBlueprintUrl("softwareupdate"); + this.checkUrl = url + "check"; + this.updateUrl = url + "update"; + }; + + OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) { + if (arguments.length == 1 && _.isObject(arguments[0])) { + var params = arguments[0]; + entries = params.entries; + force = params.force; + opts = params.opts; + } + + entries = entries || []; + if (typeof entries == "string") { + entries = [entries]; + } + + var data = {}; + if (!!force) { + data.force = true; + } + if (entries && entries.length) { + data.check = entries.join(","); + } + return this.base.getWithQuery(this.checkUrl, data, opts); + }; + + OctoPrintSoftwareUpdateClient.prototype.check = function(force, opts) { + if (arguments.length === 1 && _.isObject(arguments[0])) { + var params = arguments[0]; + force = params.force; + opts = params.opts; + } + + return this.checkEntries({entries: [], force: force, opts: opts}); + }; + + OctoPrintSoftwareUpdateClient.prototype.update = function(targets, force, opts) { + if (arguments.length === 1 && _.isObject(arguments[0])) { + var params = arguments[0]; + targets = params.targets; + force = params.force; + opts = params.opts; + } + + targets = targets || []; + if (typeof targets === "string") { + targets = [targets]; + } + + var data = { + targets: targets, + force: !!force + }; + return this.base.postJson(this.updateUrl, data, opts); + }; + + OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) { + if (arguments.length === 1 && _.isObject(arguments[0])) { + var params = arguments[0]; + force = params.force; + opts = params.opts; + } + + var data = { + force: !!force + }; + return this.base.postJson(this.updateUrl, data, opts); + }; + + OctoPrintClient.registerPluginComponent("softwareupdate", OctoPrintSoftwareUpdateClient); + return OctoPrintSoftwareUpdateClient; +}); diff --git a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js index 64e1c066b..4d47c8c73 100644 --- a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js +++ b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js @@ -1,88 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintSoftwareUpdateClient = function(base) { - this.base = base; - - var url = this.base.getBlueprintUrl("softwareupdate"); - this.checkUrl = url + "check"; - this.updateUrl = url + "update"; - }; - - OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) { - if (arguments.length == 1 && _.isObject(arguments[0])) { - var params = arguments[0]; - entries = params.entries; - force = params.force; - opts = params.opts; - } - - entries = entries || []; - if (typeof entries == "string") { - entries = [entries]; - } - - var data = {}; - if (!!force) { - data.force = true; - } - if (entries && entries.length) { - data.check = entries.join(","); - } - return this.base.getWithQuery(this.checkUrl, data, opts); - }; - - OctoPrintSoftwareUpdateClient.prototype.check = function(force, opts) { - if (arguments.length === 1 && _.isObject(arguments[0])) { - var params = arguments[0]; - force = params.force; - opts = params.opts; - } - - return this.checkEntries({entries: [], force: force, opts: opts}); - }; - - OctoPrintSoftwareUpdateClient.prototype.update = function(targets, force, opts) { - if (arguments.length === 1 && _.isObject(arguments[0])) { - var params = arguments[0]; - targets = params.targets; - force = params.force; - opts = params.opts; - } - - targets = targets || []; - if (typeof targets === "string") { - targets = [targets]; - } - - var data = { - targets: targets, - force: !!force - }; - return this.base.postJson(this.updateUrl, data, opts); - }; - - OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) { - if (arguments.length === 1 && _.isObject(arguments[0])) { - var params = arguments[0]; - force = params.force; - opts = params.opts; - } - - var data = { - force: !!force - }; - return this.base.postJson(this.updateUrl, data, opts); - }; - - OctoPrintClient.registerPluginComponent("softwareupdate", OctoPrintSoftwareUpdateClient); - return OctoPrintSoftwareUpdateClient; -}); - $(function() { function SoftwareUpdateViewModel(parameters) { var self = this; @@ -117,6 +32,9 @@ $(function() { && !self.octoprintReleasedVersion(); }); + self.environmentSupported = ko.observable(true); + self.environmentVersions = ko.observableArray([]); + self.cacheTimestamp = ko.observable(); self.cacheTimestampText = ko.pureComputed(function() { return formatDate(self.cacheTimestamp()); @@ -133,6 +51,10 @@ $(function() { && (!self.config_checkoutFolder() || self.config_checkoutFolder().trim() === ''); }); + self.enableUpdate = ko.pureComputed(function() { + return !self.updateInProgress && self.environmentSupported(); + }); + self.enable_configSave = ko.pureComputed(function() { return self.config_checkType() === "github_release" || (self.config_checkType() === "git_commit" && !self.error_checkoutFolder()); @@ -301,6 +223,9 @@ $(function() { var octoprint = data.information["octoprint"]; self.octoprintReleasedVersion(!octoprint || octoprint.released_version); + self.environmentSupported(data.environment.supported); + self.environmentVersions(data.environment.versions); + if (data.status === "inProgress") { self._markWorking(gettext("Updating..."), gettext("Updating, please wait.")); return; @@ -315,7 +240,7 @@ $(function() { _.each(self.versions.items(), function(update_info) { if (update_info.updateAvailable) { text += "
  • " - + "" + + "" + "" + update_info.fullNameRemote + "" + (update_info.releaseNotes ? "" + gettext("Release Notes") + "" : "") + "
  • "; @@ -323,7 +248,11 @@ $(function() { }); text += ""; - text += "

    " + gettext("Those components marked with can be updated directly.") + "

    "; + if (!self.environmentSupported()) { + text += "

    " + gettext("This version of the Python environment is not supported for direct updates.") + "

    "; + } else { + text += "

    " + gettext("Those components marked with can be updated directly.") + "

    "; + } if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)) { text += "

    " + gettext("To have updates applied, get in touch with an administrator of this OctoPrint instance.") + "

    "; @@ -400,8 +329,6 @@ $(function() { }; self.performCheck = function(showIfNothingNew, force, ignoreSeen) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK) && !self.settings.settings.plugins.softwareupdate.notify_users()) return; - self.checking(true); OctoPrint.plugins.softwareupdate.check(force) .done(function(data) { @@ -582,7 +509,7 @@ $(function() { }; self._showWorkingDialog = function(title) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)) { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK)) { return; } diff --git a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 index 68b61d78a..13b5c5313 100644 --- a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 +++ b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 @@ -15,6 +15,23 @@ Documentation.

    {% endtrans %} +
    {% trans %} +

    + This version of the Python environment is not supported for direct updates. +

    +

    + To reduce the likelihood of running into update problems in outdated environments, the following minimal + versions are required to use this updater to update OctoPrint or any installed plugins: +

    +{% endtrans %} +
      +
    • : ({{ _('you have') }}: )
    • +
    +{% trans %} +

    + Please take a look at this FAQ entry on how to proceed. +

    +{% endtrans %}
    @@ -29,7 +46,7 @@
    {{ _('Name') }} {{ _('Size') }} {{ _('Date') }}
    - {{ _('Update') }} + {{ _('Update') }} :
    {{ _('Installed:') }} @@ -59,7 +76,7 @@ - +
    @@ -111,7 +128,9 @@

    +
    +
    + +
    +
    +
    +
    + +
    +
    - {{ _('Event based position logging') }} + {{ _('Pausing') }}
    +
    +
    + {{ _('Cancelling') }}
    +
    + +
    diff --git a/src/octoprint/templates/dialogs/settings/webcam.jinja2 b/src/octoprint/templates/dialogs/settings/webcam.jinja2 index 3f2b17e4a..7f8ef954c 100644 --- a/src/octoprint/templates/dialogs/settings/webcam.jinja2 +++ b/src/octoprint/templates/dialogs/settings/webcam.jinja2 @@ -1,6 +1,7 @@

    {{ _('Webcam') }}

    + {% include "snippets/settings/webcam/webcamEnabled.jinja2" %} {% include "snippets/settings/webcam/webcamStreamUrl.jinja2" %} {% include "snippets/settings/webcam/webcamStreamRatio.jinja2" %} {% include "snippets/settings/webcam/webcamOrientation.jinja2" %} @@ -16,6 +17,7 @@

    {{ _('Timelapse Recordings') }}

    + {% include "snippets/settings/webcam/timelapseEnabled.jinja2" %} {% include "snippets/settings/webcam/webcamSnapshotUrl.jinja2" %} {% include "snippets/settings/webcam/ffmpegPath.jinja2" %} {% include "snippets/settings/webcam/watermark.jinja2" %} diff --git a/src/octoprint/templates/dialogs/wizard/firstrun_end.jinja2 b/src/octoprint/templates/dialogs/wizard/firstrun_end.jinja2 index 53b71622a..33aeb89be 100644 --- a/src/octoprint/templates/dialogs/wizard/firstrun_end.jinja2 +++ b/src/octoprint/templates/dialogs/wizard/firstrun_end.jinja2 @@ -4,7 +4,7 @@ Your OctoPrint installation is now all set up and ready to go. {% endtrans %}

    -

    {{ _('On your printer\'s safety') }}

    +

    {{ _('For your printer\'s safety') }}

    {% trans %} @@ -13,12 +13,18 @@ sometimes sadly do catch fire, so stay or have someone else stay close enough to physically intervene in case of such catastrophic failure. {% endtrans %}

    +

    {% trans url='https://octoprint.org/blog/2018/09/03/safe-remote-access/' %} + You also should never make your OctoPrint instance available for everyone on the + public internet, even with Access Control enabled. Your instance will be found, and bad people + will try to abuse it. Don't put yourself at risk, + use a safe way to access your instance remotely. +{% endtrans %}

    {{ _('If you enjoy OctoPrint...') }}

    {% trans url='https://octoprint.org/support-octoprint/?utm_source=octoprint&utm_medium=first_run_wizard' %} - Please consider to support OctoPrint's ongoing development, + Please consider supporting OctoPrint's ongoing development, which can only continue with funding by users like you! You can also find this link in the "About" dialog.
    Thank you! {% endtrans %}

    diff --git a/src/octoprint/templates/index.jinja2 b/src/octoprint/templates/index.jinja2 index 8482cad05..b9b3fb9d3 100644 --- a/src/octoprint/templates/index.jinja2 +++ b/src/octoprint/templates/index.jinja2 @@ -4,7 +4,8 @@ OctoPrint - + + @@ -141,13 +142,14 @@ {% include 'overlays/reloadui.jinja2' %} + {% include 'javascripts.jinja2' %} + {% for key in templates.generic.order %} {% set data = templates.generic.entries[key] %} {% try "" %}{% include data.template ignore missing %}{% endtry %} {% endfor %} - @@ -177,7 +179,5 @@
    - - {% include 'javascripts.jinja2' %} diff --git a/src/octoprint/templates/initscript.jinja2 b/src/octoprint/templates/initscript.jinja2 index c49e77d9f..0542f7eba 100644 --- a/src/octoprint/templates/initscript.jinja2 +++ b/src/octoprint/templates/initscript.jinja2 @@ -34,6 +34,7 @@ var BRANCH = "{{ version.branch|e }}"; var LOCALE = "{{ g.locale|e }}"; var AVAILABLE_LOCALES = {{ locales|tojson }}; + var SUPPORTED_FILETYPES = {{ supportedFiletypes|tojson }}; var SUPPORTED_EXTENSIONS = {{ supportedExtensions|tojson }}; var PERMISSIONS = {{ permissions|tojson }}; diff --git a/src/octoprint/templates/overlays/dragndrop.jinja2 b/src/octoprint/templates/overlays/dragndrop.jinja2 index 1056ed9e4..63341816b 100644 --- a/src/octoprint/templates/overlays/dragndrop.jinja2 +++ b/src/octoprint/templates/overlays/dragndrop.jinja2 @@ -1,4 +1,4 @@ -
    +
    {% if enableSdSupport %} diff --git a/src/octoprint/templates/sidebar/files.jinja2 b/src/octoprint/templates/sidebar/files.jinja2 index 0bbb93313..c1e2f57c4 100644 --- a/src/octoprint/templates/sidebar/files.jinja2 +++ b/src/octoprint/templates/sidebar/files.jinja2 @@ -1,5 +1,8 @@