diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..79141666b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,135 @@ +--- +name: Bug report +about: Create a report to help improve OctoPrint + +--- + + + +#### What were you doing? + + + +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + + + +#### What did you expect to happen? + +#### What happened instead? + +#### Did the same happen when running OctoPrint in safe mode? + + + +#### Version of OctoPrint + + + +#### Operating System running OctoPrint + + + +#### Printer model & used firmware incl. version + + + +#### Browser and version of browser, operating system running browser + + + +#### Link to octoprint.log + + + +#### Link to contents of terminal tab or serial.log + + + +#### Link to contents of Javascript console in the browser + + + +#### Screenshot(s)/video(s) showing the problem: + + + +I have read the FAQ. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..8842b0ca0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,21 @@ +--- +name: Feature request +about: Suggest an idea for this project + +--- + + + +**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/.versioneer-lookup b/.versioneer-lookup index ae23a1c14..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.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev -fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev -improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 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.9rc5 +# staging/maintenance is currently the branch for preparation of 1.3.10rc5 # so is regressionfix/... -staging/maintenance 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev -regressionfix/.* 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa 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 8b11fb9d9..c35aca85e 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -91,7 +91,11 @@ date of first contribution): * [Ganey](https://github.com/ganey) * [Sven Lohrmann](https://github.com/malnvenshorn) * [Andy Castille](https://github.com/klikini) + * [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) 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 47cfe59bc..27f4b8065 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,147 @@ # 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: +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: -![](https://i.imgur.com/BbEZTlc.png) +``` + +[...] +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**. @@ -885,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..97299046d 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) @@ -39,11 +39,11 @@ nothing but ticket management. [community forum at discourse.octoprint.org](https://discourse.octoprint.org) for such support issues. - If you are a **developer** that wants to brainstorm a pull request or possible - changes to the plugin system, add [Brainstorming] to your issue's title (e.g. - `[Brainstorming] New plugin hook for doing some cool stuff`). + changes to the plugin system, please get in touch on the + [community forum at discourse.octoprint.org](https://discourse.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 discourse.octoprint.org](https://discourse.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. @@ -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://discourse.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/SUPPORTERS.md b/SUPPORTERS.md index 2ddb3b341..aae0022bb 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -6,25 +6,23 @@ 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 * George Robles - * günter weber - * Hydra Research LLC - * James Seigel - * Jeff Moe + * Jared Go * Jeff Renfer * Jefferson Hunt * Jeremiah Avery @@ -35,29 +33,25 @@ thanks to everyone who contributed! * 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 - * Noe Ruiz + * Mosaic Manufacturing * Patrick McGinnis + * Prof Yuh Wen Chen * Randy C. Will * Robert Gusek * Roger Strolz - * Roy Cortes - * Rudolff Vang * Samer Najia * Simon Hallam * Stefan Krister * Sven Mueller - * Symbiotic Devices * Thomas Hatley * Timothy D Hoogland * Trent Shumay -and 1351 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 index 46ee73c8c..6015d3359 100644 --- a/docs/api/apps.rst +++ b/docs/api/apps.rst @@ -11,6 +11,10 @@ Apps Session Keys ============ +.. deprecated:: 1.3.11 + + This functionality will be removed in 1.4.0. Use the :ref:`Application Keys Plugin workflow ` instead. + 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. diff --git a/docs/api/general.rst b/docs/api/general.rst index cc1cd0a72..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. @@ -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/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/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/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 7dc337991..8bf1d5d35 100644 --- a/docs/bundledplugins/index.rst +++ b/docs/bundledplugins/index.rst @@ -9,8 +9,11 @@ Bundled Plugins action_command_prompt.rst announcements.rst + appkeys.rst + backup.rst cura.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..1fd5d3a80 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 diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index ec3b71f7e..af992cbcc 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -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: @@ -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 @@ -1058,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:: diff --git a/docs/events/index.rst b/docs/events/index.rst index a97e7e385..685558b27 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: @@ -322,6 +318,9 @@ 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 @@ -338,6 +337,10 @@ 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 @@ -354,6 +357,8 @@ 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 @@ -371,6 +376,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 +389,10 @@ 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) + * ``user``: the user who cancelled the print job (if available) + * ``position``: the print head position at the time of cancelling (if available) * ``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` @@ -408,7 +419,10 @@ 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) * ``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` @@ -435,6 +449,9 @@ 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 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/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/hooks.rst b/docs/plugins/hooks.rst index 6e588b241..31ce92e85 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -208,6 +208,10 @@ octoprint.accesscontrol.appkey .. py:function:: acl_appkey_hook(*args, **kwargs) + .. deprecated:: 1.3.11 + + This functionality will be removed in 1.4.0. Use the :ref:`Application Keys Plugin workflow ` instead. + By handling this hook plugins may register additional :ref:`App session key providers ` within the system. @@ -903,6 +907,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 @@ -1323,6 +1355,59 @@ 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 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.py b/setup.py index ba2412f48..a66affe45 100644 --- a/setup.py +++ b/setup.py @@ -12,45 +12,53 @@ import octoprint_setuptools #----------------------------------------------------------------------------------------------------------------------- +# Supported python versions +PYTHON_REQUIRES = ">=2.7.9,<3" + # Requirements for our application INSTALL_REQUIRES = [ - "flask>=0.10.1,<0.11", - "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 - "werkzeug>=0.8.3,<0.9", - "tornado==4.5.3", - #"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a - # vendored one - "PyYAML>=3.10,<3.11", - "Flask-Login>=0.2.11,<0.3", - "Flask-Principal>=0.3.5,<0.4", - "Flask-Babel>=0.9,<0.10", - "Flask-Assets>=0.10,<0.11", - "markdown>=2.6.9,<2.7", + # 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.10.1,<0.11", # 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 + "Flask-Login>=0.2.11,<0.3", # some functions changed to properties in 0.3 + "regex!=2018.11.6", # avoid broken 2018.11.6. See #2874 + + # anything below this should be checked on releases for new versions + + "Flask-Principal>=0.4,<0.5", + "Flask-Babel>=0.12,<0.13", + "Flask-Assets>=0.12,<0.13", + "werkzeug>=0.14.1,<0.15", + "PyYAML>=3.13,<4", + "markdown>=3.0,<3.1", "pyserial>=3.4,<3.5", "netaddr>=0.7.19,<0.8", - "watchdog>=0.8.3,<0.9", + "watchdog>=0.9.0,<0.10", "sarge==0.1.5post0", - "netifaces>=0.10.6,<0.11", - "pylru>=1.0.9,<1.1", - "rsa>=3.2.3,<3.3", + "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.4.2,<2.5", - "psutil>=5.4.6,<5.5", - "Click>=6.2,<6.3", + "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.2,<0.16", - "scandir>=1.3,<1.4", - "websocket-client>=0.40.0,<0.41", - "python-dateutil>=2.6.1,<2.7", + "future>=0.17,<0.18", + "scandir>=1.9,<1.10", + "websocket-client>=0.53,<0.54", + "python-dateutil>=2.7.5,<2.8", "wrapt>=1.10.11,<1.11", - "futures>=3.1.1,<3.2", - "emoji>=0.4.5,<0.5", - "monotonic>=1.3,<1.4", + "futures>=3.2,<3.3", + "emoji>=0.5.1,<0.6", + "monotonic>=1.5,<1.6", "frozendict>=1.2,<1.3" ] @@ -63,7 +71,7 @@ EXTRA_REQUIRES = dict( develop=[ # Testing dependencies "mock>=2.0.0,<3", - "nose>=1.3.0,<1.4", + "nose>=1.3.7,<1.4", "ddt", # Documentation dependencies @@ -75,13 +83,10 @@ EXTRA_REQUIRES = dict( # Dependencies for developing OctoPrint plugins plugins=[ - "cookiecutter>=1.4,<1.7" + "cookiecutter>=1.6,<1.7" ] ) -# Additional requirements for setup -SETUP_REQUIRES = [] - # Dependency links for any of the aforementioned dependencies DEPENDENCY_LINKS = [] @@ -154,10 +159,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", diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 31566ff46..73a994f49 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -103,8 +103,9 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, 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) @@ -141,7 +142,7 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, ignore_blacklist=ignore_blacklist, connectivity_checker=connectivity_checker) except Exception as ex: - raise FatalStartupError("Could not initialize settings manager", cause=ex) + raise FatalStartupError("Could not initialize plugin manager", cause=ex) kwargs["plugin_manager"] = plugin_manager if callable(after_plugin_manager): @@ -595,6 +596,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..b794f4798 100644 --- a/src/octoprint/__main__.py +++ b/src/octoprint/__main__.py @@ -2,6 +2,10 @@ # coding=utf-8 from __future__ import absolute_import, division, print_function +import sys +if sys.version_info[0] >= 3: + raise RuntimeError("Sorry, OctoPrint does not yet support Python 3") + if __name__ == "__main__": import octoprint octoprint.main() diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index dc9ff6cbf..e536b84d4 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -26,6 +26,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:")) @@ -179,7 +188,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, @@ -217,7 +226,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/events.py b/src/octoprint/events.py index 4b2e2a12b..30f141f84 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -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,14 +175,14 @@ 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)) + 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", @@ -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): """ @@ -239,7 +258,7 @@ class EventManager(object): return self._registeredListeners[event].remove(callback) - self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event)) + self._logger.debug("Unsubscribed listener {!r} for event {}".format(callback, event)) def join(self, timeout=None): self._worker.join(timeout) diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 0ebbbc664..5a1efef7a 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -21,6 +21,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import os import logging +import threading from octoprint.settings import settings as s from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin) @@ -32,16 +33,6 @@ from octoprint.util import deprecated _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, @@ -168,7 +159,8 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None): return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings) -def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, 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 +198,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 +207,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 54566de4f..7970ef7dc 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -839,12 +839,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, diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index b34a78dfa..7ce4b2eb9 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -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. @@ -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'] ) @@ -1799,6 +1811,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 @@ -2043,20 +2059,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/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 0dd9a4be2..8900c5d7a 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -49,7 +49,8 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, #~ 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"]) #~ SettingsPlugin 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..e077903a2 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,29 +1,3 @@ -(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; diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py new file mode 100644 index 000000000..7de100e79 --- /dev/null +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -0,0 +1,403 @@ +# coding=utf-8 +from __future__ import absolute_import + +import flask +import threading +import os +import yaml +import codecs +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 + + +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() + + ##~~ 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 admin_permission.can(): + keys = self._all_api_keys() + else: + keys = self._api_keys_for_user(user_id) + + return flask.jsonify(keys=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 = 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 = 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 = 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 = 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] = 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 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 codecs.open(self._key_path, "rb", encoding="utf-8", errors="strict") as f: + persisted = yaml.safe_load(f) + except: + 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) as f: + yaml.safe_dump(to_persist, f) + except: + self._logger.exception("Could not write application keys to {}".format(self._key_path)) + +__plugin_name__ = u"Application Keys Plugin" +__plugin_description__ = u"Implements a workflow for third party clients to obtain API keys" +__plugin_author__ = u"Gina Häußge, Aldo Hoeben" +__plugin_disabling_discouraged__ = gettext(u"Without this plugin third party clients will no longer be able to " + u"obtain an API key without you manually copy-pasting it.") +__plugin_implementation__ = AppKeysPlugin() +__plugin_hooks__ = { + "octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key +} 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 index 47ceb0a31..160f85070 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -11,7 +11,8 @@ from octoprint.plugin.core import FolderOrigin from octoprint.server import admin_permission, NO_CONTENT from octoprint.server.util.flask import restricted_access from octoprint.util import is_hidden_path -from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version +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 try: @@ -69,6 +70,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, def get_assets(self): return dict(js=["js/backup.js"], + clientjs=["clientjs/backup.js"], css=["css/backup.css"], less=["less/backup.less"]) @@ -82,7 +84,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, unknown_plugins = self._get_unknown_plugins() return flask.jsonify(backups=backups, backup_in_progress=len(self._in_progress) > 0, - unknown_plugins=unknown_plugins) + unknown_plugins=unknown_plugins, + restore_supported=is_os_compatible(["!windows"])) @octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"]) @admin_permission.require(403) @@ -134,6 +137,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, self._logger.info(u"... 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=u"{}".format(exc_info[1]))) + self._logger.error(u"Error while creating backup zip", exc_info=exc_info) thread = threading.Thread(target=self._create_backup, args=(backup_file,), @@ -142,7 +156,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, 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_done=on_backup_done, + on_backup_error=on_backup_error)) thread.daemon = True thread.start() @@ -171,6 +186,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, @admin_permission.require(403) @restricted_access def perform_restore(self): + if not is_os_compatible(["!windows"]): + return flask.make_response(u"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"]) @@ -199,8 +217,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, self._send_client_message("logline", dict(line=line, type="stdout")) for plugin in plugins: - octoprint_compatible = plugin["compatibility"]["octoprint"] - os_compatible = plugin["compatibility"]["os"] + 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: @@ -250,6 +268,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, 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) @@ -263,6 +284,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, 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, @@ -300,8 +322,14 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, import click @click.command("backup") - @click.option("--exclude", multiple=True) + @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 = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S")) settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings) @@ -309,16 +337,22 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, 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("Created {}".format(backup_file)) + 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 @@ -359,8 +393,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, click.echo(u"\t{}".format(line)) for plugin in plugins: - octoprint_compatible = plugin["compatibility"]["octoprint"] - os_compatible = plugin["compatibility"]["os"] + 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: @@ -407,7 +441,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, 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_log_error=on_log_error, + on_invalid_backup=on_log_error): click.echo(u"Restored from {}".format(path)) else: click.echo(u"Restoring from {} failed".format(path), err=True) @@ -479,11 +514,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, thread.start() @classmethod - def _get_disk_size(cls, path): + 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) + total += cls._get_disk_size(entry.path, ignored=ignored) elif entry.is_file(): total += entry.stat().st_size return total @@ -558,81 +599,103 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, plugin_manager=None, datafolder=None, on_backup_start=None, - on_backup_done=None): - if exclude is None: - exclude = [] + on_backup_done=None, + on_backup_error=None): + exclude_by_default = ("generated", "logs", "watched",) - configfile = settings._configfile - basedir = settings._basedir + try: + if exclude is None: + exclude = [] - temporary_path = os.path.join(datafolder, ".{}".format(name)) - final_path = os.path.join(datafolder, name) + configfile = settings._configfile + basedir = settings._basedir - size = cls._get_disk_size(basedir) - if not cls._free_space(os.path.dirname(temporary_path), size): - raise InsufficientSpace() + 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()] + own_folder = datafolder + defaults = [os.path.join(basedir, "config.yaml"),] + \ + [os.path.join(basedir, folder) for folder in default_settings["folder"].keys()] - 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, "w", compression) 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 + # 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: + 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,]) + size += cls._get_disk_size(settings.global_get_basefolder(folder), + ignored=[own_folder,]) + size += cls._get_disk_size(basedir, ignored=defaults + [own_folder,]) - # backup anything else that might be lying around in our basedir - add_to_zip(basedir, "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() - # 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 + compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED - plugins.append(dict(key=plugin.key, - name=plugin.name, - url=plugin.url)) + if callable(on_backup_start): + on_backup_start(name, temporary_path, exclude) - if len(plugins): - zip.writestr("plugin_list.json", json.dumps(plugins)) + 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 = [] - os.rename(temporary_path, final_path) + if source in ignored: + return - if callable(on_backup_done): - on_backup_done(name, final_path, exclude) + 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: + 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, @@ -647,6 +710,13 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, 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(u"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 @@ -670,15 +740,19 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, except KeyError: if callable(on_invalid_backup): on_invalid_backup(u"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"]) - if backup_version > get_octoprint_version(): + 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(u"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 @@ -697,6 +771,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, if not os.path.exists(configfile): if callable(on_invalid_backup): on_invalid_backup(u"Backup lacks config.yaml") + if callable(on_restore_failed): + on_restore_failed(path) return False import yaml @@ -709,6 +785,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, if not os.path.exists(userfile): if callable(on_invalid_backup): on_invalid_backup(u"Backup lacks users.yaml") + if callable(on_restore_failed): + on_restore_failed(path) return False if callable(on_log_progress): @@ -756,18 +834,18 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, if callable(on_log_progress): on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup)) - os.rename(basedir, basedir_backup) + shutil.move(basedir, basedir_backup) try: if callable(on_log_progress): on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir)) - os.rename(basedir_extracted, basedir) + shutil.move(basedir_extracted, basedir) except: if callable(on_log_error): on_log_error(u"Error while restoring config data", exc_info=sys.exc_info()) on_log_error(u"Rolling back old config data") - os.rename(basedir_backup, basedir) + shutil.move(basedir_backup, basedir) if callable(on_restore_failed): on_restore_failed(path) @@ -795,10 +873,14 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, shutil.rmtree(temp) except: - if callable(on_log_error): - on_log_error(u"Error while running restore", exc_info=sys.exc_info()) - if callable(on_restore_failed): - on_restore_failed(path) + exc_info = sys.exc_info() + try: + if callable(on_log_error): + on_log_error(u"Error while running restore", exc_info=exc_info) + if callable(on_restore_failed): + on_restore_failed(path) + finally: + del exc_info return False finally: @@ -813,6 +895,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, if callable(on_log_progress): on_log_progress(u"Restarting...") + if callable(on_restore_done): + on_restore_done(path) + try: sarge.run(restart_command, async_=True) except: @@ -822,8 +907,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, on_log_error(u"Please restart OctoPrint manually") return False - if callable(on_restore_done): - on_restore_done(path) + else: + if callable(on_restore_done): + on_restore_done(path) return True 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/js/backup.js b/src/octoprint/plugins/backup/static/js/backup.js index 61eedb240..26929ec57 100644 --- a/src/octoprint/plugins/backup/static/js/backup.js +++ b/src/octoprint/plugins/backup/static/js/backup.js @@ -1,56 +1,3 @@ -(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; -}); - $(function() { function BackupViewModel(parameters) { var self = this; @@ -80,6 +27,7 @@ $(function() { self.excludeFromBackup = ko.observableArray([]); self.backupInProgress = ko.observable(false); + self.restoreSupported = ko.observable(true); self.backupUploadButton = $("#settings-backup-upload"); self.backupUploadData = undefined; @@ -119,6 +67,7 @@ $(function() { self.fromResponse = function(response) { self.backups.updateItems(response.backups); self.unknownPlugins(response.unknown_plugins); + self.restoreSupported(response.restore_supported); }; self.createBackup = function() { @@ -141,7 +90,15 @@ $(function() { }; 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}), @@ -152,6 +109,12 @@ $(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()}), @@ -208,14 +171,24 @@ $(function() { 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.restoreInProgress(true); - self.loglines.removeAll(); self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"}); self.loglines.push({line: " ", stream: "message"}); - self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true}); } 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"}); diff --git a/src/octoprint/plugins/backup/templates/backup_settings.jinja2 b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 index 2d0e5e57f..e9546adb2 100644 --- a/src/octoprint/plugins/backup/templates/backup_settings.jinja2 +++ b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 @@ -46,7 +46,7 @@ -  |  |  +  |  |  @@ -91,30 +91,36 @@ -

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

+
+

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

-

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

+

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

-
-
- -
-
- - {{ _('Browse...') }} - - - + +
+ +
+
+ + {{ _('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') }} +