diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000..c55ac50cf --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,5 @@ +# These are supported funding model platforms + +github: [foosel] +patreon: foosel +custom: https://octoprint.org/support-octoprint/ diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE/bug_report.md similarity index 95% rename from .github/ISSUE_TEMPLATE.md rename to .github/ISSUE_TEMPLATE/bug_report.md index c65e40fb2..7ee1a4b4c 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -1,3 +1,9 @@ +--- +name: Bug report +about: Create a report to help improve OctoPrint + +--- + -1. ... -2. ... -3. ... +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index c9b4d9f22..51764038b 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -16,8 +16,9 @@ checklist: made sure your changes don't interfere with current development by talking it through with the maintainers, e.g. through a Brainstorming ticket - * [ ] Your PR targets OctoPrint's devel branch, or maintenance if it's - a bug fix for an issue present in the current stable version (no PRs + * [ ] Your PR targets OctoPrint's devel branch if it's a completely + new feature, or maintenance if it's a bug fix or improvement of + existing functionality for the current stable version (no PRs against master or anything else please) * [ ] Your PR was opened from a custom branch on your repository (no PRs from your version of master, maintenance or devel please), diff --git a/.gitignore b/.gitignore index eeaf038e8..856725dd2 100644 --- a/.gitignore +++ b/.gitignore @@ -31,9 +31,12 @@ OctoPrint.egg-info *.codekit venv +venv2 +venv3 venv26 venv27 venv33 venv34 venv35 venv36 +venv37 diff --git a/.travis.yml b/.travis.yml index dd3b081eb..b1f687f3e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,12 +1,22 @@ --- language: python +dist: xenial + +matrix: + include: + - python: '3.7' + env: RUN_FLAKE8=true + python: +- "3.7" +- "3.6" - "2.7" install: - pip install -e .[develop] script: -- nosetests --with-doctest +- test -n "$RUN_FLAKE8" || pytest +- test -z "$RUN_FLAKE8" || flake8 --ignore=D,E,W,F401 src/ tests setup.py sudo: false git: depth: 250 diff --git a/.versioneer-lookup b/.versioneer-lookup index ae23a1c14..6d4cdd4b7 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.13 # 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.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev +fix/.* 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev +improve/.* 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 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.12rc4 # so is regressionfix/... -staging/maintenance 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev -regressionfix/.* 1.3.9rc5 71b2cc87a36d403e09325c90134a002c5229b6aa pep440-dev +staging/maintenance 1.3.12rc4 a70a45f062687beb510fb3192e4227754e1dff39 pep440-dev +regressionfix/.* 1.3.12rc4 a70a45f062687beb510fb3192e4227754e1dff39 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 9b71243ad..13bb67b91 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -69,7 +69,7 @@ date of first contribution): * [Philipp Baum](https://github.com/philphilphil) * [Kyle Evans](https://github.com/kevans91) * [Javier Martínez Arrieta](https://github.com/Javierma) - * ["MirceaDan"](https://github.com/ByReaL) + * [Mircea Dan Gheorghe](https://github.com/ByReaL) * [Ovidiu Hossu](https://github.com/MoonshineSG) * [Eyck Jentzsch](https://github.com/eyck) * [Mathias Rangel Wulff](https://github.com/mathiasrw) @@ -93,7 +93,26 @@ date of first contribution): * [Sven Lohrmann](https://github.com/malnvenshorn) * [Andy Castille](https://github.com/klikini) * [Zachary Nofzinger](https://github.com/ZachNo) + * [Gaston Dombiak](https://github.com/gdombiak) * [Brad Fisher](https://github.com/bradcfisher) + * [Aldo Hoeben](https://github.com/fieldofview) + * [Henning Groß](https://github.com/hgross) + * [Jubaleth](https://github.com/jubaleth) + * [Matthias Urlichs](https://github.com/smurfix) + * [Daniel Joyce](https://github.com/DanielJoyce) + * [Andy Qua](https://github.com/AndyQ) + * [Fabio Santos](https://github.com/Fabi0San) + * [Jack Wilsdon](https://github.com/jackwilsdon) + * [Ryan Finnie](https://github.com/rfinnie) + * [Timur Duehr](https://github.com/tduehr) + * [Nicolai Nielsen](https://github.com/dovecode) + * [Janne Mäntyharju](https://github.com/JanneMantyharju) + * [Steven Spungin](https://github.com/flamenco) + * [Piotr Usewicz](https://github.com/pusewicz) + * [Aliaksei Pilko](https://github.com/aliaksei135) + * [Ben Yarmis](https://github.com/byarmis) + * [Florian Heilmann](https://github.com/FHeilmann) + * [Ludovico de Nittis](https://github.com/RyuzakiKK) 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..65e22cb98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,405 @@ # OctoPrint Changelog +## 1.3.12 (2019-10-22) + +### Heads-up if you are updating from OctoPrint < 1.3.6 + +Due to new versions of third party dependencies, this and future versions of OctoPrint will no longer update via the update script/`python setup.py install` that used to be OctoPrint's standard update mechanism in versions prior to 1.3.6, at least not in older Python environments as they can be found on e.g. OctoPi 0.14. + +If you haven't yet updated from such a version ([which you really should have done a long time ago](https://octoprint.org/blog/2018/03/15/security-issue-update-to-1.3.6/)) you'll need to [update manually via command line](https://community.octoprint.org/t/how-can-i-update-the-octoprint-installation-on-my-octopi-image/207?u=foosel). + +### Heads-up if you are still running OctoPi 0.14 + +As it is becoming increasingly complicated to make OctoPrint *and its third party dependencies* run in the by now ancient Python environment found on OctoPi 0.14, **1.3.12 will no longer allow to be updated from within OctoPrint on OctoPi 0.14** or a similarly outdated Python environment. + +Either [backup](https://community.octoprint.org/t/how-do-i-backup-my-octoprint-settings-on-octopi/1489?u=foosel) and migrate to a new version of OctoPi or run future updates [manually](https://community.octoprint.org/t/how-can-i-update-the-octoprint-installation-on-my-octopi-image/207?u=foosel). + +[See here for more information on the matter](https://community.octoprint.org/t/octoprint-tells-me-it-cant-run-an-update-due-to-my-python-environment-being-outdated-what-do-i-do-now/4756?u=foosel). + +### Improvements + + * [#1239](https://github.com/foosel/OctoPrint/issues/1239) & [#3227](https://github.com/foosel/OctoPrint/pull/3227) - Add command line interface for user management. Via `octoprint user [list|add|remove|activate|deactivate|password]` it is now possible to list, add, remove, activate & deactivate users or change their passwords right from the command line instead of just through the web interface. That should also make password recovery easier and as simple as `octoprint user password username`. + * [#2896](https://github.com/foosel/OctoPrint/issues/2896) - Add confirmation dialog when removing a plugin (see also [#3179](https://github.com/foosel/OctoPrint/pull/3179)). + * [#3075](https://github.com/foosel/OctoPrint/issues/3075) - Calculate filament usage for all extruders in `M605` duplicate/mirror setup (see also [#3181](https://github.com/foosel/OctoPrint/pull/3181)). + * [#3101](https://github.com/foosel/OctoPrint/issues/3101) - Support tags on GCODE script hook and add `plugin:` to script parts from plugins. + * [#2669](https://github.com/foosel/OctoPrint/issues/2669) - Add option for disabling filters on search results in the file list (see also [#3126](https://github.com/foosel/OctoPrint/pull/3126)). + * [#3131](https://github.com/foosel/OctoPrint/pull/3131) - Allow subscribing to multiple events in one yaml based event subscription. + * [#3133](https://github.com/foosel/OctoPrint/issues/3133) - Adjust wording in case of file upload errors to also hint at permission problems. + * [#3134](https://github.com/foosel/OctoPrint/pull/3134) - Add support for logging in (and creating users) through `REMOTE_USER` header supplied by a reverse proxy in front of OctoPrint. + * [#3147](https://github.com/foosel/OctoPrint/pull/3147) - Forcelogin: Add autofocus to the username + * [#3161](https://github.com/foosel/OctoPrint/issues/3161) - Plugin manager: Reduce height of plugin list. + * [#3162](https://github.com/foosel/OctoPrint/issues/3162) - Make closing behaviour of dialogs adjustable: default behaviour is to close on click outside of dialog, this can now be disabled. + * [#3167](https://github.com/foosel/OctoPrint/pull/3167) - Make it configurable whether to perform the parity double open workaround on serial needed for (some?) debian based systems. Solves issues for FreeBSD systems & Klipper. + * [#3180](https://github.com/foosel/OctoPrint/pull/3180) - Add button to terminal tab to clear the log. + * [#3188](https://github.com/foosel/OctoPrint/issues/3188) - Suppress scary `WebSocketClosedError` messages in the log simply caused by closing the browser. + * [#3171](https://github.com/foosel/OctoPrint/issues/3171) & [#3204](https://github.com/foosel/OctoPrint/issues/3204) - Action command prompts: Add close button to prompts triggered through action commands by the firmware, in case the firmware forgets to add action buttons. + * [#3174](https://github.com/foosel/OctoPrint/issues/3174) - Include upload date & time in State panel to make file refreshs clearer. + * [#3191](https://github.com/foosel/OctoPrint/pull/3191) - Docs: Clarify that a target temperature value of 0 turns heaters off. + * [#3198](https://github.com/foosel/OctoPrint/issues/3198) - Clarify execution order of GCODE scripts. + * [#3199](https://github.com/foosel/OctoPrint/issues/3199) - Hardening against corrupt print recovery data. + * [#3203](https://github.com/foosel/OctoPrint/issues/3203) - Add documentation for `printTimeLeftOrigin` field. + * [#3206](https://github.com/foosel/OctoPrint/issues/3206) - Better resilience against garbage on the line on initial connect to the printer due to more handshake attempts. + * [#3207](https://github.com/foosel/OctoPrint/issues/3207) - Try to guess the mimetype if there is none during the webcam stream test. + * [#3218](https://github.com/foosel/OctoPrint/pull/3218) - Small refactoring in comm layer + * [#3225](https://github.com/foosel/OctoPrint/pull/3225) - Quote arguments in `pip install` to avoid issues with shells other than bash. + * [#3249](https://github.com/foosel/OctoPrint/pull/3249) & [#3263](https://github.com/foosel/OctoPrint/pull/3263) - Printer profile events are now properly triggered. + * [#3250](https://github.com/foosel/OctoPrint/issues/3250) - Add optional confirmation dialog for starting a print. + * [#3271](https://github.com/foosel/OctoPrint/issues/3271) - Extend safemode to also disable third party language packs + * Make emergency codes configurable. + * Detect endless resend requests of the same line. If the printer keeps requesting the same line over and over again, something is either seriously wrong with the line or with the connection. In any case, log an error and disconnect. + * Send `M112` on disconnect due to an error (configurable) to try to disable heaters and such. + * More type annotations throughout the code. + * Re-add missing `minHeight` support to modals. + * Ensure line breaks on copy of terminal contents. + * Error Tracking: Further limit events that go out, this time by fqcn of callback methods, if needed. + * GCODE viewer: Increase logging. + * Plugin Manager: Prevent plugin installs while throttled due to undervoltage or overheating. + * Software Update: Consider an empty restart command an unset one. + * Software Update: Prevent updates while throttled due to undervoltage or overheating. + * Tracking: Track plugins & versions once every 24h. This is a feature requested repeatedly by plugin developers and will also allow the compilation of something like a Top-10-list. + * Tracking: Track slicing events + +### Bug fixes + + * [#3022](https://github.com/foosel/OctoPrint/issues/3022) & [#3236](https://github.com/foosel/OctoPrint/issues/3236) - Ignore `NaN` and `Inf` values in GCODE analysis result, don't allow `NaN` on APIs. + * [#3095](https://github.com/foosel/OctoPrint/issues/3095) - Fix a small error in the frontend through bootstrap update. + * [#3096](https://github.com/foosel/OctoPrint/issues/3096) - Fix handling of `Empty` exception in send loop. + * [#3104](https://github.com/foosel/OctoPrint/issues/3104) - `M112` and other emergency codes must *always* jump the internal command queue even when printing and be sent immediately. + * [#3107](https://github.com/foosel/OctoPrint/issues/3107) - Prevent issues if `hash` field on file metadata is unset. + * [#3109](https://github.com/foosel/OctoPrint/issues/3109) - Fix some unicode issues on the API. + * [#3114](https://github.com/foosel/OctoPrint/issues/3114) - Virtual printer: Fix handling of closed connection. + * [#3137](https://github.com/foosel/OctoPrint/issues/3137) - Do not invert axes in GCODE viewer. The axis inversion is only relevant to the control panel (depends on how the print head is positioned), NOT the rendition of the GCODE. + * [#3142](https://github.com/foosel/OctoPrint/issues/3142) - Only do autologin if not actively logged out. + * [#3143](https://github.com/foosel/OctoPrint/issues/3143) - Fix layers vanishing from GCODE viewer on settings access. + * [#3153](https://github.com/foosel/OctoPrint/issues/3153) - Fix wrong variable name in an exception handler. + * [#3154](https://github.com/foosel/OctoPrint/issues/3154) - Strip interface tags from IPv6 addresses in local address check. + * [#3155](https://github.com/foosel/OctoPrint/issues/3155) - Backup: Make sure `exclude` is always a list. + * [#3156](https://github.com/foosel/OctoPrint/issues/3156) - Tracking: Fix error if tracked time is `None`. + * [#3157](https://github.com/foosel/OctoPrint/issues/3157) - Plugin manager: Better handling of unexpected repository format (e.g. in case of a misconfigured repository URL). + * [#3166](https://github.com/foosel/OctoPrint/issues/3166) & [#3211](https://github.com/foosel/OctoPrint/issues/3211) - Fix caching behaviour in case of active wizards. + * [#3171](https://github.com/foosel/OctoPrint/issues/3171) - Action command prompts: Remove prompts on disconnect from the printer. + * [#3176](https://github.com/foosel/OctoPrint/issues/3176) - Forcelogin: Don't touch static endpoints. + * [#3177](https://github.com/foosel/OctoPrint/issues/3177) - Always report all tools in shared nozzle setups to avoid inconsistencies. + * [#3190](https://github.com/foosel/OctoPrint/issues/3190) - Plugin Manager: Refresh the repository list on cache timeout, not just on server restart and/or connectivity events. + * [#3194](https://github.com/foosel/OctoPrint/issues/3194) & [#3196](https://github.com/foosel/OctoPrint/issues/3196) - Fix typo causing a `KeyError` on starting a second consecutive print of a file (see also [#3195](https://github.com/foosel/OctoPrint/pull/3195)). + * [#3217](https://github.com/foosel/OctoPrint/pull/3217) - Docs: Fix typo in chambers documentation + * [#3220](https://github.com/foosel/OctoPrint/issues/3220) - Fix `_long_running_command` flag for `M191` on comm layer. + * [#3224](https://github.com/foosel/OctoPrint/issues/3224) - Fix file selection not being cleared in the frontend on printer disconnect. + * [#3247](https://github.com/foosel/OctoPrint/issues/3247) - Fix scoping issue in JavaScript for custom commands with `javascript`/`enabled` fields. + * [#3253](https://github.com/foosel/OctoPrint/issues/3253) - Software Update: Fix error in python version detection (see also [#3256](https://github.com/foosel/OctoPrint/pull/3256)). + * [#3257](https://github.com/foosel/OctoPrint/issues/3257) - Appkeys: Ignore empty username on `request` endpoint to avoid later issues. + * [#3270](https://github.com/foosel/OctoPrint/issues/3270) - Properly escape translation strings in single/double quoted template locations + * [#3272](https://github.com/foosel/OctoPrint/issues/3272) (regression) - GCODE viewer: Fix out-of-sync & layer slider issue + * [#3273](https://github.com/foosel/OctoPrint/issues/3273) (regression) - Fix minimum pip version for OctoPi 0.15.1, which turns out is 9.0.3, not 10.0.1 as on OctoPi 0.15.0 due to a bug related version pin back then when. + * [#3277](https://github.com/foosel/OctoPrint/issues/3277) (regression) - GCODE viewer: Fix huge memory consumption due to misplaced deep clone. + * [#3282](https://github.com/foosel/OctoPrint/issues/3282) (regression) - Don't trigger `M112` routine for firmware errors on a connection error when no connection has even been established yet. * Fix broken filtering of valid tools + * Properly clear out user data from user management dialogs + * Appkeys: Fix handling of empty request body, should return `400 Bad Request` instead of `500 Internal Server Error`. + * Printer safety: Anycubic 1.1.2 is already safe (off by one error, used to only detect >1.1.2 instead of >=1.1.2) + +### Special thanks to all the contributors! + +Special thanks to everyone who contributed to this release and provided full, analyzable bug reports and pull requests, especially [@aliaksei135](https://github.com/aliaksei135), [@AndyQ](https://github.com/AndyQ), [@dmweis](https://github.com/dmweis), [@esver](https://github.com/esver), [@gdombiak](https://github.com/gdombiak), [@jackwilsdon](https://github.com/jackwilsdon), [@JanneMantyharju](https://github.com/JanneMantyharju), [@kevans91](https://github.com/kevans91), [@pusewicz](https://github.com/pusewicz), [@rfinnie](https://github.com/rfinnie) and [@tduehr](https://github.com/tduehr) for their PRs. + +### More information + + * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.11...1.3.12) + * Release Candidates: + * [1.3.12rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.12rc1) + * [1.3.12rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.12rc2) + * [1.3.12rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.12rc3) + * A big **Thank you!** to everyone who reported back on these release candidates this time: [@arhi](https://github.com/arhi), [@b-morgan](https://github.com/b-morgan), [@EddyMI3d](https://github.com/EddyMI3d), [@ejjenkins](https://github.com/ejjenkins), [@fieldOfView](https://github.com/fieldOfView), [@gcnix](https://github.com/gcnix), [@gege2b](https://github.com/gege2b), [@gryzlov](https://github.com/gryzlov), [@Guilouz](https://github.com/Guilouz), [@JohnOCFII](https://github.com/JohnOCFII), [@kazibole](https://github.com/kazibole), [@louispires](https://github.com/louispires), [@rknobbe](https://github.com/rknobbe), [@schnello](https://github.com/schnello) + +## 1.3.11 (2019-05-14) + +### Heads-up: 1.3.11 unbundles the Cura plugin + +If you rely on the Cura Plugin for your workflow that so far was bundled with OctoPrint, be sure to install the [Cura Legacy plugin](https://github.com/OctoPrint/OctoPrint-CuraLegacy) that's now also [available on the plugin repository](https://plugins.octoprint.org/plugins/curalegacy/). + +Once installed the Cura Legacy plugin will import the settings and profiles from the former bundled Cura plugin automatically on first start. + +### Improvements + + * [#1938](https://github.com/foosel/OctoPrint/issues/1938) - Allow slicing parallel to printing on machines with more than one core. + * [#2462](https://github.com/foosel/OctoPrint/issues/2462) - Also scan and process watched folder on startup, not just during runtime. + * [#2900](https://github.com/foosel/OctoPrint/pull/2900) - Add new hook `octoprint.printer.sdcardupload` to allow plugins to override default way to upload files to the printer's SD card. + * [#2904](https://github.com/foosel/OctoPrint/issues/2904) - Added new command line switches `-4` and `-6` to restrict binding of the server to IPv4 or v6 respectively. + * [#2905](https://github.com/foosel/OctoPrint/issues/2905) - Use maximum of communication & temperature timeout as serial timeout to avoid issues if the user has set a longer temperature reporting interval than (busy) communication timeout. + * [#2945](https://github.com/foosel/OctoPrint/issues/2945) - Adjust default regex for filtering temperature requests and responses to not filter some `M115` responses as well. New regex is `(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+((P|B|N)\d+\s+)*)?(B|T\d*):\d+)`. If you modified your terminal filters you'll have to update that manually. + * [#2947](https://github.com/foosel/OctoPrint/issues/2947) - Printer safety check plugin: Disable warning for Monoprice Select Mini V2 with firmware v4.1+. + * [#2953](https://github.com/foosel/OctoPrint/issues/2953) - GCODE Viewer: Bring back the total number of printed layers. + * [#2962](https://github.com/foosel/OctoPrint/issues/2962) - Logging: deletion confirmation and bulk delete for log file management. + * [#2965](https://github.com/foosel/OctoPrint/issues/2965) - Add new hook `octoprint.events.register_custom_events` to allow plugins to cleanly add custom events by plugins. + * [#2970](https://github.com/foosel/OctoPrint/issues/2970) - Add configurable list of commands that should never be sent to the printer, and a configurable list of commands on which OctoPrint should pause the current print job. Allows more granular configuration of behaviour of `M0`, `M1` and `M25`. + * [#2974](https://github.com/foosel/OctoPrint/issues/2974) - Dedicated checkboxes to enable/disable webcam & timelapse functionality instead of relying on empty URLs. + * [#2976](https://github.com/foosel/OctoPrint/issues/2976) - Correctly identify v6 representations of v4 networks for auto login. Also correctly identify `::1` as local network. + * [#2978](https://github.com/foosel/OctoPrint/pull/2978) - Use module name instead of plugin identifier when loading plugins from entry points. Also load bundled plugins under `octoprint.plugins.*` instead of their identifier. + * [#2982](https://github.com/foosel/OctoPrint/issues/2982) - Log user activity of who started/paused/resumed/cancelled the current print. Include `owner` of a print job in event data and log. + * [#2983](https://github.com/foosel/OctoPrint/issues/2983) - Add clear button to filter box in file list. + * [#2986](https://github.com/foosel/OctoPrint/pull/2986) - Forcelogin plugin: Make login page responsive. + * [#2988](https://github.com/foosel/OctoPrint/issues/2988) - Add `--disable-pip-version-check` to pip calls to stop pip's tendency to confuse people with it's update nag messages. + * [#2997](https://github.com/foosel/OctoPrint/issues/2997) - Forcelogin plugin: Accept authentication through API key and/or authorization headers. + * [#3010](https://github.com/foosel/OctoPrint/pull/3010) - Add usage information for all folders to the API. + * [#3014](https://github.com/foosel/OctoPrint/issues/3014) - Hardening against corrupt language packs. + * [#3023](https://github.com/foosel/OctoPrint/issues/3023) - Hardening against corrupt preemptive caching configurations. + * [#3030](https://github.com/foosel/OctoPrint/issues/3030) - Backup plugin: Change name of generated backup file to have an `octoprint-` prefix. See also [#3039](https://github.com/foosel/OctoPrint/pull/3039). + * [#3033](https://github.com/foosel/OctoPrint/issues/3033) - Open serial port in exclusive mode. See also [#3036](https://github.com/foosel/OctoPrint/pull/3036). + * [#3038](https://github.com/foosel/OctoPrint/issues/3038) - Detect Klipper firmware and adjust serial communication settings accordingly. + * [#3040](https://github.com/foosel/OctoPrint/issues/3040) - Add setting to disable fuzzy estimation display in the UI. + * [#3049](https://github.com/foosel/OctoPrint/issues/3049) - Workaround for broken PEP440 non-compliant Python version numbers under Debian. See also [#3054](https://github.com/foosel/OctoPrint/pull/3054). + * [#3051](https://github.com/foosel/OctoPrint/pull/3051) - Always show unfuzzy total print time and print left in a tooltip. + * [#3055](https://github.com/foosel/OctoPrint/pull/3055) - GCODE Viewer: Add ability to preview the current layer to be drawn. + * [#3057](https://github.com/foosel/OctoPrint/issues/3057) - Performance improvements in file management operations & more aggressive cleanup of stale metadata. + * [#3066](https://github.com/foosel/OctoPrint/pull/3066) - Docs: Add missing documentation about state in `jobs` endpoint on API. + * [#3072](https://github.com/foosel/OctoPrint/pull/3072) - Hide temperature tab for machines with neither heated bed nor extruders. + * [#3073](https://github.com/foosel/OctoPrint/pull/3073) - Hide tool section in "Control" tab for machines with no extruders. + * [#3074](https://github.com/foosel/OctoPrint/issues/3074) - Updated several dependencies to newer versions. + * Add elapsed time and reason for failure to `PrintFailed` event. + * Add `trigger_event` parameter to `Settings.save` and `PluginSettings.save` to trigger `SettingsUpdated` event on save of settings. + * Simplify configuration change handling of wizards. + * Minimum Python version is now 2.7.9. + * Create a backup of working `config.yaml` after successful startup. + * Detect incomplete startups and set safe mode flag for next startup. + * Always show actual temperature as received from printer instead of "off" for very low temperatures. That way people will hopefully no longer blame OctoPrint for MINTEMP errors triggered by their firmware because it "can't handle temperatures under 10°C". + * Add full version string `OctoPrint ` to API. + * Add systemd unit file. + * Deprecate appkey API in favor of new bundled Application Keys Plugin. AFAIK was never used by anyone anyhow. + * Take bundle status into account for plugin sorting, bundled plugins should always win before not bundled plugins if no sorting key is provided. + * Load generic templates after JavaScript assets, making it possible to reference already loaded libraries in any injected generic templates. + * Hardening against callback errors in decorators on default view. + * Unbundled the Cura plugin. It lives on as "Cura Legacy" at [OctoPrint/OctoPrint-CuraLegacy](https://github.com/OctoPrint/OctoPrint-CuraLegacy) and will also be available on the plugin repository. + * Hardening against invalid SD status reports. + * Cleanup now obsolete `metadata.yaml` files. + * Use `monotonic_time` for relative times everywhere. + * Support for heated chamber firmware capabilities. + * Remove `UI_API_KEY` and API disabling. With the inclusion of the ForceLogin plugin that doesn't serve a real purpose anymore in most cases, and it was only ever more of a rate limiting feature than an actual security measure anyhow. Plus it lead to a ton of false security alarms. + * More resilience against broken configurations. + * More resilience against platform startup issues during environment detection. + * Don't confuse users with current `pip`'s "Python 2.7 is EOL" messages + * Define empty `UI_API_KEY` for backwards compatibility with third party plugins + * Add config flag `server.ignoredIncompleteStartup` to override incomplete startup detection + * Hardening against errors triggered during print time estimation + * Introduce setting to disable exclusive claim on serial port. There might be issues with this out there in the field, so having the option to disable it is a good thing. + * Docs: Improve docs of connection API to avoid issues as encountered in [#3043](https://github.com/foosel/OctoPrint/issues/3043). + * Action Command Prompt plugin: Set `M876` as default command as discussed in [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982). + * Action Command Prompt plugin: Add `M876` to `EMERGENCY_PARSER` compliant commands, if configured accordingly. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982). + * Action Command Prompt plugin: Signal support for action command prompts to firmware via `M876 P1`, if configured accordingly. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982). + * Action Command Prompt plugin: Properly handle `PROMPT_SUPPORT` capability report from firmware and configure action command prompt support accordingly. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982). + * Error Tracking plugin: New plugin utilizing [sentry.io](https://sentry.io) to track any kind of errors thrown in either backend or the default UI. Will ship disabled by default, has to be enabled by the user. Release Candidates will prompt users to enable it in order to improve on error detection during RC phase. + * Error Tracking: Severely restrict what gets tracked: + * we are only interested in handled core exceptions or unhandled exceptions + * we are not interested at all in `SerialException` + * Error Tracking: Further restriction of what gets tracked + * Forcelogin plugin: Set sorting key to 0 to increase likelihood of coming before alternative UIs. + * Forcelogin plugin: Add favicon meta tags. + * Plugin Manager plugin, Softwareupdate plugin: Use scrollables instead of pagination. + * Printer Safety Check plugin: Add version restriction to Anycubic check. + * Tracking plugin: Add elapsed time and reason for failure to `print_failed` event. + * Tracking plugin: Add elapsed time to `print_cancelled` event. + * Tracking plugin: Track firmware/communication errors. + * Tracking plugin: Track printer safety warnings. + * Tracking plugin: Track uptime of OctoPrint in `ping` event. + +### Bug fixes + + * [#1881](https://github.com/foosel/OctoPrint/issues/1881) - Another attempt at fixing the hard to intentionally reproduce issue where all API endpoints start returning `403` responses. Caching headers have been adjusted and API key handling has been changed, which might fix things. + * [#2859](https://github.com/foosel/OctoPrint/issues/2859) - Fix for used port and baudrate to not be properly reflected on the UI. + * [#2916](https://github.com/foosel/OctoPrint/issues/2916) - Possible workaround for a rare issue with the bundled Tornado dependency when running OctoPrint under Windows. + * [#2954](https://github.com/foosel/OctoPrint/issues/2954) - Backup plugin: Fix an issue with calculation of available free space. + * [#2955](https://github.com/foosel/OctoPrint/issues/2955) - Fix handling of `action:resume` or `action:resumed` received during `PAUSING` and handling of `action:pause` or `action:paused` received during `RESUMING`. Fix `PAUSING` state not allowing a resume to proceed. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982). + * [#2959](https://github.com/foosel/OctoPrint/issues/2959) - Enforce max height smaller than available viewport for notifications so that they cannot scroll out of the screen. + * [#2967](https://github.com/foosel/OctoPrint/issues/2967) - Tracking plugin: Fix exception caused on printer events when tracking is disabled and no UUID is thus set. + * [#2971](https://github.com/foosel/OctoPrint/issues/2971) - Forcelogin plugin: Fix "remember me" not working as advertised. See also [#2973](https://github.com/foosel/OctoPrint/pull/2973). + * [#2992](https://github.com/foosel/OctoPrint/issues/2992) - Backup plugin: Use `shutil.move` instead of `os.rename` and thus avoid issues with certain filesystem configurations. See also [#2993](https://github.com/foosel/OctoPrint/pull/2993). + * [#2996](https://github.com/foosel/OctoPrint/issues/2996) - Use non-blocking writes on serial communication to avoid `select` blocking issues under certain conditions. See also [#3004](https://github.com/foosel/OctoPrint/pull/3004). + * [#3001](https://github.com/foosel/OctoPrint/issues/3001) - Fix a race condition in SD printing detection. + * [#3012](https://github.com/foosel/OctoPrint/issues/3012) - Fix a unicode vs ASCII bug in translating plugins. + * [#3024](https://github.com/foosel/OctoPrint/issues/3024) - Fix inconsistent behaviour of CORS support on the API regarding static routes and the socket. + * [#3029](https://github.com/foosel/OctoPrint/issues/3029) & [#3045](https://github.com/foosel/OctoPrint/pull/3045) & [#3061](https://github.com/foosel/OctoPrint/issues/3061) - Fix issues in the German translation + * [#3053](https://github.com/foosel/OctoPrint/pull/3053) - GCODE Viewer: Fix an issue with multi extruder files where only a higher extruder index is actually used and all prior ones are undefined. + * [#3080](https://github.com/foosel/OctoPrint/issues/3080) - Virtual Printer plugin: Fix tracking of negative movements and homing. + * [#3071](https://github.com/foosel/OctoPrint/issues/3071) - Application Keys plugin: Fix appkeys not working when access control is disabled. + * [#3088](https://github.com/foosel/OctoPrint/issues/3088) (regression) - Fix 500 error on index rendering in case of plugins that use unicode in plugin vars. + * [#3089](https://github.com/foosel/OctoPrint/issues/3089) (regression) - Fix missing `_chamberTemp` definition + * [#3090](https://github.com/foosel/OctoPrint/issues/3090) (regression) - Fix missing method causing an exception on `/api/printer/tool` endpoint + * [#3091](https://github.com/foosel/OctoPrint/issues/3091) (regression) - Printer Safety Check: Fix unicode errors in certain communication scenarios. + * [#3092](https://github.com/foosel/OctoPrint/issues/3092) - Fix invalid tool parameter detection on `/api/printer/tool` endpoint. + * [#3098](https://github.com/foosel/OctoPrint/issues/3098) - Backup: Exclude temporary timelapse files as well if timelapses are excluded from backup. + * [#3105](https://github.com/foosel/OctoPrint/issues/3105) (regression) - Virtual printer: Fix an encoding issue + * [#3108](https://github.com/foosel/OctoPrint/issues/3108) (regression) - Fix bug in port detection + * [#3111](https://github.com/foosel/OctoPrint/issues/3111) (regression) - Refresh port list after disconnect to detect vanishing ports + * [#3115](https://github.com/foosel/OctoPrint/issues/3115) (regression) - Fix extra newlines in `serial.log` and empty lines on terminal + * [#3116](https://github.com/foosel/OctoPrint/issues/3116) - Fix potential division by zero + * Fix a typo in an error message during startup. + * `paused` action command must not trigger *any* local processing. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982). + * Only use page size from local storage in `ItemListHelper` if configured. + * Fix caching headers on main view. + * Fix missing default value for `self._errorValue` in comm layer. + * Don't read return code on async system commands, it won't work. + * Fix wrong textual representation of `STARTING` state + * Fix some potential encoding errors in the comm layer + * Fix for the file list in the UI not getting refreshed after an SD list refresh from the printer. + * Docs: Fix documentation for firmware info & capability plugin hooks. + * Docs: Fix a formatting issue in the event docs, making it seem like events were deprecated when it was only payload entries that are deprecated. + * Forcelogin plugin: Never handle the UI if ACL is disabled. + * Tracking plugin: Fix tracking not starting fully if enabled during runtime. + * Tracking plugin: Fix handling of missing print time. See also [#3063](https://github.com/foosel/OctoPrint/issues/3063). + +### Special thanks to all the contributors! + +Special thanks to everyone who contributed to this release, especially [@agrif](https://github.com/agrif), [@akraus53](https://github.com/akraus53), [@AndyQ](https://github.com/AndyQ), [@CapnBry](https://github.com/CapnBry), [@DanielJoyce](https://github.com/DanielJoyce), [@devildant](https://github.com/devildant), [@Fabi0San](https://github.com/Fabi0San), [@fake-name](https://github.com/fake-name), [@fieldOfView](https://github.com/fieldOfView), [@gloomyandy](https://github.com/gloomyandy), [@HarlemSquirrel](https://github.com/HarlemSquirrel), [@hgross](https://github.com/hgross), [@jubaleth](https://github.com/foosel/OctoPrint/commits?author=jubaleth), [@melgish](https://github.com/melgish), [@rgriebl](https://github.com/rgriebl) and [@tedder](https://github.com/tedder) for their PRs. + +### More information + + * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.10...1.3.11) + * Release Candidates: + * [1.3.11rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.11rc1) + * [1.3.11rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.11rc2) + * [1.3.11rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.11rc3) + * A big **Thank you!** to everyone who reported back on these release candidates this time: [@arhi](https://github.com/arhi), [@b-morgan](https://github.com/b-morgan), [@CRCinAU](https://github.com/CRCinAU), [@devildant](https://github.com/devildant), [@evanquinnalaska](https://github.com/evanquinnalaska), [@FormerLurker](https://github.com/FormerLurker), [@gege2b](https://github.com/gege2b), [@isbric](https://github.com/isbric), [@JohnOCFII](https://github.com/JohnOCFII), [@kazibole](https://github.com/kazibole), [@nionio6915](https://github.com/nionio6915), [@reloxx13](https://github.com/reloxx13), [@schnello](https://github.com/schnello), [@trunzoc](https://github.com/trunzoc), [@vfrdirk](https://github.com/vfrdirk) & [@zeroflow](https://github.com/zeroflow) + +## 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**. @@ -420,7 +813,7 @@ You can find out more about the change, how to know if a plugin is even affected * Make timeout after which to unload the webcam stream after navigating away from it configurable (as suggested in [#1937](https://github.com/foosel/OctoPrint/issues/1937)) * Add `ToolChange` event and tool change GCODE scripts * Support parsing GCODE subcodes. - * Add `octoprint.users.factory` hook, allowing plugins to extend/swap out the user manager OctoPrint uses. + * Add `octoprint.access.users.factory` hook, allowing plugins to extend/swap out the user manager OctoPrint uses. * Corewizard: Disable view model and client code if it's not actually required. * Corewizard: Disable injection of JS files into UI when it's not actually required. * GCODE analysis: Moved into its own subprocess. That should improve performance on multi core systems. @@ -885,1019 +1278,6 @@ If you are running OctoPi, this does **not** apply to you and you do not need to * [1.3.0rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.0rc2) * [1.3.0rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.0rc3) -## 1.2.18 (2016-11-30) +--- -### Improvements - - * Allow arbitrary frame rates for creating timelapses. Before, the entered fps value was also directly used as frame rate for the actual video, which could cause problems with any frame rates not specified in the MPEG2 standard. Now OctoPrint will use a standard frame rate for the rendered video and render the timelapse stills into the finished movie with the configured frame rate. - * Limited Cura profile importer to `.ini` files and clarified the supported versions - * Add support for the `R` parameter for `M109` and `M190` - -### Bug fixes - - * [#1541](https://github.com/foosel/OctoPrint/issues/1541) - Fix selecting the printer profile to use by default - * [#1543](https://github.com/foosel/OctoPrint/issues/1543) - Fix target temperature propagation from communication layer - * [#1567](https://github.com/foosel/OctoPrint/issues/1567) - Fix issue with restricted settings getting parsed to the wrong data structure in the frontend if loaded anonymously first. - * [#1571](https://github.com/foosel/OctoPrint/issues/1571) - Fix parsing of port number from HTTP Host header for IPv6 addresses - * Fix issue with settings restriction causing internal settings defaults to be changed. - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.2.17...1.2.18) - * Release Candidates: - * [1.2.18rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.18rc1) - -## 1.2.17 (2016-11-08) - -### Improvements - - * Files like `config.yaml` etc will now persist their permissions, with a lower and upper permission bounds for sanitization (e.g. removing executable flags on configuration files but keeping group read/write permissions if found). - * Log full stack trace on socket connection errors when debug logging for `octoprint.server.util.sockjs` is enabled - * ``SettingsPlugin``s may now mark configuration paths as restricted so that they are not returned on the REST API - * Updated LESS.js version - * Improved the `serial.log` logging handler to roll over serial log on new connections to the printer instead of continuously appending to the same file. Please note that `serial.log` is a debugging tool only and should *not* be left enabled unless you are trying to troubleshoot something in your printer communication. - * Split JS/CSS/LESS asset bundles according into asset bundles for core + bundled plugins ("packed_core.{js|css|less}") and third party plugins ("packed_plugins.{js|css|less}"). That will allow the core UI to still function properly even if an installed third party plugin produces invalid JS and therefore causes a parser error for the whole plugin JS file. See [#1544](https://github.com/foosel/OctoPrint/issues/1544) for an example of such a situation. - -### Bug fixes - - * [#1531](https://github.com/foosel/OctoPrint/issues/1531) - Fixed encoding bug in HTTP request processing triggered by content type headers on form data fields - * Fixed forced `config.yaml` save on startup caused by mistakenly assuming that printer parameters were always migrated. - * Fixed issue causing ``remember_me`` cookie not to be deleted properly on logout - * Fixed broken filter toggling on ``ItemListHelper`` class used for various lists throughout the web interface - * Fixed an issue with the preliminary page never reporting that the server is now up if the page generated during preliminary caching had no cache headers set (e.g. because it contained the first run setup wizard) - * Fixed a bug causing the update of OctoPrint to not work under certain circumstances: If 1.2.16 was installed and the settings were *never* saved via the "Settings" dialog's "Save", the update of OctoPrint would fail due to a `KeyError` in the updater. Reason is a renamed property, properly switched to when saving the settings. - * Fixed the logging subsystem to properly clean up after itself. - * Fixed a wrong order in loading JS files on the client introduced in 1.2.17rc2 to make the UI more resilient against broken plugin JS. - * Properly handle empty JS file list from plugins. Solves a 500 on OctoPrint instances without any third party plugins installed generated during web asset bundling introduced in 1.2.17rc2. - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.2.17) - * Release Candidates: - * [1.2.17rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc1) - * [1.2.17rc2](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc2) - * [1.2.17rc3](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc3) - * [1.2.17rc4](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc4) - -## 1.2.16 (2016-09-23) - -### Improvements - - * [#1434](https://github.com/foosel/OctoPrint/issues/1434): Make sure to sanitize any file names in the upload folder that do not match OctoPrint's file name "sanitization standard" automatically when creating a file listing. This should solve issues with UI functionality like selecting a file for printing or deleting a file to not work with files that were uploaded manually to the ``uploads`` folder. As a side note: Please don't do this, use the ``watched`` folder if you want to SCP/FTP/copy files directly to OctoPrint. - * [#1434](https://github.com/foosel/OctoPrint/issues/1434): Allow `[` and `]` in uploaded file names. - * [#1481](https://github.com/foosel/OctoPrint/issues/1481): Bring back non-fuzzy layer time estimates in the GCODE viewer. - * Improved fuzzy print time displays in the frontend. Rounding now takes overall duration into account - durations over a day will be rounded up/down to half days, durations over an hour will be rounded up/down to half hours, durations over 30min will be rounded to 10min segments, durations below 30min will be rounded up or down to the next minute depending on the seconds and finally if we are talking about less than a minute, durations over 30s will return "less than a minute", durations under 30s will return "a couple of seconds". - * Improved intermediary loading page: Don't report server as ready and reload until preliminary caching has been done, IF preliminary caching will be done. - * Added release channels to OctoPrint's bundled Software Update plugin. You will now be able to subscribe to OctoPrint's `maintenance` or `devel` release candidates in addition to stable versions. [Read more about Release Channels on the wiki](https://github.com/foosel/OctoPrint/wiki/Using-Release-Channels). - * Return a "400 Bad Request" instead of a "500 Internal Server Error" if a `multipart/form-data` request (e.g. a file upload) is sent which lacks the `boundary` field. - -### Bug Fixes - - * [#1448](https://github.com/foosel/OctoPrint/issues/1448): Don't "eat" first line of the pause script after a pause triggering `M0` but send it to the printer instead - * [#1477](https://github.com/foosel/OctoPrint/issues/1477): Only report files enqueued for analysis which actually are (as in, don't claim to have queued STL files for GCODE analysis) - * [#1478](https://github.com/foosel/OctoPrint/issues/1478): Don't display inaccurate linear estimate ("6 days remaining") until 30 *minutes* have passed, even if nothing else is available. Potentially related to [#1428](https://github.com/foosel/OctoPrint/issues/1428). - * [#1479](https://github.com/foosel/OctoPrint/issues/1479): Make sure set cookies are post fixed with a port specific suffix and that the path they are set on takes the script root from the request into account. - * [#1483](https://github.com/foosel/OctoPrint/issues/1483): Filenames in file uploads may also now be encoded in ISO-8859-1, as defined in [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2.4). Solves an issue when sending files with non-ASCII-characters in the file name from Slic3r. - * [#1491](https://github.com/foosel/OctoPrint/issues/1491): Fixed generate/delete API key in the user settings - * [#1492](https://github.com/foosel/OctoPrint/issues/1492): Fixed a bug in the software update plugin depending on the presence of the ``prerelease`` flag which is only present when added manually or using a non stable release channel. - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.2.15...1.2.16) - * Release Candidates: - * [1.2.16rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.16rc1) - * [1.2.16rc2](https://github.com/foosel/OctoPrint/releases/tag/1.2.16rc2) - -## 1.2.15 (2016-07-30) - -### Improvements - - * [#1425](https://github.com/foosel/OctoPrint/issues/1425) - Added a compatibility work around for plugins implementing the [`octoprint.comm.transport.serial_factory` hook](http://docs.octoprint.org/en/master/plugins/hooks.html#octoprint-comm-transport-serial-factory) but whose handler's `write` method did not return the number of written bytes (e.g. [GPX plugin including v2.5.2](http://plugins.octoprint.org/plugins/gpx/), [M33 Fio plugin including v1.2](http://plugins.octoprint.org/plugins/m33fio/)). - -### Bug Fixes - - * [#1423](https://github.com/foosel/OctoPrint/issues/1423) - Fixed an issue with certain printers dropping or garbling communication when setting the read timeout of the serial line. Removed the dynamic timeout setting introduced by [#1409](https://github.com/foosel/OctoPrint/issues/1409) to solve this. - * [#1425](https://github.com/foosel/OctoPrint/issues/1425) - Fixed an error when trying to close a printer connection that had not yet been opened and was `None` - * Fixed "Last Modified" header calculation for views where only one source file was present - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.14...1.2.15)) - -## 1.2.14 (2016-07-28) - -### Improvements - - * [#935](https://github.com/foosel/OctoPrint/issues/935) - Support alternative source file types and target extensions in [SlicerPlugins](http://docs.octoprint.org/en/master/plugins/mixins.html#slicerplugin). - * [#1393](https://github.com/foosel/OctoPrint/issues/1393) - Added dedicated sub commands on the job API to pause and resume a print job (instead of only offering a toggle option). - * Better "upload error" message with a list of supported extensions (instead of hardcoded ones) - * Use fuzzy times for print time estimation from GCODE analysis - * Allow M23 "File opened" response with no filename (RepRapPro) - * Allow intermediary startup page to forward query parameters and fragments from initial call to actual web frontend - * More error resilience when rendering templates (e.g. from plugins) - * Make sure that all bytes of a line to send to the printer have actually been sent - * "Tickle" printer when encountering a communication timeout while idle - * Report `CLOSED`/`CLOSED_WITH_ERROR` states as "Offline" in frontend for more consistency with startup `NONE` state which already was reported as "Offline" - * Another attempt at a saner print time estimation: Force linear (way less accurate) estimate if calculation of more accurate version takes too long, sanity check calculated estimate and use linear estimate if it looks wrong, improved threshold values for calculation. Read [the second half of this post on the mailing list](https://groups.google.com/forum/#!msg/octoprint/WWpm1FCUkAs/X3HomTM5DgAJ) on why accurate print time estimation is so difficult to achieve. - * Display print job progress percentage on progress bar. - * Added an indicator for print time left prediction accuracy and explanation of its origin as tooltip. - * Improved visual distinction of "State" sidebar panel info clusters. - -### Bug Fixes - - * [#1385](https://github.com/foosel/OctoPrint/issues/1385) - Send all non-protocol messages from printer to clients. - * [#1388](https://github.com/foosel/OctoPrint/issues/1388) - Track consecutive timeouts even when idle and disconnect from printer when it's not responding any longer. - * [#1391](https://github.com/foosel/OctoPrint/issues/1391) - Only use the first value from the X-Scheme header for the reverse proxy setup. Otherwise there could be problems when multiple reverse proxies were configured chained together, each adding their own header to the mix. - * [#1407](https://github.com/foosel/OctoPrint/issues/1407) - If a file is uploaded with the "print" flag set to true, make sure to clear that flag after the print job has been triggered so that now all following uploaded or selected files will start printing on their own. - * [#1409](https://github.com/foosel/OctoPrint/issues/1409) - Don't report a communication timeout after a heatup triggered by a print from SD. - * Fixed scrolling to freshly uploaded files, also now highlighting the file entry for better visibility. - * Fixed overeager preemptive caching of invalid protocols. - * Fix modal background of update confirmation not vanishing - * Ensure log entries and messages from printer are sent to frontend already converted to utf-8. Otherwise even one line in the log that can't be converted automatically without error can cause updates from the backend to not arrive. - * Report correct printer state including error strings even after disconnecting - * While printing, be sure to read the next line from file and send that if the current line was filtered - * Small fixes in the GCODE analysis - * Small fixes in the documentation - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.13...1.2.14)) - -## 1.2.13 (2016-06-16) - -### Bug Fixes - - * [#1373](https://github.com/foosel/OctoPrint/issues/1373): Don't parse `B:` as bed temperature when it shows up as part of a position report from `M114`. - * [#1374](https://github.com/foosel/OctoPrint/issues/1374): Don't try to perform a passive login when the components we'd need to inform about a change in login state aren't yet available. Solves a bug that lead - among other things - to the Plugin Manager and the Software Update Plugin not showing anything but misleading errors until the user logged out and back in. - * Fixed the temperature graph staying uninitialized until a connection to a printer was established. - * Fixed an error causing issues during frontend startup if the browser doesn't support tracking browser visibility. - * Fixed an error causing issues during frontend startup if the browser doesn't support the capabilities needed for the GCODE viewer. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.12...1.2.13)) - -## 1.2.12 (2016-06-09) - -### Improvements - - * [#1338](https://github.com/foosel/OctoPrint/issues/1338): Threshold configuration fields now include information about how to specify the thresholds. - * Mark unrendered timelapses currently being processed (recording or rendering) in the list and remove action buttons so no accidental double-processing can take place. - * Removed file extension from "rendering" and "rendered" notifications, was misleading when using the [mp4 wrapper script](https://github.com/guysoft/OctoPi/issues/184). - * Added some new events for manipulation of slicing profiles. - * Small fix of the german translation. - -### Bug Fixes - - * [#1314](https://github.com/foosel/OctoPrint/issues/1314): Do not change the extension of `.g` files being uploaded to SD (e.g. `auto0.g`) - * [#1320](https://github.com/foosel/OctoPrint/issues/1320): Allow deletion of *.mp4 timelapse files (see [this wrapper script](https://github.com/guysoft/OctoPi/issues/184)). - * [#1324](https://github.com/foosel/OctoPrint/issues/1324): Make daemonized OctoPrint properly clean up its pid file again (see also [#1330](https://github.com/foosel/OctoPrint/pull/1330)). - * [#1326](https://github.com/foosel/OctoPrint/issues/1326): Do not try to clean up an unrendered timelapse while it is already being deleted (and produce way too much logging output in the process). - * [#1343](https://github.com/foosel/OctoPrint/issues/1343): Events are now processed in the order they are fired in, making e.g. the "timelapse rendering" message always appear before "timelapse failed" and hence not stay on forever in case of a failed timelapse. - * [#1344](https://github.com/foosel/OctoPrint/issues/1344): `ProgressPlugin`s now get also notified about a progress of 0%. - * [#1357](https://github.com/foosel/OctoPrint/issues/1357): Fixed wrongly named method call on editing access control options for a user, causing that to not work properly. - * [#1361](https://github.com/foosel/OctoPrint/issues/1361): Properly reload profile list for currently selected slicer in the slicing dialog on change of profiles. - * [#1364](https://github.com/foosel/OctoPrint/issues/1364): Fixed a race condition that could cause the UI to not initialize correctly due to 401 errors, leaving it in an unusable state until a reload. - * Fixed concurrent message pushing to the frontend being able to break push messages for the session by forcing synchronization of SockJS message sending. - * Do not require admin rights for connecting/disconnecting, like it was in 1.1.x (note that this is supposed to become configurable behaviour once [#1110](https://github.com/foosel/OctoPrint/issues/1110) gets implemented) - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.11...1.2.12)) - -## 1.2.11 (2016-05-04) - -### Important Announcement - -Due to a recent change in the financial situation of the project, the funding of OctoPrint is at stake. If you love OctoPrint and want to see its development continue at the pace of the past two years, please read on about its current funding situation and how you can help: ["I need your support"](http://octoprint.org/blog/2016/04/13/i-need-your-support/). - -### Improvements - - * Added option to treat resend requests as `ok` for such firmwares that do not send an `ok` after requesting a resend. If you printer communication gets stalled after a resend request from the firmware, try checking this option. - * Added an "About" dialog to properly inform about OctoPrint's license, contributors and supporters. - * Added a announcement plugin that utilizes the RSS feeds of the [OctoPrint Blog](http://octoprint.org/blog/) and the [plugin repository](http://plugins.octoprint.org) to display news to the user. By default only the "important announcement" category is enabled. This category will only be used for very rare situations such as making you aware of critical updates or important news. You can enable further categories (with more announcements to be expected) in the plugin's settings dialog. - -### Bug Fixes - - * [#1300](https://github.com/foosel/OctoPrint/issues/1300) - Removed possibility to accidentally disabling local file list by first limiting view to files from SD and then disabling SD support. - * [#1315](https://github.com/foosel/OctoPrint/issues/1315) - Fixed broken post roll on z-based timelapses. - * Fixed CSS data binding syntax on the download link in the files list - * Changed control distance from jQuery data into a knockout observerable and observerableArray - * Allow an unauthorized user to logout from a logedin interface state - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.10...1.2.11)) - -## 1.2.10 (2016-03-16) - -### Improvements - - * Improved performance of console output during plugin installation/deinstallation - * Slight performance improvements in the communication layer - * Log small log excerpt to `octoprint.log` upon encountering a communication error. - * Changed wording in "firmware error" notifications to better reflect that there was an error while communicating with the printer, since the error condition can also be triggered by serial errors while trying to establish a connection to the printer or when already connected. - * Support downloading ".mp4" timelapse files. You'll need a [custom wrapper script for timelapse rendering](https://github.com/guysoft/OctoPi/issues/184) for this to be relevant to you. See also [#1255](https://github.com/foosel/OctoPrint/pull/1255) - * The communication layer will now wait up to 10s after clicking disconnect in order to send any left-over lines from its buffers. - * Moved less commonly used configuration options in Serial settings into "Advanced options" roll-out. - -### Bug Fixes - - * [#1224](https://github.com/foosel/OctoPrint/issues/1224) - Fixed an issue introduced by the fix for [#1196](https://github.com/foosel/OctoPrint/issues/1196) that had the "Upload to SD" button stop working correctly. - * [#1226](https://github.com/foosel/OctoPrint/issues/1226) - Fixed an issue causing an error on disconnect after or cancelling of an SD print, caused by the unsuccessful attempt to record print recovery data for the file on the printer's SD card. - * [#1268](https://github.com/foosel/OctoPrint/issues/1268) - Only add bed temperature line to temperature management specific start gcode in CuraEngine invocation if a bed temperature is actually set in the slicing profile. - * [#1271](https://github.com/foosel/OctoPrint/issues/1271) - If a communication timeout occurs during an active resend request, OctoPrint will now not send an `M105` with an increased line number anymore but repeat the last resent command instead. - * [#1272](https://github.com/foosel/OctoPrint/issues/1272) - Don't add an extra `ok` for `M28` response. - * [#1273](https://github.com/foosel/OctoPrint/issues/1273) - Add an extra `ok` for `M29` response, but only if configured such in "Settings" > "Serial" > "Advanced options" > "Generate additional ok for M29" - * [#1274](https://github.com/foosel/OctoPrint/issues/1274) - Trigger `M20` only once after finishing uploading to SD - * [#1275](https://github.com/foosel/OctoPrint/issues/1275) - Prevent `M105` "cascade" due to communication timeouts - * Fixed wrong tracking of extruder heating up for `M109 Tn` commands in multi-extruder setups. - * Fixed start of SD file uploads not sending an `M110`. - * Fixed job data not being reset when disconnecting while printing. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.9...1.2.10)) - -## 1.2.9 (2016-02-10) - -### Improvements - - * [#318](https://github.com/foosel/OctoPrint/issues/318) - Snapshots for timelapses are now named in a non-colliding, job-based way, allowing a new timelapse to start while the other is still being rendered (although printing with an active timelapse rendering job is not recommended and will be solved with a proper render job queue in a later version). Timelapses that were not successfully rendered are kept for 7 days (configurable, although not via the UI so far) and can be manually rendered or deleted through a new UI component within the timelapse tab that shows up if unrendered timelapses are detected. - * [#485](https://github.com/foosel/OctoPrint/issues/485) - "Timelapse rendering" notification is now persistent, even across reloads/client switches. That should make it easier to see that a rendering job is currently in progress. - * [#939](https://github.com/foosel/OctoPrint/issues/939) - Updated to Knockout 3.4.0 - * [#1204](https://github.com/foosel/OctoPrint/issues/1204) - Display total print time as estimated by GCODE viewer on GCODE viewer tab. That will allow access to an estimate even if the server hadn't yet calculated that when a print started. Note that due to slightly different implementation server and client side the resulting estimate might differ. - * OctoPrint now serves an intermediary page upon start that informs the user about the server still starting up. Once the server is detected as running, the page automatically switches to the standard interface. - * OctoPrint now displays a link to the release notes of an updated component in the update notification, the update confirmation and the version overview in the settings dialog. Please always make sure to at least skim over the release notes for new OctoPrint releases, they might contain important information that you need to know before updating. - * Improved initial page loading speeds by introducing a preemptive cache. OctoPrint will now record how you access it and on server start pre-render the page so it's ideally available in the server-side cache when you try to access it. - * Initialize login user name and password with an empty string and clear both on successful login (see [#1175](https://github.com/foosel/OctoPrint/pull/1175)). - * Added a "Refresh" button to the file list for people who modify the stored files externally (doing this is not encouraged however due to reasons of book keeping, e.g. metadata tracking etc). - * "Save" button on settings dialog is now disabled while background tasks (getting or receiving config data from the backend) are in progress. - * Improved performance of terminal tab on lower powered clients. Adaptive rate limiting now ensures the server backs off with log updates if the client can't process them fast enough. If the client is really slow, log updates get disabled automatically during printing. This behaviour can be disabled with override buttons in the terminal tab's advanced options if necessary. - * Added option to ignore any unhandled errors reported by the firmware and another option to only cancel ongoing prints on unhandled errors from the firmware (instead of instant disconnect that so far was the default). - * Made version compatibility check PEP440 compliant (important for plugin authors). - * Do not hiccup on manually sent `M28` commands. - * Persist print recovery data on print failures (origin and name of printed file, position in file when print was aborted, time and date of print failure). Currently this data isn't used anywhere, but it [can be accessed from plugins in order to add recovery functionality](https://github.com/foosel/OctoPrint-PrintRecoveryPoc) to OctoPrint. - * Small performance improvements in update checks. - * The file upload dialog will now only display files having an extension that's supported for upload (if the browser supports it, also see [#1196](https://github.com/foosel/OctoPrint/issues/1196)). - -### Bug Fixes - - * [#1007](https://github.com/foosel/OctoPrint/issues/1007) - Don't enable the "Print" button if no print job is selected. - * [#1181](https://github.com/foosel/OctoPrint/issues/1181) - Properly slugify UTF-8 only file names. - * [#1196](https://github.com/foosel/OctoPrint/issues/1196) - Do not show drag-n-drop overlay if server is offline. - * [#1208](https://github.com/foosel/OctoPrint/issues/1208) - Fixed `retraction_combing` profile setting being incorrectly used by bundled Cura plugin (see [#1209](https://github.com/foosel/OctoPrint/pull/1209)) - * Fixed OctoPrint compatibility check in the plugin manager, could report `False` for development versions against certain versions of Python's `setuptools` (thanks to @ignaworm who stumbled over this). - * Fixed a missing parameter in `PluginSettings.remove` call (see [#1177](https://github.com/foosel/OctoPrint/pull/1177)). - * Docs: Fixed the example for a custom `M114` control to also match negative coordinates. - * Reset scroll position in settings dialog properly when re-opening it or switching tabs. - * Fixed an issue that prevented system menu entries that were added to a so far empty system menu make the menu show up. - * Fixed an issue that made requests to restricted resources fail even though the first run wizard had been completed successfully. - * Fixed an issue where an unknown command or the suppression of a command could cause the communication to stall until a communication timeout was triggered. - * Strip [unwanted ANSI characters](https://github.com/pypa/pip/issues/3418) from output produced by pip versions 8.0.0, 8.0.1 and 8.0.3 that prevents our plugin installation detection from working correctly. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.8...1.2.9)) - -## 1.2.8 (2015-12-07) - -### Notes for Upgraders - -#### A bug in 1.2.7 prevents directly updating to 1.2.8, here's what to do - -A bug in OctoPrint 1.2.7 (fixed in 1.2.8) prevents updating OctoPrint to version -1.2.8. If you try to perform the update, you will simply be told that "the update -was successful", but the update won't actually have taken place. To solve this -hen-egg-problem, a plugin has been made available that fixes said bug (through -monkey patching). - -The plugin is called "Updatefix 1.2.7" and can be found -[in the plugin repository](http://plugins.octoprint.org/plugins/updatefix127/) -and [on Github](https://github.com/OctoPrint/OctoPrint-Updatefix-1.2.7/). - -Before attempting to update your installation from version 1.2.7 to version 1.2.8, -please install the plugin via your plugin manager and restart your server. Note that -you will only see it in the Plugin Manager if you need it, since it's only compatible with -OctoPrint version 1.2.7. After you installed the plugin and restarted your server -you can update as usual. The plugin will self-uninstall once it detects that it's -running under OctoPrint 1.2.8. After the self-uninstall another restart of your server -will be triggered (if you have setup your server's restart command, defaults to -`sudo service octoprint restart` on OctoPi) in order to really get rid of any -left-overs, so don't be alarmed when that happens, it is intentional. - -**If you cannot or don't want to use the plugin**, alternatively you can switch -OctoPrint to "Commit" based tracking via the settings of the Software Update plugin, -update, then switch back to "Release" based tracking (see [this screenshot](https://i.imgur.com/wvkgiGJ.png)). - -#### Bed temperatures are now only displayed if printer profile has a heated bed configured - -This release fixes a [bug](https://github.com/foosel/OctoPrint/issues/1125) -that caused bed temperature display and controls to be available even if the -selected printer profile didn't have a heated bed configured. - -If your printer does have a heated bed but you are not seeing its temperature -in the "Temperature" tab after updating to 1.2.8, please make sure to check -the "Heated Bed" option in your printer profile (under Settings > Printer Profiles) -as shown [in this short GIF](http://i.imgur.com/wp1j9bs.gif). - -### Improvements - - * Version numbering now follows [PEP440](https://www.python.org/dev/peps/pep-0440/). - * Prepared some things for publishing OctoPrint on [PyPi](https://pypi.python.org/pypi) - in the future. - * [BlueprintPlugin mixin](http://docs.octoprint.org/en/master/plugins/mixins.html#blueprintplugin) - now has an `errorhandler` decorator that serves the same purpose as - [Flask's](http://flask.pocoo.org/docs/0.10/patterns/errorpages/#error-handlers) - ([#1059](https://github.com/foosel/OctoPrint/pull/1059)) - * Interpret `M25` in a GCODE file that is being streamed from OctoPrint as - indication to pause, like `M0` and `M1`. - * Cache rendered page and translation files indefinitely. That should - significantly improve performance on reloads of the web interface. - * Added the string "unknown command" to the list of ignored printer errors. - This should help with general firmware compatibility in case a firmware - lacks features. - * Added the strings "cannot open" and "cannot enter" to the list of ignored - printer errors. Those are errors that Marlin may report if there is an issue - with the printer's SD card. - * The "CuraEngine" plugin now makes it more obvious that it only targets - CuraEngine versions up to and including 15.04 and also links to the plugin's - homepage with more information right within the settings dialog. - * Browser tab visibility is now tracked by the web interface, disabling the - webcam and the GCODE viewer if the tab containing OctoPrint is not active. - That should reduce the amount of resource utilized by the web interface on - the client when it is not actively monitored. Might also help to mitigate - [#1065](https://github.com/foosel/OctoPrint/issues/1065), the final verdict - on that one is still out though. - * The printer log in the terminal tab will now be cut off after 3000 lines - even if autoscroll is disabled. If the limit is reached, no more log lines - will be added to the client's buffer. That ensures that the log will not - scroll and the current log excerpt will stay put while also not causing - the browser to run into memory errors due to trying to buffer an endless - amount of log lines. - * Increased timeout of "waiting for restart" after an update from 20 to 60sec - (20sec turned out to be too little for OctoPi for whatever reason). - * Added a couple of unit tests - -### Bug Fixes - - * [#1120](https://github.com/foosel/OctoPrint/issues/1120) - Made the watchdog - that monitors and handles the `watched` folder more resilient towards errors. - * [#1125](https://github.com/foosel/OctoPrint/issues/1125) - Fixed OctoPrint - displaying bed temperature and controls and allowing the sending of GCODE - commands targeting the bed (`M140`, `M190`) if the printer profile doesn't - have a heated bed configured. - * Fixed an issue that stopped the software updater working for OctoPrint. The - updater reports success updating, but no update has actually taken place. A - fix can be applied for this issue to OctoPrint version 1.2.7 via - [the Updatefix 1.2.7 plugin](https://github.com/OctoPrint/OctoPrint-Updatefix-1.2.7). - For more information please refer to the [Important information for people updating from version 1.2.7](#important-information-for-people-updating-from-version-127) - above. - * Fix: Current filename in job data should never be prefixed with `/` - * Only persist plugin settings that differ from the defaults. This way the - `config.yaml` won't be filled with lots of redundant data. It's the - responsibility of the plugin authors to responsibly handle changes in default - settings of their plugins and add data migration where necessary. - * Fixed a documentation bug ([#1067](https://github.com/foosel/OctoPrint/pull/1067)) - * Fixed a conflict with bootstrap-responsive, e.g. when using the - [ScreenSquish Plugin](http://plugins.octoprint.org/plugins/screensquish/) - ([#1103](https://github.com/foosel/OctoPrint/pull/1067)) - * Fixed OctoPrint still sending SD card related commands to the printer even - if SD card support is disabled (e.g. `M21`). - * Hidden files are no longer visible to the template engine, neither as (GCODE) - scripts nor as interface templates. - * The hostname and URL prefix via which the OctoPrint web interface is accessed - is now part of the cache key. Without that being the case the cache could - be created referring to something like `/octoprint/prefix/api/` for its API - endpoint (if accessed via `http://somehost:someport/octoprint/prefix/` first - time), which would then cause the interface to not work if accessed later - via another route (e.g. `http://someotherhost/`). - * Fixed a JavaScript error on finishing streaming of a file to SD. - * Fixed version reporting on detached HEADs (when the branch detection - reported "HEAD" instead of "(detached" - * Fixed some path checks for systems with symlinked paths - ([#1051](https://github.com/foosel/OctoPrint/pull/1051)) - * Fixed a bug causing the "Server Offline" overlay to pop _under_ the - "Please reload" overlay, which could lead to "Connection refused" browser - messages when clicking "Reload now" in the wrong moment. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.7...1.2.8)) - -## 1.2.7 (2015-10-20) - -### Improvements - - * [#1062](https://github.com/foosel/OctoPrint/issues/1062) - Plugin Manager - now has a configuration dialog that among other things allows defining the - used `pip` command if auto detection proves to be insufficient here. - * Allow defining additional `pip` parameters in Plugin Manager. That might - make `sudo`-less installation of plugins possible in situations where it's - tricky otherwise. - * Improved timelapse processing (backported from `devel` branch): - * Individually captured frames cannot "overtake" each other anymore through - usage of a capture queue. - * Notifications will now be shown when the capturing of the timelapse's - post roll happens, including an approximation of how long that will take. - * Usage of `requests` instead of `urllib` for fetching the snapshot, - appears to also have [positive effects on webcam compatibility](https://github.com/foosel/OctoPrint/issues/1078). - * Some more defensive escaping for various settings in the UI (e.g. webcam URL) - * Switch to more error resilient saving of configuration files and other files - modified during runtime (save to temporary file & move). Should reduce risk - of file corruption. - * Downloading GCODE and STL files should now set more fitting `Content-Type` - headers (`text/plain` and `application/sla`) for better client side support - for "Open with" like usage scenarios. - * Selecting z-triggered timelapse mode will now inform about that not working - when printing from SD card. - * Software Update Plugin: Removed "The web interface will now be reloaded" - notification after successful update since that became obsolete with - introduction of the "Reload Now" overlay. - * Updated required version of `psutil` and `netifaces` dependencies. - -### Bug Fixes - - * [#1057](https://github.com/foosel/OctoPrint/issues/1057) - Better error - resilience of the Software Update plugin against broken/incomplete update - configurations. - * [#1075](https://github.com/foosel/OctoPrint/issues/1075) - Fixed support - of `sudo` for installing plugins, but added big visible warning about it - as it's **not** recommended. - * [#1077](https://github.com/foosel/OctoPrint/issues/1077) - Do not hiccup - on [UTF-8 BOMs](https://en.wikipedia.org/wiki/Byte_order_mark) (or other - BOMs for that matter) at the beginning of GCODE files. - * Fixed an issue that caused user sessions to not be properly associated, - leading to Sessions getting duplicated, wrongly saved etc. - * Fixed internal server error (HTTP 500) response on REST API calls with - unset `Content-Type` header. - * Fixed an issue leading to drag-and-drop file uploads to trigger frontend - processing in various other file upload widgets. - * Fixed a documentation error. - * Fixed caching behaviour on GCODE/STL downloads, was setting the `ETag` - header improperly. - * Fixed GCODE viewer not properly detecting change of currently visualized - file on Windows systems. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.6...1.2.7)) - -## 1.2.6 (2015-09-02) - -### Improvements - - * Added support for version reporting on detached checkouts - (see [#1041](https://github.com/foosel/OctoPrint/pull/1041)) - -### Bug Fixes - - * Pinned requirement for [psutil](https://pypi.python.org/pypi/psutil) - dependency to version 3.1.1 of that library due to an issue when - installing version 3.2.0 of that library released on 2015-09-02 through - a `python setup.py install` on OctoPrint. Also pinned all other requirements - to definitive versions that definitely work while at it to keep that from - happening again. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.5...1.2.6)) - -## 1.2.5 (2015-08-31) - -### Improvements - - * [#986](https://github.com/foosel/OctoPrint/issues/986) - Added tooltip for - "additional data" button in file list. - * [#1028](https://github.com/foosel/OctoPrint/issues/1028) - Hint about why - timelapse configuration is disabled. - * New central configuration option for commands to restart OctoPrint and to - restart and shut down the system OctoPrint is running on. This allows plugins - (like the Software Update Plugin or the Plugin Manager) and core functionality - to perform these common administrative tasks without the user needing to define - everything redundantly. - * Settings dialog now visualizes when settings are saving and when they being - retrieved. Also the Send/Cancel buttons are disabled while settings are saving - to prevent duplicated requests and concurrent retrieval of the settings by - multiple viewmodels is disabled as well. - * Better protection against rendering errors from templates provided by third - party plugins. - * Better protection against corrupting the configuration by using a temporary - file as intermediate buffer. - * Added warning to UI regarding Z timelapses and spiralized objects. - * Better compatibility with Repetier firmware: - * Added "Format Error" to whitelisted recoverable communication errors - (see also [#1032](https://github.com/foosel/OctoPrint/pull/1032)). - * Added option to ignore repeated resend requests for the same line (see - also discussion in [#1015](https://github.com/foosel/OctoPrint/pull/1015)). - * Software Update Plugin: - * Adjusted to utilize new centralized restart commands (see above). - * Allow configuration of checkout folder and version tracking type via - Plugin Configuration. - * Display message to user if OctoPrint's checkout folder is not configured - or a non-release version is running and version tracking against releases - is enabled. - * Clear version cache when a change in the check configuration is detected. - * Mark check configurations for which an update is not possible. - * Made disk space running low a bit more obvious through visual warning on - configurable thresholds. - -### Bug Fixes - - * [#985](https://github.com/foosel/OctoPrint/issues/985) - Do not hiccup on - unset `Content-Type` part headers for multipart file uploads. - * [#1001](https://github.com/foosel/OctoPrint/issues/1001) - Fixed connection - tab not unfolding properly (see also [#1002](https://github.com/foosel/OctoPrint/pull/1002)). - * [#1012](https://github.com/foosel/OctoPrint/issues/1012) - All API - responses now set no-cache headers, making the Edge browser behave a bit better - * [#1019](https://github.com/foosel/OctoPrint/issues/1019) - Better error - handling of problems when trying to write the webassets cache. - * [#1021](https://github.com/foosel/OctoPrint/issues/1021) - Properly handle - serial close on Macs. - * [#1031](https://github.com/foosel/OctoPrint/issues/1031) - Special - handling of `M112` (emergency stop) command: - * Jump send queue - * In case the printer's firmware doesn't understand it yet, at least - shutdown all of the heaters - * Disconnect - * Properly reset job progress to 0% when restarting a previously completed - printjob (see [#998](https://github.com/foosel/OctoPrint/pull/998)). - * Report an update as failed if the `pip` command returns a return code that - indicates failure. - * Fixed sorting of templates: could only be sorted by name, individual - configurations were ignored (see [#1022](https://github.com/foosel/OctoPrint/pull/1022)). - * Fixed positioning of custom context menus: were offset due to changes in - overall positioning settings (see [#1023](https://github.com/foosel/OctoPrint/pull/1023)). - * Software Update: Don't use display version for comparison of git commit - hashs. - * Fixed temperature parsing for multi extruder setups. - * Fixed nested vertical and horizontal custom control layouts. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.4...1.2.5)) - -## 1.2.4 (2015-07-23) - -### Improvements - - * `RepeatedTimer` now defaults to `daemon` set to `True`. This makes sure - plugins using it don't have to remember to set that flag themselves in - order for the server to properly shut down when timers are still active. - * Fixed a typo in the docs about `logging.yaml` (top level element is - `loggers`, not `logger`). - * Support for plugins with external dependencies (`dependency_links` in - setuptools), interesting for plugin authors who need to depend on Python - libraries that are (not yet) available on PyPI. - * Better resilience against errors within plugins. - -### Bug Fixes - - * Do not cache web page when running for the first time, to avoid caching - the first run dialog popup along side with it. This should solve issues - people were having when configuring OctoPrint for the first time, then - reloading the page without clearing the cache, being again prompted with - the dialog with no chance to clear it. - * Fix/workaround for occasional white panes in settings dialog on Safari 8, - which appears to have an issue with fixed positioning. - * Fixed form field truncation in upload requests that could lead to problems - when trying to import Cura profiles with names longer than 28 characters. - * Fixed webcam rotation for timelapse rendering. - * Fixed user settings not reaching the editor in the frontend. - * Notifications that are in process of being closed don't open again on - mouse over (that was actually more of an unwanted feature). - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.3...1.2.4)) - -## 1.2.3 (2015-07-09) - -### Improvements - - * New option to actively poll the watched folder. This should make it work also - if it is mounted on a filesystem that doesn't allow getting notifications - about added files through notification by the operating system (e.g. - network shares). - * Better resilience against senseless temperature/SD-status-polling intervals - (such as 0). - * Log exceptions during writing to the serial port to `octoprint.log`. - -### Bug Fixes - - * [#961](https://github.com/foosel/OctoPrint/pull/961) - Fixed a JavaScript error that caused an error to be logged when "enter" was pressed in file or plugin search. - * [#962](https://github.com/foosel/OctoPrint/pull/962) - ``url(...)``s in packed CSS and LESS files should now be rewritten properly too to refer to correct paths - * Update notifications were not vanishing properly after updating: - * Only use version cache for update notifications if the OctoPrint version still is the same to make sure the cache gets invalidated after an external update of OctoPrint. - * Do not persist version information when saving settings of the Software Update plugin - * Always delete files from the ``watched`` folder after importing then. Using file preprocessor plugins could lead to the files staying there. - * Fixed an encoding problem causing OctoPrint's Plugin Manager and Software Update plugins to choke on UTF-8 characters in the update output. - * Fixed sorting by file size in file list - * More resilience against missing plugin assets: - * Asset existence will now be checked before they get included - in the assets to bundle by webassets, logging a warning if a - file isn't present. - * Monkey-patched webassets filter chain to not die when a file - doesn't exist, but to log an error instead and just return - an empty file instead. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.2...1.2.3)) - -## 1.2.2 (2015-06-30) - -### Bug Fixes - -* Fixed an admin-only security issue introduced in 1.2.0, updating is strongly advised. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.1...1.2.2)) - -## 1.2.1 (2015-06-30) - -### Improvements - -* More flexibility when interpreting compatibility data from plugin repository. If compatibility information is provided - only as a version number it's prefixed with `>=` for the check (so stating a compatibility of only - `1.2.0` will now make the plugin compatible to OctoPrint 1.2.0+, not only 1.2.0). Alternatively the compatibility - information may now contain stuff like `>=1.2,<1.3` in which case the plugin will only be shown as compatible - to OctoPrint versions 1.2.0 and up but not 1.3.0 or anything above that. See also - [the requirement specification format of the `pkg_resources` package](https://pythonhosted.org/setuptools/pkg_resources.html#requirements-parsing). -* Only print the commands of configured event handlers to the log when a new `debug` flag is present in the config - (see [the docs](http://docs.octoprint.org/en/master/configuration/config_yaml.html#events)). Reduces risk of disclosing sensitive data when sharing log files. - -### Bug Fixes - -* [#956](https://github.com/foosel/OctoPrint/issues/956) - Fixed server crash when trying to configure a default - slicing profile for a still unconfigured slicer. -* [#957](https://github.com/foosel/OctoPrint/issues/957) - Increased maximum allowed body size for plugin archive uploads. -* Bugs without tickets: - * Clean exit on `SIGTERM`, calling the shutdown functions provided by plugins. - * Don't disconnect on `volume.init` errors from the firmware. - * `touch` uploaded files on local file storage to ensure proper "uploaded date" even for files that are just moved - from other locations of the file system (e.g. when being added from the `watched` folder). - -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.0...1.2.1)) - -## 1.2.0 (2015-06-25) - -### Note for Upgraders - - * The [Cura integration](https://github.com/daid/Cura) has changed in such a way that OctoPrint now calls the - [CuraEngine](https://github.com/Ultimaker/CuraEngine) directly instead of depending on the full Cura installation. See - [the wiki](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) for instructions on how to change your setup to - accommodate the new integration. - -### New Features - -* OctoPrint now has a [plugin system](http://docs.octoprint.org/en/master/plugins/index.html) which allows extending its - core functionality. - * Plugins may be installed through the new and bundled [Plugin Manager Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager) - available in OctoPrint's settings. This Plugin Manager also allows browsing and easy installation of plugins - registered on the official [OctoPrint Plugin Repository](http://plugins.octoprint.org). - * For interested developers there is a [tutorial available in the documentation](http://docs.octoprint.org/en/master/plugins/gettingstarted.html) - and also a [cookiecutter template](https://github.com/OctoPrint/cookiecutter-octoprint-plugin) to quickly bootstrap - new plugins. -* Added internationalization of UI. Translations of OctoPrint are being crowd sourced via [Transifex](https://www.transifex.com/projects/p/octoprint/). - Language Packs for both the core application as well as installed plugins can be uploaded through a new management - dialog in Settings > Appearance > Language Packs. A translation into German is included, further language packs - will soon be made available. -* Printer Profiles: Printer properties like print volume, extruder offsets etc are now managed via Printer Profiles. A - connection to a printer will always have a printer profile associated. -* File management now supports STL files as first class citizens (including UI adjustments to allow management of - uploaded STL files including removal and reslicing) and also allows folders (not yet supported by UI). STL files - can be downloaded like GCODE files. -* Slicing has been greatly improved: - * It now allows for a definition of slicing profiles to use for slicing plus overrides which can be defined per slicing - job (defining overrides is not yet part of the UI but it's on the roadmap). - * A new slicing dialog has been added which allows (re-)slicing uploaded STL files (which are now displayed in the file list - as well). The slicing profile and printer profile to use can be specified here as well as the file name to which to - slice to and the action to take after slicing has been completed (none, selecting the sliced GCODE for printing or - starting to print it directly) - * The slicing API allows positioning the model to slice on the print bed (Note: this is not yet available in the UI). - * Slicers themselves are integrated into the system via ``SlicingPlugins``. - * Bundled [Cura Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) allows slicing through CuraEngine up - to and including 15.04. Existing Cura slicing profiles can be imported through the web interface. -* New file list: Pagination is gone, no more (mobile incompatible) pop overs, instead scrollable and with instant - search -* You can now define a folder (default: `~/.octoprint/watched`) to be watched for newly added GCODE (or -- if slicing - support is enabled -- STL) files to automatically add. -* New type of API key: [App Session Keys](http://docs.octoprint.org/en/master/api/apps.html) for trusted applications -* OctoPrint now supports `action:...` commands received via debug messages (`// action:...`) from the printer. Currently supported are - - `action:pause`: Pauses the current job in OctoPrint - - `action:resume`: Resumes the current job in OctoPrint - - `action:disconnect`: Disconnects OctoPrint from the printer - Plugins can add supported commands by [hooking](http://docs.octoprint.org/en/master/plugins/hooks.html) into the - ``octoprint.comm.protocol.action`` hook -* Mousing over the webcam image in the control tab enables key control mode, allowing you to quickly move the axis of your - printer with your computer's keyboard ([#610](https://github.com/foosel/OctoPrint/pull/610)): - - arrow keys: X and Y axes - - W, S / PageUp, PageDown: Z axes - - Home: Home X and Y axes - - End: Home Z axes - - 1, 2, 3, 4: change step size used (0.1, 1, 10, 100mm) -* Controls for adjusting feed and flow rate factor added to Controls ([#362](https://github.com/foosel/OctoPrint/issues/362)) -* Custom controls now also support slider controls -* Custom controls now support a row layout -* Users can now define custom GCODE scripts to run upon starting/pausing/resuming/success/failure of a print or for - custom controls ([#457](https://github.com/foosel/OctoPrint/issues/457), [#347](https://github.com/foosel/OctoPrint/issues/347)) -* Bundled [Discovery Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery) allows discovery of OctoPrint - instances via SSDP/UPNP and optionally also via ZeroConf/Bonjour/Avahi. -* Bundled [Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update) takes care of notifying - about new OctoPrint releases and also allows updating if configured as such. Plugins may register themselves with the - update notification and application process through a new hook ["octoprint.plugin.softwareupdate.check_config"](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update#octoprintpluginsoftwareupdatecheck_config). - -### Improvements - -* Logging is now configurable via config file -* Added last print time to additional GCODE file information -* Better error handling for capture issues during timelapse creation & more robust handling of missing images during - timelapse creation -* Start counting the layers at 1 instead of 0 in the GCODE viewer -* Upgraded [Font Awesome](https://fortawesome.github.io/Font-Awesome/) to version 3.2.1 -* Better error reporting for timelapse rendering and system commands -* Custom control can now be defined so that they show a Confirm dialog with configurable text before executing - ([#532](https://github.com/foosel/OctoPrint/issues/532) and [#590](https://github.com/foosel/OctoPrint/pull/590)) -* Serial communication: Also interpret lines starting with "!!" as errors -* Added deletion of pyc files to the `python setup.py clean` command -* Settings now show a QRCode for the API Key ([#637](https://github.com/foosel/OctoPrint/pull/637)) -* Username in UI is no longer enclosed in scare quotes ([#595](https://github.com/foosel/OctoPrint/pull/595)) -* Username in login dialog is not automatically capitalized on mobile devices anymore ([#639](https://github.com/foosel/OctoPrint/pull/639)) -* "Slicing Done" and "Streaming Done" notifications now have a green background ([#558](https://github.com/foosel/OctoPrint/issues/558)) -* Files that are currently in use, be it for slicing, printing or whatever, are now tracked and can not be deleted as - long as they are in use -* Settings in UI get refreshed when opening settings dialog -* New event "SettingsUpdated" -* "Print time left" is now not displayed until it becomes somewhat stable. Display in web interface now also happens - in a fuzzy way instead of the format hh:mm:ss, to not suggest a high accuracy anymore where the can't be one. Additionally - OctoPrint will use data from prior prints to enhance the initial print time estimation. -* Added handler for uncaught exceptions to make sure those get logged, should make the logs even more useful for analysing - bug reports -* The server now tracks the modification date of the configuration file and reloads it prior to saving the config if - it has been changed during runtime by external editing, hence no config settings added manually while the server - was running should be overwritten anymore. -* Display a "Please Reload" overlay when a new server version or a change in installed plugins is detected after a - reconnect to the server. -* Better handling of errors on the websocket - no more logging of the full stack trace to the log, only a warning - message for now. -* Daemonized OctoPrint now cleans up its pidfile when receiving a TERM signal ([#711](https://github.com/foosel/OctoPrint/issues/711)) -* Added serial types for OpenBSD ([#551](https://github.com/foosel/OctoPrint/pull/551)) -* Improved behaviour of terminal: - * Disabling autoscrolling now also stops cutting off the log while it's enabled, effectively preventing log lines from - being modified at all ([#735](https://github.com/foosel/OctoPrint/issues/735)) - * Applying filters displays ``[...]`` where lines where removed and doesn't cause scrolling on filtered lines - anymore ([#286](https://github.com/foosel/OctoPrint/issues/286)) - * Added a link to scroll to the end of the terminal log (useful for when autoscroll is disabled) - * Added a link to select all current contents of the terminal log for easy copy-pasting - * Added a display of how many lines are displayed, how many are filtered and how many are available in total -* Frame rate for timelapses can now be configured per timelapse ([#782](https://github.com/foosel/OctoPrint/pull/782)) -* Added an option to specify the amount of encoding threads for FFMPEG ([#785](https://github.com/foosel/OctoPrint/pull/785)) -* "Disconnected" screen now is not shown directly after a close of the socket, instead the client first tries to - directly reconnect once, and only if that doesn't work displays the dialog. Should reduce short popups of the dialog - due to shaky network connections and/or weird browser behaviour when downloading things from the UI. -* Development dependencies can now be installed with ``pip -e .[develop]`` -* White and transparent colors ;) are supported for the navigation bar ([#789](https://github.com/foosel/OctoPrint/pull/789)) -* Drag-n-drop overlay for file uploads now uses the full available screen space, improving usability on high resolution - displays ([#187](https://github.com/foosel/OctoPrint/issues/187)) -* OctoPrint server should no longer hang when big changes in the system time happen, e.g. after first contact to an - NTP server on a Raspberry Pi image. Achieved through monkey patching Tornado with - [this PR](https://github.com/tornadoweb/tornado/pull/1290). -* Serial ports matching ``/dev/ttyAMA*`` are not anymore listed by default (this was the reason for a lot of people - running into problems while attempting to connect to their printer on their Raspberry Pis, on which ``/dev/ttyAMA0`` - is the OS's serial console by default). Added configuration of additional ports to the Serial Connection section in - the Settings to make it easier for those people who do indeed have their printer connected to ``/dev/ttyAMA0``. -* Better behaviour of the settings dialog on low-width devices, navigation and content also now scroll independently - from each other (see also [#823](https://github.com/foosel/OctoPrint/pull/823)) -* Renamed "Temperature Timeout" and "SD Status Timeout" in Settings to "Temperature Interval" and "SD Status Interval" - to better reflect what those values are actually used for. -* Added support for rectangular printer beds with the origin in the center ([#682](https://github.com/foosel/OctoPrint/issues/682) - and [#852](https://github.com/foosel/OctoPrint/pull/852)). Printer profiles now contain a new settings ``volume.origin`` - which can either be ``lowerleft`` or ``center``. For circular beds only ``center`` is supported. -* Made baudrate detection a bit more solid, still can't perform wonders. -* Only show configuration options for additional extruders if more than one is available, and don't include offset - configuration for first nozzle which acts as reference for the other offsets ([#677](https://github.com/foosel/OctoPrint/issues/677)). -* Cut off of the temperature graph is now not based on the number of data points any more but on the actual time of the - data points. Anything older than ``n`` minutes will be cut off, with ``n`` defaulting to 30min. This value can be - changed under "Temperatures" in the Settings ([#343](https://github.com/foosel/OctoPrint/issues/343)). -* High-DPI support for the GCode viewer ([#837](https://github.com/foosel/OctoPrint/issues/837)). -* Stop websocket connections from multiplying ([#888](https://github.com/foosel/OctoPrint/pull/888)). -* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and - [#906](https://github.com/foosel/OctoPrint/pull/906)) -* System commands now be set to a) run asynchronized by setting their `async` property to `true` and b) to ignore their - result by setting their `ignore` property to `true`. -* Various improvements of newly introduced features over the course of development: - * File management: The new implementation will migrate metadata from the old one upon first startup after upgrade from - version 1.1.x to 1.2.x. That should speed up initial startup. - * File management: GCODE Analysis backlog processing has been throttled to not take up too many resources on system - startup. Freshly uploaded files should still be analyzed at full speed. - * Plugins: SettingsPlugins may track versions of configuration format stored in `config.yaml`, including a custom - migration method getting called when a mismatch between the currently stored configuration format version and the one - reported by the plugin as current is detected. - * Plugins: Plugins may now have a folder for plugin related data whose path can be retrieved from the plugin itself - via its new method [`get_plugin_data_folder`](http://docs.octoprint.org/en/master/modules/plugin.html#octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder). - * Plugin Manager: Don't allow plugin management actions (like installing/uninstalling or enabling/disabling) while the - printer is printing (see also unreproduced issue [#936](https://github.com/foosel/OctoPrint/issues/936)). - * Plugin Manager: More options to try to match up installed plugin packages with discovered plugins. - * Plugin Manager: Display a more friendly message if after the installation of a plugin it could not be correctly - identifier. - * Software Update: Enforce refreshing of available updates after any changes in enabled plugins. - -### Bug Fixes - -* [#435](https://github.com/foosel/OctoPrint/issues/435) - Always interpret negative duration (e.g. for print time left) - as 0 -* [#516](https://github.com/foosel/OctoPrint/issues/516) - Also require API key even if ACL is disabled. -* [#556](https://github.com/foosel/OctoPrint/issues/556) - Allow login of the same user from multiple browsers without - side effects -* [#612](https://github.com/foosel/OctoPrint/issues/612) - Fixed GCODE viewer in zoomed out browsers -* [#633](https://github.com/foosel/OctoPrint/issues/633) - Correctly interpret temperature lines from multi extruder - setups under Smoothieware -* [#680](https://github.com/foosel/OctoPrint/issues/680) - Don't accidentally include a newline from the MIME headers - in the parsed multipart data from file uploads -* [#709](https://github.com/foosel/OctoPrint/issues/709) - Properly initialize time estimation for SD card transfers too -* [#715](https://github.com/foosel/OctoPrint/issues/715) - Fixed an error where Event Triggers of type command caused - and exception to be raised due to a misnamed attribute in the code -* [#717](https://github.com/foosel/OctoPrint/issues/717) - Use ``shutil.move`` instead of ``os.rename`` to avoid cross - device renaming issues -* [#752](https://github.com/foosel/OctoPrint/pull/752) - Fix error in event handlers sending multiple gcode commands. -* [#780](https://github.com/foosel/OctoPrint/issues/780) - Always (re)set file position in SD files to 0 so that reprints - work correctly -* [#784](https://github.com/foosel/OctoPrint/pull/784) - Also include ``requirements.txt`` in files packed up for - ``python setup.py sdist`` -* [#330](https://github.com/foosel/OctoPrint/issues/330) - Ping pong sending to fix potential acknowledgement errors. - Also affects [#166](https://github.com/foosel/OctoPrint/issues/166), [#470](https://github.com/foosel/OctoPrint/issues/470) - and [#490](https://github.com/foosel/OctoPrint/issues/490). A big thank you to all people involved in these tickets - in getting to the ground of this. -* [#825](https://github.com/foosel/OctoPrint/issues/825) - Fixed "please visualize" button of large GCODE files -* Various fixes of bugs in newly introduced features and improvements: - * [#625](https://github.com/foosel/OctoPrint/pull/625) - Newly added GCODE files were not being added to the analysis - queue - * [#664](https://github.com/foosel/OctoPrint/issues/664) - Fixed jog controls again - * [#677](https://github.com/foosel/OctoPrint/issues/677) - Fixed extruder offsets not being properly editable in - printer profiles - * [#678](https://github.com/foosel/OctoPrint/issues/678) - SockJS endpoints is now referenced by relative URL - using ``url_for``, should solve any issues with IE11. - * [#683](https://github.com/foosel/OctoPrint/issues/683) - Fixed heated bed option not being properly displayed in - printer profiles - * [#685](https://github.com/foosel/OctoPrint/issues/685) - Quoted file name for Timelapse creation to not make - command hiccup on ``~`` in file name - * [#709](https://github.com/foosel/OctoPrint/issues/709) - Fixed file sending to SD card - * [#714](https://github.com/foosel/OctoPrint/issues/714) - Fixed type validation of printer profiles - * Heating up the heated bed (if present) was not properly configured in CuraEngine plugin - * [#720](https://github.com/foosel/OctoPrint/issues/720) - Fixed translation files not being properly copied over - during install - * [#724](https://github.com/foosel/OctoPrint/issues/724) - Fixed timelapse deletion for timelapses with non-ascii - characters in their name - * [#726](https://github.com/foosel/OctoPrint/issues/726) - Fixed ``babel_refresh`` command - * [#759](https://github.com/foosel/OctoPrint/pull/759) - Properly initialize counter for template plugins of type - "generic" - * [#775](https://github.com/foosel/OctoPrint/pull/775) - Error messages in javascript console show the proper name - of the objects - * [#795](https://github.com/foosel/OctoPrint/issues/795) - Allow adding slicing profiles for unconfigured slicers - * [#809](https://github.com/foosel/OctoPrint/issues/809) - Added proper form validation to printer profile editor - * [#824](https://github.com/foosel/OctoPrint/issues/824) - Settings getting lost when switching between panes in - the settings dialog (fix provided by [#879](https://github.com/foosel/OctoPrint/pull/879)) - * [#892](https://github.com/foosel/OctoPrint/issues/892) - Preselected baudrate is now properly used for auto detected - serial ports - * [#909](https://github.com/foosel/OctoPrint/issues/909) - Fixed Z-Timelapse for Z changes on ``G1`` moves. - * Fixed another instance of a missing `branch` field in version dicts generated by versioneer (compare - [#634](https://github.com/foosel/OctoPrint/pull/634)). Caused an issue when installing from source archive - downloaded from Github. - * [#931](https://github.com/foosel/OctoPrint/issues/931) - Adjusted `octoprint_setuptools` to be compatible to older - versions of setuptools potentially site-wide installed on hosts. - * [#942](https://github.com/foosel/OctoPrint/issues/942) - Settings can now be saved again after installing a new - plugin. Plugins must not use `super` anymore to call parent implementation of `SettingsPlugin.on_settings_save` but - should instead switch to `SettingsPlugin.on_settings_save(self, ...)`. Settings API will capture related - `TypeErrors` and log a big warning to the log file indicating which plugin caused the problem and needs to be - updated. Also updated all bundled plugins accordingly. - * Software Update: Don't persist more check data than necessary in the configuration. Solves an issue where persisted - information overrode updated check configuration reported by plugins, leading to a "an update is available" loop. - An auto-migration function was added that should remove the redundant data. -* Various fixes without tickets: - * GCODE viewer now doesn't stumble over completely extrusionless GCODE files - * Do not deliver the API key on settings API unless user has admin rights - * Don't hiccup on slic3r filament_diameter comments in GCODE generated for multi extruder setups - * Color code successful or failed print results directly in file list, not just after a reload - * Changing Timelapse post roll activates save button - * Timelapse post roll is loaded properly from config - * Handling of files on the printer's SD card contained in folders now works correctly - * Don't display a "Disconnected" screen when trying to download a timelapse in Firefox - * Fixed handling of SD card files in folders - * Fixed refreshing of timelapse file list upon finished rendering of a new one - * Fixed ``/api/printer`` which wasn't adapter yet to new internal offset data model - * Made initial connection to printer a bit more responsive: Having to wait for the first serial timeout before sending - the first ``M105`` even when not waiting for seeing a "start" caused unnecessary wait times for reaching the - "Operational" state. - * Log cancelled prints only once (thanks to @imrahil for the headsup) - -### More information - - * [Commits](https://github.com/foosel/OctoPrint/compare/1.1.2...1.2.0) - * Release Candidates: - * [RC1](https://github.com/foosel/OctoPrint/releases/tag/1.2.0-rc1) - * [RC2](https://github.com/foosel/OctoPrint/releases/tag/1.2.0-rc2) - * [RC3](https://github.com/foosel/OctoPrint/releases/tag/1.2.0-rc3) - -## 1.1.2 (2015-03-23) - -### Improvements - -* Added deletion of `*.pyc` files to `python setup.py clean` command, should help tremendously when switching branches (backported - from [9e014eb](https://github.com/foosel/OctoPrint/commit/9e014eba1feffde11ed0601d9c911b8cac9f3fb0)) -* Increased default communication and connection timeouts -* [#706](https://github.com/foosel/OctoPrint/issues/706) - Do not truncate error reported from printer - -### Bug Fixes - -* [#539](https://github.com/foosel/OctoPrint/issues/539) - Limit maximum number of tools, sanity check tool numbers in - GCODE files against upper limit and refuse to create 10000 tools due to weird slicers. (backported from `devel`) -* [#634](https://github.com/foosel/OctoPrint/pull/634) - Fixed missing `branch` fields in version dicts generated - by versioneer -* [#679](https://github.com/foosel/OctoPrint/issues/679) - Fix error where API state is requested and printer is offline - (backport of [619fe9a](https://github.com/foosel/OctoPrint/commit/619fe9a0e78826bd1524b235a910156439bcb6d7)). -* [#719](https://github.com/foosel/OctoPrint/issues/719) - Properly center print bed in GCODE viewer -* [#780](https://github.com/foosel/OctoPrint/issues/780) - Always (re)set file position in SD files to 0 so that reprints - work correctly (backported from ``devel``) -* [#801](https://github.com/foosel/OctoPrint/issues/801) - Fixed setting of bed temperature offset -* [IRC] - Don't hiccup on slic3r ``filament_diameter`` comments generated for multi extruder setups -* [ML] - Fixed relative URL to SockJS endpoint, wasn't yet using the proper base url -* [unreported] & [#698](https://github.com/foosel/OctoPrint/issues/698) - Generated URLs now take X-Forwarded-Host header - sent by proxies into account for included host and port, also fixed [#698](https://github.com/foosel/OctoPrint/issues/698) - introduced by this -* [unreported] Fixed a bug causing gcodeInterpreter to hiccup on GCODES containing invalid coordinates such as Xnan or - Yinf (backported from `devel`) -* Small fixes for timelapse creation: - - [#344](https://github.com/foosel/OctoPrint/issues/344) - Made timelapses capable of coping with missing captures in between by decrementing the image counter again if there - was an error fetching the latest image from the snapshot URL (backport of [1a7a468](https://github.com/foosel/OctoPrint/commit/1a7a468eb65fdf2a13b4c7a7723280e822c9c34b) - and [bf9d5ef](https://github.com/foosel/OctoPrint/commit/bf9d5efe43a1e57aacd8512125082ddca06b4efc)) - - [#693](https://github.com/foosel/OctoPrint/issues/693) - Try not to capture an image if image counter is still unset - - [unreported] Synchronize image counter decrementing as well as incrementing to prevent rare race conditions when generating the - image file names - -([Commits](https://github.com/foosel/OctoPrint/compare/1.1.1...1.1.2)) - -## 1.1.1 (2014-10-27) - -### Improvements - -* The API is now enabled by default and the API key -- if not yet set -- will be automatically generated on first - server start and written back into ``config.yaml`` -* Event subscriptions are now enabled by default (it was an accident that they weren't) -* Generate the key used for session hashing individually for each server instance -* Generate the salt used for hashing user passwords individually for each server instance - -### Bug Fixes - -* [#580](https://github.com/foosel/OctoPrint/issues/580) - Properly unset job data when instructed so by callers -* [#604](https://github.com/foosel/OctoPrint/issues/604) - Properly initialize settings basedir on server startup -* [IRC] Also allow downloading .g files via Tornado - -([Commits](https://github.com/foosel/OctoPrint/compare/1.1.0...1.1.1)) - -## 1.1.0 (2014-09-03) - -### New Features - -* New REST API, including User API Keys additionally to the global API key. Please note that **this will break existing - API clients** as it replaces the old API (same endpoint). You can find the documentation of the new API at - [docs.octoprint.org](http://docs.octoprint.org/en/1.1.0/api/index.html). -* New Event structure allows more flexibility regarding payload data, configuration files will be migrated automatically. - You can find the documentation of the new event format and its usage at [docs.octoprint.org](http://docs.octoprint.org/en/1.1.0/events/index.html). -* Support for multi extruder setups. With this OctoPrint now in theory supports an unlimited amount of extruders, however - for now it's artificially limited to 9. -* Log files can be accessed from within the browser via the Settings dialog ([#361](https://github.com/foosel/OctoPrint/pull/361)) -* Timelapses can now have a post-roll duration configured which will be rendered into the video too to not let it - end so abruptly ([#384](https://github.com/foosel/OctoPrint/issues/384)) -* The terminal tab now has a command history ([#388](https://github.com/foosel/OctoPrint/pull/388)) - -### Improvements - -* Stopping the application via Ctrl-C produces a less scary message ([#277](https://github.com/foosel/OctoPrint/pull/277)) -* Webcam stream is disabled when control tab is not in focus, reduces bandwidth ([#316](https://github.com/foosel/OctoPrint/issues/316)) -* M and G commands entered in Terminal tab are automatically converted to uppercase -* GCODE viewer now only loads automatically if GCODE file size is beneath certain threshold (different ones for desktop - and mobile devices), only actually loads file if user acknowledges that this might be too much for his browser -* Added time needed for printing file to PrintDone event's payload ([#333](https://github.com/foosel/OctoPrint/issues/333)) -* Also provide the filename (basename without the path) in print events -* Support for circular beds in the GCODE viewer ([#407](https://github.com/foosel/OctoPrint/pull/407)) -* The dimensions of the print bed can now be configured via the Settings ([#396](https://github.com/foosel/OctoPrint/pull/396)) -* Target temperature reporting format of Repetier Firmware is now supported as well ([360](https://github.com/foosel/OctoPrint/issues/360)) -* Version tracking now based on git tagging and [versioneer](https://github.com/warner/python-versioneer/). Version number, - git commit and branch get reported in the format `--g ( branch)`, - e.g. `1.2.0-dev-172-ga48b5de (devel branch)`. -* Made "Center viewport on model" and "Zoom in on model" in the GCODE viewer automatically deselect and de-apply if - viewport gets manipulated by the user ([#398](https://github.com/foosel/OctoPrint/issues/398)) -* GCODE viewer now interprets inverted axes for printer control and mirrors print bed accordingly ([#431](https://github.com/foosel/OctoPrint/issues/431)) -* Added `clean` command to `setup.py`, removes old build artifacts (mostly interesting for developers) -* Added version resource on API which reports application and API version -* Made the navbar static instead of fixed to improve usability on mobile devices ([#257](https://github.com/foosel/OctoPrint/issues/257)) -* Switch to password field upon enter in username field, submit login form upon enter in password field -* Changed default path to OctoPrint executable in included init-script to `/usr/local/bin/octoprint` (the default when - installing via `python setup.py install`) - -### Bug Fixes - -* Properly calculate time deltas (forgot to factor in days) -* [#35](https://github.com/foosel/OctoPrint/issues/35) - GCODE viewer has been modularized, options are now functional -* [#337](https://github.com/foosel/OctoPrint/issues/337) - Also recognize `--iknowwhatimdoing` when running as daemon -* [#357](https://github.com/foosel/OctoPrint/issues/357) - Do not run GCODE analyzer when a print is ongoing -* [#381](https://github.com/foosel/OctoPrint/issues/381) - Only list those SD files that have an ASCII filename -* Fixed a race condition that could occur when pressing "Print" (File not opened yet, but attempt to read from it) -* [#398](https://github.com/foosel/OctoPrint/issues/398) - Fixed interfering options in GCODE viewer -* [#399](https://github.com/foosel/OctoPrint/issues/399) & [360](https://github.com/foosel/OctoPrint/issues/360) - Leave - bed temperature unset when not detected (instead of dying a horrible death) -* [#492](https://github.com/foosel/OctoPrint/issues/492) - Fixed a race condition which could lead to an attempt to read - from an already closed serial port, causing an error to be displayed to the user -* [#257](https://github.com/foosel/OctoPrint/issues/257) - Logging in on mobile devices should now work -* [#476](https://github.com/foosel/OctoPrint/issues/476) - Also update the metadata correctly when an analysis finishes -* Various fixes of bugs in newly introduced features and improvements: - - [#314](https://github.com/foosel/OctoPrint/issues/314) - Use G28 for homing (G1 was copy and paste error) - - [#317](https://github.com/foosel/OctoPrint/issues/317) - Fixed "load and print" function - - [#326](https://github.com/foosel/OctoPrint/issues/326) - Fixed refresh of SD file list - - [#338](https://github.com/foosel/OctoPrint/issues/338) - Refetch file list when deleting a file - - [#339](https://github.com/foosel/OctoPrint/issues/339) - More error resilience when handling temperature offset data from the backend - - [#345](https://github.com/foosel/OctoPrint/issues/345) - Also recognize such temperature reports that do not contain a `T:` but a `T0:` - - [#377](https://github.com/foosel/OctoPrint/pull/377) - URLs in API examples fixed - - [#378](https://github.com/foosel/OctoPrint/pull/378) - Fixed crash of API call when `getStartTime()` returns None - - [#379](https://github.com/foosel/OctoPrint/pull/379) - Corrected response code for connection success - - [#414](https://github.com/foosel/OctoPrint/pull/414) - Fix style attribute for Actual column header - -([Commits](https://github.com/foosel/OctoPrint/compare/1.0.0...1.1.0)) - -## 1.0.0 (2014-06-22) - -First release with new versioning scheme. +For even older changes, please refer to [the Github releases page](https://github.com/foosel/OctoPrint/releases). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 861215f4d..675b60b4d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,7 +27,7 @@ to **address problems in a timely manner** but also keep it possible for them to **fix bugs, add new and improve on existing functionality** instead of doing nothing but ticket management. -![Ticket flow chart](https://i.imgur.com/SmU7iCJ.png) +![Ticket flow chart](https://i.imgur.com/cw19qHX.png) - **[Read the FAQ](https://faq.octoprint.org)** - If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report) @@ -36,14 +36,14 @@ nothing but ticket management. - If you want to post a **feature request** or a **documentation request**, add `[Request]` to your issue's title (e.g. `[Request] Awesome new feature`). A question on how to run/change/setup something is **not** what qualifies as a request here, use the - [community forum at discourse.octoprint.org](https://discourse.octoprint.org) for + [community forum at community.octoprint.org](https://community.octoprint.org) for such support issues. - If you are a **developer** that wants to brainstorm a pull request or possible - changes to the plugin system, add [Brainstorming] to your issue's title (e.g. - `[Brainstorming] New plugin hook for doing some cool stuff`). + changes to the plugin system, please get in touch on the + [community forum at community.octoprint.org](https://community.octoprint.org/c/development). - If you need **support**, have a **question** or some **other reason** that doesn't fit any of the above categories, the issue tracker is not the right place. - Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org) instead. + Consult the [community forum at community.octoprint.org](https://community.octoprint.org/c/support) instead. No matter what kind of ticket you create, never mix two or more "ticket reasons" into one ticket: One ticket per bug, request, brainstorming thread please. @@ -53,7 +53,7 @@ into one ticket: One ticket per bug, request, brainstorming thread please. > A bot is in place that monitors new tickets, automatically > categorizes them and checks new bug reports for usage of the provided template. > That bot will only bother you if you open a ticket that appears to be a bug (no -> `[Request]` or `[Brainstorming]` in the title) without the complete template, and it +> `[Request]` in the title) without the complete template, and it > will do that only to ensure that all information needed to solve the issue is > available for the maintainers to directly start tackling that problem. @@ -75,7 +75,7 @@ following section *completely* and also follow the instructions in the **OctoPrint doesn't manage your network connection or your webcam nor can it fix your printer not getting detected as a serial interface** - if you have any kinds of problems with that, get in touch on the - [community forum](https://discourse.octoprint.org). + [community forum](https://community.octoprint.org). **This is not the bug tracker of OctoPi**, which is the preconfigured Raspberry Pi image including OctoPrint among other things - that one can be found @@ -126,7 +126,7 @@ following section *completely* and also follow the instructions in the there's now also a [red herring](https://en.wikipedia.org/wiki/Red_herring) interfering - so please be very diligent here! -If in doubt about any of the above - get in touch on the [community forum](https://discourse.octoprint.org) +If in doubt about any of the above - get in touch on the [community forum](https://community.octoprint.org) instead of opening a ticket here. If you are actually running into a bug, we'll figure it out together there. @@ -153,7 +153,7 @@ plugins and not unofficial OctoPrint versions). Do not seek support here ("I need help with ...", "I have a question ..."), that belongs on the community forum at -discourse.octoprint.org, NOT here. +community.octoprint.org, NOT here. Mark requests with a "[Request]" prefix in the title please. For bug reports fully fill out the bug reporting template (if you don't know @@ -275,11 +275,11 @@ all requested information or your ticket will be closed. ### Where can I find which version and branch I'm on? -Please refer to [this FAQ entry](https://discourse.octoprint.org/t/how-can-i-find-out-the-version-of-octoprint-or-octopi-i-am-running/204/1). +Please refer to [this FAQ entry](https://community.octoprint.org/t/how-can-i-find-out-the-version-of-octoprint-or-octopi-i-am-running/204/1). ### Where can I find those log files you keep talking about? -Please refer to [this FAQ entry](https://discourse.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299/1). +Please refer to [this FAQ entry](https://community.octoprint.org/t/where-can-i-find-octoprints-and-octopis-log-files/299/1). ### Where can I find my browser's error console? @@ -301,7 +301,8 @@ the documentation. the discussion going on how best to solve *this* in OctoPrint's plugin system - maybe that's the actual PR you have been waiting for to contribute :) 2. If you plan to make **any large or otherwise disruptive changes to the - code or appearance, please open a "Brainstorming" ticket first** so + code or appearance, please get in touch on the + [forums](https://community.octoprint.org/c/development)** first so that we can determine if it's a good time for your specific pull request. It might be that we're currently in the process of making heavy changes to the code locations you'd target as well, or your @@ -311,7 +312,8 @@ the documentation. 3. Create your pull request **from a custom branch** on your end (e.g. `dev/myNewFeature`)[1]. 4. Create your pull request **only against the `maintenance` or `devel` branch**: - * if it's a bug fix for a bug in the current stable version: `maintenance` branch + * if it's a bug fix for a bug in the current stable version, an improvement of existing functionality or a + *small* new feature (e.g. a new hook, a new config flag, ...): `maintenance` branch * otherwise: `devel` branch 5. Create **one pull request per feature/bug fix**. 6. Make sure there are **only relevant changes** included in your PR. No @@ -472,7 +474,9 @@ the local version identifier to allow for an exact determination of the active c * 2017-11-22: Added note on how to run the unit tests * 2018-03-15: Link to new community forum and some clarifications re bug reporting - * 2018-03-29: "Where to find version numbers" is now located on the FAQ + * 2018-03-29: "Where to find version numbers" is now located on the FAQ + * 2018-10-18: Allow PRs against `maintenance` branch for improvements and small + new features, suggest getting in touch on the forum for larger changes ## Footnotes * [1] - If you are wondering why, the problem is that anything that you add diff --git a/README.md b/README.md index fc9f7e0f1..0e4ac5f3a 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ ![GitHub release](https://img.shields.io/github/release/foosel/OctoPrint.svg?colorB=brightgreen) [![Travis build status](https://img.shields.io/travis/foosel/OctoPrint.svg)](https://travis-ci.org/foosel/OctoPrint) -[![Discourse topics](https://img.shields.io/discourse/https/discourse.octoprint.org/users.svg)](https://discourse.octoprint.org) +[![Discourse topics](https://img.shields.io/discourse/https/community.octoprint.org/users.svg)](https://community.octoprint.org) [![IRC](https://img.shields.io/badge/chat-on%20irc-brightgreen.svg)](https://chat.octoprint.org) [![Twitter Follow](https://img.shields.io/twitter/follow/OctoPrint3d.svg?style=social&label=Follow)](https://twitter.com/OctoPrint3d) @@ -13,7 +13,7 @@ and released under the [GNU Affero General Public License V3](http://www.gnu.org Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme). -The community forum is available at [discourse.octoprint.org](https://discourse.octoprint.org/?utm_source=github&utm_medium=readme). +The community forum is available at [community.octoprint.org](https://community.octoprint.org/?utm_source=github&utm_medium=readme). The official IRC channel is [#octoprint on freenode](https://chat.octoprint.org). Its logs can be found [here](https://freenode.logbot.info/octoprint). @@ -31,16 +31,16 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!** You are currently looking at the source code repository of OctoPrint. If you already installed it (e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki) -might be of more interest for you. You might also want to subscribe to join -[the community forum at discourse.octoprint.org](https://discourse.octoprint.org) where there are other active users who might be +might be of more interest for you. You might also want to subscribe to join +[the community forum at community.octoprint.org](https://community.octoprint.org) where there are other active users who might be able to help you with any questions you might have. ## Contributing Contributions of all kinds are welcome, not only in the form of code but also with regards to the [official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), debugging help -in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on -[the community forum at discourse.octoprint.org](https://discourse.octoprint.org) +in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on +[the community forum at community.octoprint.org](https://community.octoprint.org) and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme). If you think something is bad about OctoPrint or its documentation the way it is, please help @@ -61,18 +61,19 @@ which is a custom SD card image that includes OctoPrint plus dependencies. The generic steps that should basically be done regardless of operating system and runtime environment are the following (as *regular user*, please keep your hands *off* of the `sudo` command here!) - this assumes -you already have Python 2.7, pip and virtualenv set up on your system: +you already have Python 2.7, 3.6 or 3.7, pip and virtualenv set up on your system: 1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git` 2. Change into the OctoPrint folder: `cd OctoPrint` -3. Create a user-owned virtual environment therein: `virtualenv venv` +3. Create a user-owned virtual environment therein: `virtualenv venv` if your system default python version is + python 2.7, otherwise you need to specify the version explicitly, e.g. `virtualenv --python=python2.7 venv`. 4. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install .` You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage) for details. After installation, please make sure you follow the first-run wizard and set up -access control as necessary. +access control as necessary. ## Dependencies @@ -83,7 +84,7 @@ OctoPrint via `pip`: You should do this every time after pulling from the repository, since the dependencies may have changed. -OctoPrint currently only supports Python 2.7. +OctoPrint currently supports Python 2.7, 3.6 and 3.7. ## Usage @@ -142,5 +143,8 @@ be edited from OctoPrint's settings dialog. ## Special Thanks -Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/). -Profiling is done with the help of [PyVmMonitor](http://www.pyvmmonitor.com). +Cross-browser testing services are kindly provided by [BrowserStack](https://www.browserstack.com/). + +Profiling is done with the help of [PyVmMonitor](https://www.pyvmmonitor.com). + +Error tracking is powered and sponsored by [Sentry](https://sentry.io). diff --git a/SUPPORTERS.md b/SUPPORTERS.md index 2ddb3b341..475d05956 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -6,58 +6,54 @@ thanks to everyone who contributed! ## Patreon Patrons + * Andre Bubel * Andrew Moorby + * ANTONIO AUGUSTO DE LIMA PONTES * Arnljot Arntsen * Boris Hussein * Brad Jackson - * Brian E. Tyler * Christian Petropolis * Christian Wolf * COLLE+McVOY * D Brian Kimmel * DeltaMaker 3D Printers + * Dorian Gray * E3D BigBox + * Eric Betts * Ernesto Martinez - * F. Kunsmann - * Frank Sander + * Franziska Kunsmann * George Robles - * günter weber - * Hydra Research LLC - * James Seigel - * Jeff Moe + * jean-claude migneault * Jeff Renfer * Jefferson Hunt * Jeremiah Avery - * Joseph Payne - * Josh Daniels * Joshua Wills * Justin Kaufman * Kaile Riser * Kale Stedman * Kazuhiro Ogura - * Kodama Inc. - * Lewis Newby + * LA 3D Printer Repair + * Lee Dohm * LulzBot® * Makespace Madrid * Mark Walker - * Martin Beattie * Michael Aumock * Miles Flavel - * mitchell hirsch - * Noe Ruiz + * Mosaic Manufacturing + * OMER MEHMET SUTAS + * Patrick Glyré * Patrick McGinnis + * Prof Yuh Wen Chen * Randy C. Will + * Ranjib Dey * Robert Gusek - * Roger Strolz - * Roy Cortes - * Rudolff Vang * Samer Najia + * Shawn Lewis * Simon Hallam * Stefan Krister * Sven Mueller - * Symbiotic Devices - * Thomas Hatley - * Timothy D Hoogland * Trent Shumay + * Ulrich Kempken + * Vladislav Kuzemchik -and 1351 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! \ No newline at end of file +and 1615 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)! \ No newline at end of file diff --git a/THIRDPARTYLICENSES.md b/THIRDPARTYLICENSES.md index 6e626afe2..568a14bc5 100644 --- a/THIRDPARTYLICENSES.md +++ b/THIRDPARTYLICENSES.md @@ -37,7 +37,6 @@ * [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3 * [chainmap](https://bitbucket.org/jeunice/chainmap): Python * [Click](http://click.pocoo.org/): BSD - * [dateutil](https://dateutil.readthedocs.io/): BSD * [emoji](https://github.com/carpedm20/emoji/): BSD * [feedparser](https://github.com/kurtmckee/feedparser): BSD * [Flask](http://flask.pocoo.org/): BSD diff --git a/docs/api/apps.rst b/docs/api/apps.rst deleted file mode 100644 index 46ee73c8c..000000000 --- a/docs/api/apps.rst +++ /dev/null @@ -1,170 +0,0 @@ -.. _sec-api-apps: - -**** -Apps -**** - -.. contents:: - -.. _sec-api-apps-sessionkey: - -Session Keys -============ - -OctoPrint offers a special API key type for apps to use, the so called App Session Key. These keys have a time based -validity and are generated by OctoPrint for requesting apps. - -Obtaining those keys is based on a handshake procedure backed by cryptographic signatures using RSA. OctoPrint needs to -be aware of apps and their associated public keys (this can be achieved either via entries in ``config.yaml`` or by -installing app specific plugins which implement the ``AppPlugin`` type). - -Apps can be registered within OctoPrint via ``config.yaml`` by adding them to the ``api`` > ``apps`` section, using the -application's id concatenated with its version as key, with the public key provided as item ``pubkey`` (stripped of the -``BEGIN RSA PUBLIC KEY`` and ``END RSA PUBLIC KEY`` separators and also newlines) and optionally also whether the app is -enabled or not (defaults to enabled, so can be left out if it's not to be set to disabled explicitly). - -Example: - -.. sourcecode:: yaml - - api: - apps: - "com.example.my_octoprint_app:0.9": - pubkey: MEgCQQDYkr5Fv/YXK5ZL1uwRN4A61IagZaYLGqJ5JJGFo8wDrmpAMRqE9kK4+5hIDblC5DzfEr5oP7OA3tRO48Rf5yInAgMBAAE= - enabled: false - "com.example.my_octoprint_app:1.0": - pubkey: MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4osvb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE= - -In the example, the app ``com.example.my_octoprint_app`` in version 0.9 has been disabled (e.g. due to the key having -leaked) whereas version 1.0 is fully registered with OctoPrint and may verify app session keys. - - -.. _sec-api-apps-sessionkey-workflow: - -Workflow --------- - -Apps perform the handshake by first requesting a temporary key with very limited validity, -then sending a message back to OctoPrint containing their id, version, the temporary key and a signature created with their -private key over these three pieces of data. OctoPrint then tries to verify the signature and if successful unlocks the -key to be used as a fully recognized API key. - -For performing the handshake a special API exists within OctoPrint for which no API key is needed which is described below. - -.. _sec-api-apps-sessionkey-get: - -Obtaining a temporary session key ---------------------------------- - -.. http:get:: /apps/auth - - Retrieve a temporary session key with a minimum validity. It can only be used as a proper API key after having been - :ref:`verified `. - - Returns the temporary session key and the timestamp until it's valid. - - **Example**: - - .. sourcecode:: http - - GET /apps/auth HTTP/1.1 - Host: example.com - - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - { - "unverifiedKey": "F43A844750F74AD080FE9F438D47B33C", - "validUntil": 1416220357.011 - } - - :statuscode 200: No error - -.. _sec-api-apps-sessionkey-verify: - -Verifying a temporary session key ---------------------------------- - -.. http:post:: /apps/auth - - Verify a formerly :ref:`retrieved ` temporary session key by providing credentials and a - cryptographic signature over these credentials and the temporary key. - - Returns the now verified session key and the new validity. - - **Example**: - - .. sourcecode:: http - - POST /apps/auth HTTP/1.1 - Host: example.com - Content-Type: application/json - - { - "appid": "com.example.my_octoprint_app", - "appversion": "1.0", - "key": "F43A844750F74AD080FE9F438D47B33C", - "_sig": "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w==" - } - - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - { - "key": "F43A844750F74AD080FE9F438D47B33C", - "validUntil": 1416227497.011 - } - -.. _sec-api-apps-sessionkey-signature: - -Creating the signature ----------------------- - -The signature is created by concatenating the ``appid``, ``appversion`` and ``key`` fields, separated by a ``:`` (colon), -signing the result with the app's private key using SHA-1 and then BASE64-encoding the result, stripping newlines. - -Example for signature generation using Python and the `Python RSA library `_: - -.. sourcecode:: python - - import base64 - import rsa - - appid = "com.example.my_octoprint_app" - version = "1.0" - unverified_key = "F43A844750F74AD080FE9F438D47B33C" - message_to_sign = appid + ":" + version + ":" + unverified_key - // => "com.example.my_octoprint_app:1.0:F43A844750F74AD080FE9F438D47B33C" - - private_key = rsa.PrivateKey.load_pkcs1("...") - signature = base64.encodestring(rsa.sign(message_to_sign, private_key, "SHA-1")).replace("\n", "") - // => "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w==" - - -.. _sec-api-apps-sessionkey-testing: - -Testing your implementation ---------------------------- - -If you want to use app session keys, here is the key pair with which the above examples were created, in order for you -to verify your signature implementation:: - - -----BEGIN RSA PRIVATE KEY----- - MIIBPQIBAAJBAIhZ+Ls1zxtyd9kkm0DprhHIwL6woGUw5vbk5U00Hgva/ROIY7va - NUpHiiy9vijO2VtFbkaR2JjRPYslx8Ni+QkCAwEAAQJARK4lFo+FEcs3yR2iQjEy - p+yaAbNQJ4hZXlVvltLAYICzOM3kyKx53/eKU59NjskLz9q6QxfleymYPWAgl4NW - fQIjAJVH8MjwNcaAquTM9z2OiFi3OC8WgaKOi5W/T+r2+B70wG8CHwDp08dqOZ/u - xcBiy4Wzpcme9bckqoVuS3gWMm+YqgcCIwCMFU07kkY0NyumtzxPdIA4F/7OGSWf - IHqWFEfvasAddHlbAh8A5UgkB3Zf7Bt+7aFSBnlvve6FWm/XDPL12xYztYgrAiIa - W3miN6FjIm+8TDowrk+nyYXG2GZefeY7QXOjYr6tlDn0 - -----END RSA PRIVATE KEY----- - - -----BEGIN RSA PUBLIC KEY----- - MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4os - vb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE= - -----END RSA PUBLIC KEY----- - diff --git a/docs/api/connection.rst b/docs/api/connection.rst index 721e92cac..2a0037b9a 100644 --- a/docs/api/connection.rst +++ b/docs/api/connection.rst @@ -59,7 +59,7 @@ Issue a connection command Issue a connection command. Currently available command are: connect - Instructs OctoPrint to connect to the printer. Additional parameters are: + Instructs OctoPrint to connect or, if already connected, reconnect to the printer. Additional parameters are: * ``port``: Optional, specific port to connect to. If not set the current ``portPreference`` will be used, or if no preference is available auto detection will be attempted. diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst index a55554e9e..2af4f727f 100644 --- a/docs/api/datamodel.rst +++ b/docs/api/datamodel.rst @@ -218,6 +218,17 @@ Progress information - 1 - Integer - Estimate of time left to print, in seconds + * - ``printTimeLeftOrigin`` + - 1 + - String + - Origin of the current time left estimate. Can currently be either of: + + * ``linear``: based on an linear approximation of the progress in file in bytes vs time + * ``analysis``: based on an analysis of the file + * ``estimate``: calculated estimate after stabilization of linear estimation + * ``average``: based on the average total from past prints of the same model against the same printer profile + * ``mixed-analysis``: mixture of ``estimate`` and ``analysis`` + * ``mixed-average``: mixture of ``estimate`` and ``average`` .. _sec-api-datamodel-files: diff --git a/docs/api/general.rst b/docs/api/general.rst index 4232a96c9..3c404724c 100644 --- a/docs/api/general.rst +++ b/docs/api/general.rst @@ -11,9 +11,12 @@ General information 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. +If :ref:`Access Control ` is enabled 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 or an app and user specific one as generated by the +authorization workflow implemented by the bundled :ref:`Application Keys Plugin ` (since 1.3.10). + +Clients are advised to implement the :ref:`Application Keys Plugin workflow ` first and +fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used. The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g. @@ -23,8 +26,6 @@ The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g. Host: example.com X-Api-Key: abcdef... -If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`401`. - For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g. .. sourcecode:: http @@ -34,6 +35,24 @@ For testing purposes it is also possible to supply the API key via a query param Please be advised that clients should use the header field variant if at all possible. +If the key is missing or invalid, OctoPrint will treat the request as it would any unauthenticated anonymous request to the endpoint. +Consequently, if the bundled :ref:`ForceLogin plugin ` is active (which is the default), that means +that any requests without or with an invalid API key targeting other API endpoints than :ref:`Login ` +will be denied with a :http:statuscode:`403`. + +.. warning:: + + If :ref:`Access Control ` is disabled, OctoPrint will treat any unauthenticated anonymous requests and thus also requests + with an invalid or outright missing API key as requests with full admin rights! + +.. note:: + + The API key requirements changed in 1.3.11. Up to that version, even if Access Control was disabled, all requests needed to + be supplied with an API Key. To make the webinterface work under these circumstances, an unauthenticated anonymous API key was injected into the + HTML page and also available on the :ref:`Push API `. The presence and ready availability of this unauthenticated + anonymous "UI API key" caused confusion and false alarm among users and didn't contribute to the security of the platform in a + meaningful way, so it was finally abandoned in 1.3.11. + .. _fig-api-general-globalapikey: .. figure:: ../images/settings-global-api-key.png :align: center @@ -55,11 +74,6 @@ Please be advised that clients should use the header field variant if at all pos The API key options in the "Change password" dialog. Users can generate and revoke their custom API key here. -.. note:: - OctoPrint's web interface uses a custom API key that is freshly generated on every server start. This key is not - intended to be used by any other client and would not be very useful in any case, since it basically represents - a completely anonymous client. - .. _sec-api-general-contenttype: Content Type @@ -120,3 +134,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/job.rst b/docs/api/job.rst index 338a10ea7..0c43e2b3b 100644 --- a/docs/api/job.rst +++ b/docs/api/job.rst @@ -212,7 +212,8 @@ Retrieve information about the current job "filepos": 337942, "printTime": 276, "printTimeLeft": 912 - } + }, + "state": "Printing" } :statuscode 200: No error @@ -243,4 +244,8 @@ Job information response - 1 - :ref:`sec-api-datamodel-jobs-progress` - Information regarding the progress of the current print job - + * - ``state`` + - 1 + - String + - A textual representation of the current state of the job, i.e. "Operational", "Printing", "Pausing", "Paused", + "Cancelling", "Error" or "Offline". diff --git a/docs/api/printer.rst b/docs/api/printer.rst index 98f4ccbff..3fe43aa18 100644 --- a/docs/api/printer.rst +++ b/docs/api/printer.rst @@ -22,6 +22,11 @@ Bed corresponding resource returns temperature information including an optional history. Note that Bed commands are only available if the currently selected printer profile has a heated bed. See :ref:`sec-api-printer-bedcommand`. +Chamber + Chamber commands allow setting the temperature and temperature offset for the printer's heated chamber. Querying + the corresponding resource returns temperature information including an option history. Note that Chamber commands + are only available if the currently selected printer profile has a heated chamber. + See :ref:`sec-api-printer-chambercommand`. SD card SD commands allow initialization, refresh and release of the printer's SD card (if available). Querying the corresponding resource returns the current SD card state. @@ -219,7 +224,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: @@ -345,7 +350,7 @@ Issue a tool command Sets the given target temperature on the printer's tools. Additional parameters: * ``targets``: Target temperature(s) to set, properties must match the format ``tool{n}`` with ``n`` being the - tool's index starting with 0. + tool's index starting with 0. A value of `0` will turn the heater off. offset Sets the given temperature offset on the printer's tools. Additional parameters: @@ -362,6 +367,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. @@ -621,12 +628,12 @@ Issue a bed command are: target - Sets the given target temperature on the printer's tools. Additional parameters: + Sets the given target temperature on the printer's bed. Additional parameters: - * ``target``: Target temperature to set. + * ``target``: Target temperature to set. A value of `0` will turn the heater off. offset - Sets the given temperature offset on the printer's tools. Additional parameters: + Sets the given temperature offset on the printer's bed. Additional parameters: * ``offset``: Offset to set. @@ -708,7 +715,7 @@ Retrieve the current bed state an :http:statuscode:`409`. .. note:: - If you want both tool and bed temperature information at the same time, take a look at + If you want tool, bed and chamber temperature information at the same time, take a look at :ref:`Retrieve the current printer state `. **Example** @@ -758,6 +765,154 @@ Retrieve the current bed state :statuscode 409: If the printer is not operational or the selected printer profile does not have a heated bed. +.. _sec-api-printer-chambercommand: + +Issue a chamber command +======================= + +.. http:post:: /api/printer/chamber + + Chamber commands allow setting the temperature and temperature offsets for the printer's heated chamber. Available commands + are: + + target + Sets the given target temperature on the printer's chamber. Additional parameters: + + * ``target``: Target temperature to set. A value of `0` will turn the heater off. + + offset + Sets the given temperature offset on the printer's chamber. Additional parameters: + + * ``offset``: Offset to set. + + All of these commands may only be sent if the printer is currently operational. Otherwise a :http:statuscode:`409` + is returned. + + Upon success, a status code of :http:statuscode:`204` and an empty body is returned. + + If no heated chamber is configured for the currently selected printer profile, the resource will return + an :http:statuscode:`409`. + + Requires user rights. + + **Example Target Temperature Request** + + Set the target temperature for the printer's heated chamber to 50°C. + + .. sourcecode:: http + + POST /api/printer/chamber HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "target", + "target": 50 + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content + + **Example Offset Temperature Request** + + Set the temperature offset for the heated chamber to -5°C. + + .. sourcecode:: http + + POST /api/printer/chamber HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "offset", + "offset": -5 + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content + + :json string command: The command to issue, either ``target`` or ``offset``. + :json object target: ``target`` command: The target temperature to set. + :json object offset: ``offset`` command: The offset temperature to set. + :statuscode 204: No error + :statuscode 400: If ``target`` or ``offset`` is not a valid number or outside of the supported range, or if the + request is otherwise invalid. + :statuscode 409: If the printer is not operational or the selected printer profile + does not have a heated chamber. + +.. _sec-api-printer-chamberstate: + +Retrieve the current chamber state +================================== + +.. http:get:: /api/printer/chamber + + Retrieves the current temperature data (actual, target and offset) plus optionally a (limited) history (actual, target, + timestamp) for the printer's heated chamber. + + It's also possible to retrieve the temperature history by supplying the ``history`` query parameter set to ``true``. The + amount of returned history data points can be limited using the ``limit`` query parameter. + + Returns a :http:statuscode:`200` with a Temperature Response in the body upon success. + + If no heated chamber is configured for the currently selected printer profile, the resource will return + an :http:statuscode:`409`. + + .. note:: + If you want tool, bed and chamber temperature information at the same time, take a look at + :ref:`Retrieve the current printer state `. + + **Example** + + Query the chamber temperature data and also include the temperature history but limit it to two entries. + + .. sourcecode:: http + + GET /api/printer/chamber?history=true&limit=2 HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "chamber": { + "actual": 50.221, + "target": 70.0, + "offset": 5 + }, + "history": [ + { + "time": 1395651928, + "chamber": { + "actual": 50.221, + "target": 70.0 + } + }, + { + "time": 1395651926, + "chamber": { + "actual": 49.1123, + "target": 70.0 + } + } + ] + } + + :query history: If set to ``true`` (or: ``yes``, ``y``, ``1``), history information will be included in the response + too. If no ``limit`` parameter is given, all available temperature history data will be returned. + :query limit: If set to an integer (``n``), only the last ``n`` data points from the printer's temperature history + will be returned. Will be ignored if ``history`` is not enabled. + :statuscode 200: No error + :statuscode 409: If the printer is not operational or the selected printer profile + does not have a heated chamber. + .. _sec-api-printer-sdcommand: Issue an SD command diff --git a/docs/api/printerprofiles.rst b/docs/api/printerprofiles.rst index 8db1b51ae..9f2f163e2 100644 --- a/docs/api/printerprofiles.rst +++ b/docs/api/printerprofiles.rst @@ -52,6 +52,7 @@ Retrieve all printer profiles "height": 200 }, "heatedBed": true, + "heatedChamber": false, "axes": { "x": { "speed": 6000, @@ -93,6 +94,7 @@ Retrieve all printer profiles "height": 200 }, "heatedBed": true, + "heatedChamber": true, "axes": { "x": { "speed": 6000, @@ -184,6 +186,7 @@ Add a new printer profile "height": 200 }, "heatedBed": true, + "heatedChamber": false, "axes": { "x": { "speed": 6000, @@ -267,6 +270,7 @@ Add a new printer profile "height": 300 }, "heatedBed": false, + "heatedChamber": false, "axes": { "x": { "speed": 6000, @@ -352,6 +356,7 @@ Update an existing printer profile "height": 200 }, "heatedBed": true, + "heatedChamber": false, "axes": { "x": { "speed": 6000, @@ -578,6 +583,10 @@ Profile - 0..1 - ``boolean`` - Whether the printer has a heated bed (``true``) or not (``false``) + * - ``heatedChamber`` + - 0..1 + - ``boolean`` + - Whether the printer has a heated chamber (``true``) or not (``false``) * - ``axes`` - 0..1 - Object diff --git a/docs/api/push.rst b/docs/api/push.rst index 7d8813867..87e40bf5d 100644 --- a/docs/api/push.rst +++ b/docs/api/push.rst @@ -47,23 +47,41 @@ Clients must ignore any unknown messages. The data model of the attached payloads is described further below. -OctoPrint's SockJS socket also accepts one command from the client to the server, -the ``throttle`` command. Usually, OctoPrint will push the general state update -in the ``current`` message twice per second. For some clients that might still -be too fast, so they can signal a different factor to OctoPrint utilizing the -``throttle`` message. OctoPrint expects a single integer here which represents -the multiplier for the base rate limit of one message every 500ms. A value of -1 hence will produce the default behaviour of getting every update. A value of -2 will set the rate limit to maximally one message every 1s, 3 to maximally one -message every 1.5s and so on. +OctoPrint's SockJS socket also accepts two commands from the client to the server. -Example for a ``throttle`` client-server-message: + * ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an + existing user session with the socket. That is of special importance to receive + any kind of messages if the bundled :ref:`Forcelogin Plugin ` is enabled + (as it is by default), since it will prevent any kind of status messages to be sent to connected unauthenticated + clients. -.. sourcecode:: javascript + The ``auth`` message expects the user id of the user to authenticate followed by ``:`` and a session key to be + obtained from the successful payload of a :ref:`(passive or active) login via the API `. - { - "throttle": 2 - } + Example for a ``auth`` client-server-message: + + .. sourcecode:: javascript + + { + "auth": "someuser:LGZ0trf8By" + } + + * ``throttle``: Usually, OctoPrint will push the general state update + in the ``current`` message twice per second. For some clients that might still + be too fast, so they can signal a different factor to OctoPrint utilizing the + ``throttle`` message. OctoPrint expects a single integer here which represents + the multiplier for the base rate limit of one message every 500ms. A value of + 1 hence will produce the default behaviour of getting every update. A value of + 2 will set the rate limit to maximally one message every 1s, 3 to maximally one + message every 1.5s and so on. + + Example for a ``throttle`` client-server-message: + + .. sourcecode:: javascript + + { + "throttle": 2 + } .. _sec-api-push-datamodel: diff --git a/docs/api/settings.rst b/docs/api/settings.rst index 902127ab8..b4597ef94 100644 --- a/docs/api/settings.rst +++ b/docs/api/settings.rst @@ -274,10 +274,10 @@ Fetch template data "plugin_name": "Action Command Prompt Support" }, { - "id": "plugin_cura", - "name": "CuraEngine (<= 15.04)", - "plugin_id": "cura", - "plugin_name": "CuraEngine (<= 15.04)" + "id": "plugin_curalegacy", + "name": "Cura Legacy", + "plugin_id": "curalegacy", + "plugin_name": "Cura Legacy" } ], "sidebar": [ @@ -396,7 +396,7 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted: - * - ``feature.sdSupport`` - - * - ``feature.sdReleativePath`` + * - ``feature.sdRelativePath`` - * - ``feature.sdAlwaysAvailable`` - diff --git a/docs/api/slicing.rst b/docs/api/slicing.rst index 129653171..c49cb4cd5 100644 --- a/docs/api/slicing.rst +++ b/docs/api/slicing.rst @@ -42,22 +42,22 @@ List All Slicers and Slicing Profiles Content-Type: application/json { - "cura": { - "key": "cura", - "displayName": "CuraEngine", + "curalegacy": { + "key": "curalegacy", + "displayName": "Cura Legacy", "default": true, "profiles": { "high_quality": { "key": "high_quality", "displayName": "High Quality", "default": false, - "resource": "http://example.com/api/slicing/cura/profiles/high_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality" }, "medium_quality": { "key": "medium_quality", "displayName": "Medium Quality", "default": true, - "resource": "http://example.com/api/slicing/cura/profiles/medium_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality" } } } @@ -81,7 +81,7 @@ List Slicing Profiles of a Specific Slicer .. sourcecode:: http - GET /api/slicing/cura/profiles HTTP/1.1 + GET /api/slicing/curalegacy/profiles HTTP/1.1 Host: example.com X-Api-Key: abcdef... @@ -95,13 +95,13 @@ List Slicing Profiles of a Specific Slicer "key": "high_quality", "displayName": "High Quality", "default": false, - "resource": "http://example.com/api/slicing/cura/profiles/high_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality" }, "medium_quality": { "key": "medium_quality", "displayName": "Medium Quality", "default": true, - "resource": "http://example.com/api/slicing/cura/profiles/medium_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality" } } @@ -125,7 +125,7 @@ Retrieve Specific Profile .. sourcecode:: http - GET /api/slicing/cura/profiles/quick_test HTTP/1.1 + GET /api/slicing/curalegacy/profiles/quick_test HTTP/1.1 Host: example.com X-Api-Key: abcdef... @@ -137,7 +137,7 @@ Retrieve Specific Profile { "displayName": "Just a test", "description": "This is just a test", - "resource": "http://example.com/api/slicing/cura/profiles/quick_test", + "resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test", "data": { "bottom_layer_speed": 20.0, "bottom_thickness": 0.3, @@ -174,14 +174,14 @@ Add Slicing Profile .. sourcecode:: http - PUT /api/slicing/cura/profiles/quick_test HTTP/1.1 + PUT /api/slicing/curalegacy/profiles/quick_test HTTP/1.1 Host: example.com X-Api-Key: abcdef... Content-Type: application/json { "displayName": "Just a test", - "description": "This is just a test to show how to create a cura profile with a different layer height and skirt count", + "description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count", "data": { "layer_height": 0.2, "skirt_line_count": 3 @@ -197,8 +197,8 @@ Add Slicing Profile { "displayName": "Just a test", - "description": "This is just a test to show how to create a cura profile with a different layer height and skirt count", - "resource": "http://example.com/api/slicing/cura/profiles/quick_test" + "description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count", + "resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test" } :param slicer: The identifying key of the slicer for which to add the profile diff --git a/docs/api/version.rst b/docs/api/version.rst index 47b0c56e0..9716139c4 100644 --- a/docs/api/version.rst +++ b/docs/api/version.rst @@ -7,7 +7,8 @@ Version information .. http:get:: /api/version Retrieve information regarding server and API version. Returns a JSON object with two keys, ``api`` containing - the API version, ``server`` containing the server version. + the API version, ``server`` containing the server version, ``text`` containing the server version including + the prefix ``OctoPrint `` (to determine that this is indeed a genuine OctoPrint instance). **Example Request** @@ -26,7 +27,8 @@ Version information { "api": "0.1", - "server": "1.1.0" + "server": "1.3.10", + "text": "OctoPrint 1.3.10" } :statuscode 200: No error diff --git a/docs/bundledplugins/announcements.rst b/docs/bundledplugins/announcements.rst new file mode 100644 index 000000000..44dfe63e1 --- /dev/null +++ b/docs/bundledplugins/announcements.rst @@ -0,0 +1,67 @@ +.. _sec-bundledplugins-announcements: + +Announcement Plugin +=================== + +The OctoPrint Announcement Plugin comes bundled with OctoPrint (starting with 1.2.11). + +It displays announcements fetched from OctoPrint's websites, such as important updates, release announcements, new +plugins and similar. Through some manual configuration via ``config.yaml`` it also allows adding additional channels +via RSS or Atom feed URLs. + +.. _fig-bundledplugins-announcements-example1: +.. figure:: ../images/bundledplugins-announcements-example1.png + :align: center + :alt: Example notification + + An example notification from the Announcement Plugin. + +.. _fig-bundledplugins-announcements-example2: +.. figure:: ../images/bundledplugins-announcements-example2.png + :align: center + :alt: Announcement reader + + The Announcement Plugin's reader dialog. + +.. _fig-bundledplugins-announcements-settings: +.. figure:: ../images/bundledplugins-announcements-settings.png + :align: center + :alt: Announcement settings + + The Announcement Plugin's settings dialog. + +.. _sec-bundledplugins-announcements-configuration: + +Configuring the plugin +---------------------- + +The plugin allows enabling and disabling the preconfigured announcement channels via its settings dialog. + +On top of that it's possible to add additional announcement channels (as RSS or Atom feed URLs) or change the +configuration of the existing channels through ``config.yaml``. + +The available configuration keys are: + + * ``channels``: Configured announcement channels. A mapping from a unique identifier to a configuration structure + that follows this format: + + * ``name``: Name of the channel, used e.g. in the title of the displayed notifications. + * ``description``: Description of the channel. + * ``priority``: ``1`` for high priority announcements (red notification), ``2`` for regular ones (yellow notification). + * ``type``: Currently unused. + * ``url``: URL for the feed acting as notification source, must be RSS or Atom format. + + * ``enabled_channels``: List of identifiers of enabled channels. + * ``forced_channels``: List of identifiers of channels that cannot be disabled (currently only ``_important`` which is used sparingly). + * ``channel_order``: List of channel identifiers in the order they should appear in the UI. + * ``ttl``: Time to live of the channel cache in minutes (default: 6 hours). + * ``display_limit``: Limit of items to display per channel (default: 3). + * ``summary_limit``: Limit of characters to display from each channel entry (default: 300). + +.. _sec-bundledplugins-announcements-sourcecode: + +Source code +----------- + +The source of the Announcement plugin is bundled with OctoPrint and can be found in +its source repository under ``src/octoprint/plugins/announcements``. diff --git a/docs/bundledplugins/appkeys.rst b/docs/bundledplugins/appkeys.rst new file mode 100644 index 000000000..9d696dac2 --- /dev/null +++ b/docs/bundledplugins/appkeys.rst @@ -0,0 +1,543 @@ +.. _sec-bundledplugins-appkeys: + +Application Keys Plugin +======================= + +The OctoPrint Application Keys Plugin comes bundled with OctoPrint (starting with version 1.3.10). + +It implements a workflow for third party apps or clients to obtain an application specific API key from OctoPrint to interact with it +on a user's behalf, via confirmation of the user through OctoPrint's web interface. Existing keys can be managed +on a per-user base as well as globally by administrators. + +.. _fig-bundledplugins-appkeys-confirmation: +.. figure:: ../images/bundledplugins-appkeys-confirmation_prompt.png + :align: center + :alt: Confirmation + + The plugin's confirmation generated for a new application key request. + +.. _fig-bundledplugins-appkeys-user_settings: +.. figure:: ../images/bundledplugins-appkeys-user_settings.png + :align: center + :alt: Key management via user settings + + Users can manage the application specific API keys registered to their account via their user settings. + +.. _fig-bundledplugins-appkeys-settings: +.. figure:: ../images/bundledplugins-appkeys-settings.png + :align: center + :alt: Global key management via settings + + Administrators can manage all application specific API keys registered to any user. + +.. _sec-bundledplugins-appkeys-workflow: + +Workflow +-------- + +The workflow to receive an API key for a third party client/an app via the Application Keys Plugin should consist +of the following steps: + + 1. The User opens the App and gets prompted to enter or select an instance URL. Optionally (recommended!) the User also + enters their username which is also their user ID into the App. + 2. The App :ref:`probes for workflow support ` on the Server. If this request + doesn't get an HTTP :http:statuscode:`204` the App needs to direct the user to an alternative manual workflow + (copy-paste API key) and abort this one. Otherwise it proceeds to the next step. + 3. The App sends a :ref:`key request ` to the Server to start the + authorization process. + 4. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the + App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`. + 5. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202` + signals that no decision has been made yet. + 6. The User either accepts or denies the access request which makes the Webinterface send a + :ref:`decision request ` to the Server. + 7. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached + :ref:`API key response `. If they deny it, the App will receive + an HTTP :http:statuscode:`404`. + + +.. mermaid:: + + sequenceDiagram + participant User + participant App + participant Webinterface + participant Server + + note over User, Server: Step 1, 2 & 3 + + User->>App: enters URL of instance to connect to and optional user_id + + App->>Server: GET /plugin/appkeys/probe + + alt Workflow unsupported + + Server->>App: 404 + App->>User: alternative workflow, copy-paste key manually + + else Workflow supported + + App->>Server: POST /plugin/appkeys/request, (app_name, user_id) + + note over User, Server: Step 4 + + Server-->>Webinterface: plugin message for "appkeys" w/ (app_name, user_token, user_id) + Webinterface-->>User: Display confirmation dialog + Server->>App: 201, Location: /plugin/appkeys/request/ + + note over User, Server: Step 5 + + loop Poll for decision + App->>Server: GET /plugin/appkeys/request/ + Server->>App: 202 + end + + note over User, Server: Step 6 & 7 + + alt User accepts + + User-->>Webinterface: Allow access + Webinterface->>Server: POST /plugin/appkeys/decision/, (True) + Server->>Webinterface: 204 + App->>Server: GET /plugin/appkeys/request/ + Server->>App: 200, api_key + + else User denies + + User-->>Webinterface: Deny access + Webinterface->>Server: POST /plugin/appkeys/decision/, (False) + Server->>Webinterface: 204 + App->>Server: GET /plugin/appkeys/request/ + Server->>App: 404 + + end + + end + +.. _sec-bundledplugins-appkeys-api: + +API +--- + +.. _sec-bundledplugins-appkeys-api-probe: + +Probe for workflow support +.......................... + +.. http:get:: /plugin/appkeys/probe + + Probes for support of the workflow. + + Normally returns an HTTP :http:statuscode:`204`, indicating workflow availability. If a different status code is returned + (usually an HTTP :http:statuscode:`404`), the plugin is disabled or not installed. Fall back to manual api key exchange. + + :status 204: the workflow is supported + +.. _sec-bundledplugins-appkeys-api-startauthprocess: + +Start authorization process +........................... + +.. http:post:: /plugin/appkeys/request + + Starts the authorization process. + + Expects a :ref:`Key request ` as request body. + + The ``app`` parameter should be a human readable identifier to use + for the application requesting access. It will be displayed to the user. Internally it will be used case insensitively, + so ``My App`` and ``my APP`` are considered the same application identifiers. + + The optional ``user`` parameter should be used to limit the authorization process to a specified user. If the parameter + is left unset, any user will be able to complete the authorization process and grant access to the app with their + account. E.g. if a user ``me`` starts the process in an app, the app should request that name from the user and use + it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me`` + is logged in on. + + :json app: application identifier to use for the request, case insensitive + :json user: optional user id to restrict the decision to the specified user + :status 201: authorization process started, polling URL to query can be found in ``Location`` header + +.. _sec-bundledplugins-appkeys-api-polldecision: + +Poll for decision on existing request +..................................... + +.. http:get:: /plugin/appkeys/request/ + + Endpoint generated per authorization request to poll for the result. + + Returns an HTTP :http:statuscode:`202` while no decision has been made yet, an HTTP :http:statuscode:`200` and + a :ref:`Key response ` if access has been granted and an + HTTP :http:statuscode:`404` if the request has been denied or timed out. + + .. note:: + + The request will be considered stale and deleted internally if the polling endpoint for it isn't called + for more than 5s. + + :status 200: access granted, API key in response body + :status 202: no decision has been made yet, continue polling + :status 404: access denied or request timed out + +.. _sec-bundledplugins-appkeys-api-decide: + +Decide on existing request +.......................... + +.. http:post:: /plugin/appkeys/decision/ + + Endpoint to decide on the authorization request. + + Expects a :ref:`Decision request ` as request body. + + Returns an HTTP :http:statuscode:`204` on success. + + :json decision: boolean value to indicate whether to confirm (``True``) or deny (``False``) access + :status 204: success + +.. _sec-bundledplugins-appkeys-api-fetchlist: + +Fetch list of existing application keys +....................................... + +.. http:get:: /api/plugin/appkeys + + Fetches a list of existing application keys and pending requests registered in the system for the current user. + + If the additional optional parameter ``all`` is provided and the user has administrator rights, fetches a list + of *all** application keys and pending requests registered in the system for any user. + + Returns a :http:statuscode:`200` with a :ref:`List response ` in the + body upon success. + + :query all: Fetch all application keys and pending requests from all users. Requires administrator rights. + +.. _sec-bundledplugins-appkeys-api-issuecommand: + +Issue an application key command +................................ + +.. http:post:: /api/plugin/appkeys + + Application key commands allow revoking existing application keys and manually generating new ones. The available + commands are: + + revoke + Revokes an existing application key. Must belong to the user issuing the command, unless the user has admin rights + in which case they make revoke any application key in the system. Expects the key in question as parameter ``key``. + + generate + Generates a new application key for the user, using the application identifier provided as parameter ``app``. + + Upon success, a status code of :http:statuscode:`204` and an empty body is returned. + + Requires user rights. + + **Example revoke request** + + Revokes the (fictional) key ``aabbccddeeff112233445566``. + + .. sourcecode:: http + + POST /api/plugin/appkeys HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "revoke", + "key": "aabbccddeeff112233445566" + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content + + **Example generate request** + + Generates a new key for application identifier "My awesome application 1.0". + + .. sourcecode:: http + + POST /api/plugin/appkeys HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "generate", + "key": "My awesome application 1.0" + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content + + :json string command: The command to issue, either ``revoke`` or ``generate`` + :json string key: ``revoke`` command: The key to revoke + :json string app: ``generate`` command: Application identifier for which to generate a key + :statuscode 204: No error + :statuscode 400: Invalid or missing parameter + +.. _sec-bundledplugins-appkey-datamodel: + +Data model +---------- + +.. _sec-bundledplugins-appkey-datamodel-keyrequest: + +Key request +........... + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``app`` + - 1 + - str + - Application identifier to use for the request + * - ``user`` + - 0..1 + - str + - User identifier/name to restrict the request to + +.. _sec-bundledplugins-appkey-datamodel-keyresponse: + +Key response +............ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``apikey`` + - 1 + - str + - the API key generated for the application + +.. _sec-bundledplugins-appkey-datamodel-decisionrequest: + +Decision request +................ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``decision`` + - 1 + - boolean + - ``True`` if the access request it to be granted, ``False`` otherwise + +.. _sec-bundledplugins-appkey-datamodel-listreponse: + +List response +............. + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``keys`` + - 1 + - list of :ref:`key list entries ` + - Keys registered in the system + * - ``pending`` + - 1 + - list of :ref:`pending list entries ` + - Currently pending authorization requests + +.. _sec-bundledplugins-appkey-datamodel-keylistentry: + +Key list entry +.............. + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``api_key`` + - 1 + - str + - API key + * - ``app_id`` + - 1 + - str + - Application identifier + * - ``user_id`` + - 1 + - str + - User ID of the key's owner + +.. _sec-bundledplugins-appkey-datamodel-pendinglistentry: + +Pending list entry +.................. + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``app_id`` + - 1 + - str + - Application identifier + * - ``user_id`` + - 0..1 + - str + - optional: User ID of user who can grant or deny request + * - ``user_token`` + - 1 + - str + - Token to grant or deny request + +.. _sec-bundledplugins-appkeys-jsclientlib: + +JavaScript Client Library +------------------------- + +.. js:function:: OctoPrintClient.plugins.appkeys.getKeys(opts) + + Retrieves registered keys and pending requests for the current user. + + See :ref:`Fetch list of existing application keys ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.getAllKeys(opts) + + Retrieves registered keys and pending requests for all users. + + Needs administrator rights. + + See :ref:`Fetch list of existing application keys ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.generateKey(app, opts) + + Generates a key for the given ``app`` and the current user. + + See :ref:`Issue an application key command ` for details. + + :param string app: Application identifier + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.revokeKey(key, opts) + + Revokes the given ``key``. The key must belong to the current user, or the current user must have administrator + rights. + + See :ref:`Issue an application key command ` for details. + + :param string key: Key to revoke + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.decide(token, decision, opts) + + Decides on an existing authorization request. + + See :ref:`Decide on existing request ` for more details. + + :param string token: User token for which to make the decision, as pushed to the client via the socket. + :param boolean decision: Whether to grant access (``true``) or not (``false``). + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.probe(opts) + + Probes for workflow support. + + See :ref:`Probe for workflow support ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.request(app, opts) + + Starts a new authorization request for the provided ``app`` identifier. + + See :ref:`Start authorization process ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.requestForUser(app, user, opts) + + Starts a new authorization request for the provided ``app`` and ``user`` identifiers. + + See :ref:`Start authorization process ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.checkDecision(token, opts) + + Polls for a decision on an existing authorization request identified by ``token``. + + See :ref:`Poll for decision on existing request ` for more details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.appkeys.authenticate(app, user, opts) + + Convenience function that probes for support, issues a request and then automatically starts polling for a decision + on the returned polling endpoint every 1s, until either a positive or negative decision is returned. On success the + returned promise is resolved with the generated API key as argument. If anything goes wrong or there is no support + for the workflow, the promise is rejected. + + **Example usage** + + .. sourcecode:: javascript + + OctoPrint.plugins.appkeys.authenticate("My App", "some_user") + .done(function(api_key) { + console.log("Got our API key:", api_key); + }) + .fail(function() { + console.log("No API key for us"); + }) + + :param string app: Application identifier + :param string user: Optional user identifier + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. _sec-bundledplugins-appkeys-sourcecode: + +Source code +----------- + +The source of the Application Keys plugin is bundled with OctoPrint and can be found in +its source repository under ``src/octoprint/plugins/appkeys``. diff --git a/docs/bundledplugins/backup.rst b/docs/bundledplugins/backup.rst new file mode 100644 index 000000000..350d40508 --- /dev/null +++ b/docs/bundledplugins/backup.rst @@ -0,0 +1,70 @@ +.. _sec-bundledplugins-backup: + +Backup Plugin +============= + +The OctoPrint Backup Plugin comes bundled with OctoPrint (starting with 1.3.10). + +It allows the creation and restoration of backups of OctoPrint's settings, data and installed plugins [#]_. + +This allows easy migration +to newly setup instances as well as making regular backups to prevent data loss. + +.. _fig-bundledplugins-backup-settings: +.. figure:: ../images/bundledplugins-backup-settings.png + :align: center + :alt: OctoPrint Backup Plugin + + The plugin's settings panel with existing backups, the backup creation and restore sections. + +As long as plugins adhere to the standard of storing their data and settings in OctoPrint's plugin data folders, their +data will be part of the backup. Note that the backups made by the Backup Plugin will *not* be part of any backups - +you'll need to persist the resulting zip files yourself! + +.. _sec-bundledplugins-backup-cli: + +Command line usage +------------------ + +The Backup Plugin implements a command line interface that allows creation and restoration of backups. +It adds two new commands, ``backup:backup`` and ``backup_restore``. + +.. code-block:: none + + $ octoprint plugins backup:backup --help + Initializing settings & plugin subsystem... + Usage: octoprint plugins backup:backup [OPTIONS] + + Creates a new backup. + + Options: + --exclude TEXT Identifiers of data folders to exclude, e.g. 'uploads' to + exclude uploads or 'timelapse' to exclude timelapses. + --help Show this message and exit. + + $ octoprint plugins backup:restore --help + Initializing settings & plugin subsystem... + Usage: octoprint plugins backup:restore [OPTIONS] PATH + + Restores an existing backup from the backup zip provided as argument. + + OctoPrint does not need to run for this to proceed. + + Options: + --help Show this message and exit. + +.. note:: + + The ``backup:backup`` command can be useful in combination with a cronjob to create backups in regular intervals. + +.. _sec-bundledplugins-backup-sourcecode: + +Source code +----------- + +The source of the Backup plugin is bundled with OctoPrint and can be found in +its source repository under ``src/octoprint/plugins/backup``. + +.. [#] Note that only those plugins that are available on `OctoPrint's official plugin repository `_ + can be automatically restored. If you have plugins installed that are not available on there you'll get their + names and - if available - homepage URL displayed after restore in order to be able to manually reinstall them. diff --git a/docs/bundledplugins/cura.rst b/docs/bundledplugins/cura.rst deleted file mode 100644 index 7c47d620a..000000000 --- a/docs/bundledplugins/cura.rst +++ /dev/null @@ -1,130 +0,0 @@ -.. _sec-bundledplugins-cura: - -Cura -==== - -The Cura Plugin allows slicing of STL files uploaded to OctoPrint directly via -the `CuraEngine `_ **up to and -including version 15.04.x** and supersedes the slicing support integrated into -OctoPrint so far. It comes bundled with OctoPrint starting with version 1.2.0. - -.. note:: - - Versions of CuraEngine later than 15.04.x have changed their calling - parameters in such a way that the current implementation of OctoPrint's Cura plugin - is not compatible to it. For this reason, please use only CuraEngine versions up to - and including 15.04 for now, as available in the ``legacy`` branch of the CuraEngine - repository on Github. - -The plugin offers a settings module that allows configuring the path to the -CuraEngine executable to use, as well as importing and managing slicing -profiles to be used. Please note that the Cura Plugin will use the printer -parameters you configured within OctoPrint (meaning bed size and extruder -count and offsets) for slicing. - -.. _sec-bundledplugins-cura-firststeps: - -First Steps ------------ - -Before you can slice from within OctoPrint, you'll need to - - #. :ref:`Install CuraEngine ` - #. :ref:`Configure the path to CuraEngine within OctoPrint ` - #. :ref:`Export a slicing profile from Cura and import it within OctoPrint ` - -.. note:: - - OctoPi 0.12.0 and later ships with steps 1 and 2 already done, you only need to - supply one or more slicing profiles to get going :) - -.. _sec-bundledplugins-cura-installing: - -Installing CuraEngine ---------------------- - -You'll need a build of ``legacy`` branch of `CuraEngine `_ -in order to be able to use the Cura OctoPrint plugin. You can find the ``legacy`` branch -`here `__. - -If you previously used the `old variant of the Cura integration `_, -you probably still have a fully functional binary lying around in the -installation folder of the full install of Cura you used then -- just put the -path to that in the plugin settings. - -.. _sec-bundledplugins-cura-installing-raspbian: - -Compiling for Raspbian -++++++++++++++++++++++ - -Raspbian Jessie and later -~~~~~~~~~~~~~~~~~~~~~~~~~ - -Building on Raspbian Jessie and later is as easy as:: - - sudo apt-get -y install gcc-4.7 g++-4.7 - git clone -b legacy https://github.com/Ultimaker/CuraEngine.git - cd CuraEngine - make - -After this has completed, you'll find your shiny new build of CuraEngine in -the `build` folder (full path for above example: -``~/CuraEngine/build/CuraEngine``). - -Raspbian Wheezy -~~~~~~~~~~~~~~~ - -You'll need to install a new version of gcc and g++ and patch CuraEngine's -Makefile (see `this post `_) -in order for the compilation to work on current Raspbian builds (e.g. OctoPi):: - - sudo apt-get -y install gcc-4.7 g++-4.7 - git clone -b legacy https://github.com/Ultimaker/CuraEngine.git - cd CuraEngine - wget http://bit.ly/curaengine_makefile_patch -O CuraEngine.patch - patch < CuraEngine.patch - make CXX=g++-4.7 - -After this has completed, you'll find your shiny new build of CuraEngine in -the `build` folder (full path for above example: -``~/CuraEngine/build/CuraEngine``). - -.. _sec-bundledplugins-cura-configuring: - -Configuring the plugin ----------------------- - -The Cura plugin needs to be configured with the full path to your copy of the -CuraEngine executable that it's supposed to use. You can do this either via -the Cura plugin settings dialog or by manually configuring the path to the -executable via ``config.yaml``, example: - -.. code-block:: yaml - - plugins: - cura: - cura_engine: /path/to/CuraEngine - -.. _sec-bundledplugins-cura-profiles: - -Using Cura Profiles -------------------- - -The Cura Plugin supports importing your existing profiles for Cura **up to and -including Cura 15.04.x**. Newer Cura releases (e.g. 15.06 or 2.x) use a different -internal format that will *not* work with the current version of the Cura Plugin. - -You can find downloads of Cura 15.04.x for Windows, Mac and Linux `on Ultimaker's download page `_. - -In order to export a slicing profile from the Cura desktop UI, open it, -set up your profile, then click on "File" and there on "Save Profile". You can -import the .ini-file this creates via the "Import Profile" button in the -Cura Settings within OctoPrint. - -.. _sec-bundledplugins-cura-sourcecode: - -Source code ------------ - -The source of the Cura plugin is bundled with OctoPrint and can be found in -its source repository under ``src/octoprint/plugins/cura``. diff --git a/docs/bundledplugins/errortracking.rst b/docs/bundledplugins/errortracking.rst new file mode 100644 index 000000000..f87e7e8b2 --- /dev/null +++ b/docs/bundledplugins/errortracking.rst @@ -0,0 +1,40 @@ +.. _sec-bundledplugins-errortracking: + +Error Tracking Plugin +===================== + +The Error Tracking plugin will cause any logged exceptions in the server and the browser interface to be sent to +OctoPrint's `Sentry instance `_. + +By enabling it you help to gather detailed information on the cause of bugs or other issues. This is especially +valuable on release candidates, which is why this plugin will also prompt you to enable error tracking if it detects +that you are subscribed to an RC release channel. + +By default, even when enabled it will only be active if you are running a released OctoPrint version, so either a stable +release or a release candidate. + +The Error Tracking plugin is using a Sentry instance kindly provided by `sentry.io `_. For information on their service +please refer to their `Security & Compliance documentation `_ +and their `Privacy Policy `_. + +The Error Tracking plugin has been bundled with OctoPrint since version 1.3.11. + +.. _sec-bundledplugins-errortracking-configuration: + +Configuring the plugin +---------------------- + +The plugin supports the following configuration keys: + + * ``enabled``: Whether to enable error tracking. Defaults to ``false``. + * ``enabled_unreleased``: Whether to also enable tracking on unreleased OctoPrint versions (anything not stable releases + or release candidates). Defaults to ``false``. + * ``unique_id``: Unique instance identifier, auto generated on first activation + +.. _sec-bundledplugins-errortracking-sourcecode: + +Source Code +----------- + +The source of the Error Tracking plugin is bundled with OctoPrint and can be +found in its source repository under ``src/octoprint/plugins/errortracking``. diff --git a/docs/bundledplugins/forcelogin.rst b/docs/bundledplugins/forcelogin.rst new file mode 100644 index 000000000..e5214f79f --- /dev/null +++ b/docs/bundledplugins/forcelogin.rst @@ -0,0 +1,35 @@ +.. _sec-bundledplugins-forcelogin: + +ForceLogin Plugin +================= + +The ForceLogin Plugin comes bundled with OctoPrint (starting with version 1.3.10). It removes the anonymous +read-only access that up until 1.3.10 was standard when accessing OctoPrint instances without being logged in and +instead forces users to log in if they want to get any kind of information from OctoPrint. + +.. _fig-bundledplugins-forcelogin: +.. figure:: ../images/bundledplugins-forcelogin-dialog.png + :align: center + :alt: Forced login dialog + + OctoPrint's new forced login dialog. + +.. warning:: + + Keep in mind that **OctoPrint does not manage your webcam**, it merely embeds it. If you have a webcam, + it will still be accessible to users who are not logged in under its (guessable) URL. If you need to restrict + access to your webcam, you'll need to find a way to do so directly on the webcam server which - again - + is not OctoPrint itself. + +.. note:: + + If you want back the old behaviour of allowing anonymous read-only access to your OctoPrint instance, disable + the ForceLogin Plugin in OctoPrint's plugin manager. + +.. _sec-bundledplugins-forcelogin-sourcecode: + +Source code +----------- + +The source of the ForceLogin plugin is bundled with OctoPrint and can be found in +its source repository under ``src/octoprint/plugins/forcelogin``. diff --git a/docs/bundledplugins/index.rst b/docs/bundledplugins/index.rst index 26a520699..d82c3eb29 100644 --- a/docs/bundledplugins/index.rst +++ b/docs/bundledplugins/index.rst @@ -8,8 +8,13 @@ Bundled Plugins :maxdepth: 2 action_command_prompt.rst - cura.rst + announcements.rst + tracking.rst + appkeys.rst + backup.rst discovery.rst + errortracking.rst + forcelogin.rst logging.rst pluginmanager.rst printer_safety_check.rst diff --git a/docs/bundledplugins/pluginmanager.rst b/docs/bundledplugins/pluginmanager.rst index dacb3f8ca..2ec1babbb 100644 --- a/docs/bundledplugins/pluginmanager.rst +++ b/docs/bundledplugins/pluginmanager.rst @@ -82,6 +82,45 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``: - hidden - plugins +.. _sec-bundledplugins-pluginmanager-events: + +Events +------ + +plugin_pluginmanager_install_plugin + A plugin was installed. + + Payload: + + * ``id``: the identifier of the installed plugin + * ``version``: the version of the installed plugin + * ``source``: source from which the plugin was installed, can be an URL or a path in the local file system + * ``source_type``: type of source from which the plugin was installed, can be ``url`` or ``path`` + +plugin_pluginmanager_uninstall_plugin + A plugin was uninstalled. + + Payload: + + * ``id``: the identifier of the uninstalled plugin + * ``version``: the version of the uninstalled plugin + +plugin_pluginmanager_enable_plugin + A plugin was enabled. + + Payload: + + * ``id``: the identifier of the enabled plugin + * ``version``: the version of the enabled plugin + +plugin_pluginmanager_disabled_plugin + A plugin was disabled. + + Payload: + + * ``id``: the identifier of the disabled plugin + * ``version``: the version of the disabled plugin + .. _sec-bundledplugins-pluginmanager-hooks: Hooks diff --git a/docs/bundledplugins/printer_safety_check.rst b/docs/bundledplugins/printer_safety_check.rst index 89974de48..320de9053 100644 --- a/docs/bundledplugins/printer_safety_check.rst +++ b/docs/bundledplugins/printer_safety_check.rst @@ -16,17 +16,12 @@ such identification. An example of a warning generated by the Printer Safety Check -Currently the following firmwares produce this warning: - - * Anet A8 stock firmware +Please refer to the `entry on the "unsafe firmware" warning in OctoPrint's FAQ `_ +for a list of currently identified printers. If you know of further printers/printer firmwares that need to be added here, please `get in touch on the forum and provide their response to an M115 `_. -.. seealso:: - - `Entry on the "unsafe firmware" warning in OctoPrint's FAQ `_ - .. note:: Feel free to disable the plugin in OctoPrint's Plugin Manager if you feel like it is unnecessary. Be advised though @@ -34,6 +29,20 @@ If you know of further printers/printer firmwares that need to be added here, pl unexpectedly and with `catastrophic `_ `results `_. +.. _sec-bundledplugins-printer_safety_check-events: + +Events +------ + +warning + A printer safety warning was triggered. + + Payload: + + * ``check_type``: type of check that was triggered (e.g. ``m115``, ``received`` or ``cap``) + * ``check_name``: name of check that was triggered (e.g. ``aneta8``) + * ``warning_type``: type of warning that was triggered (e.g. ``firmware-unsafe``) + .. _sec-bundledplugins-printer_safety_check-source: Source Code diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index de4896b6d..1ba0daf84 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -325,6 +325,29 @@ The same, but tracking all commits pushed to branch ``devel`` (thus allowing branch: devel pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip' +.. _sec-bundledplugins-softwareupdate-events: + +Events +------ + +plugin_softwareupdate_update_succeeded + An update succeeded. + + Payload: + + * ``target``: update target + * ``from_version``: version from which was updated + * ``to_version``: version to which was updated + +plugin_softwareupdate_update_failed + An update failed. + + Payload: + + * ``target``: update target + * ``from_version``: version from which was updated + * ``to_version``: version to which was updated + .. _sec-bundledplugins-softwareupdate-hooks: Hooks @@ -362,8 +385,8 @@ octoprint.plugin.softwareupdate.check_config .. code-block:: python - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals def get_update_information(*args, **kwargs): return dict( diff --git a/docs/bundledplugins/tracking.rst b/docs/bundledplugins/tracking.rst new file mode 100644 index 000000000..4864deb6f --- /dev/null +++ b/docs/bundledplugins/tracking.rst @@ -0,0 +1,45 @@ +.. _sec-bundledplugins-tracking: + +Anonymous Usage Tracking Plugin +=============================== + +The Anonymous Usage Tracking plugin provides valuable insights into how many instances running what versions of +OctoPrint are out there, whether they are successfully completing print jobs and various other metrics. + +By enabling it you help to identify problems with new releases and release candidates early on, and to better tailor +OctoPrint's future development to actual use. + +For details on what gets tracked, please refer to `tracking.octoprint.org `_ +and also the `Privacy Policy at tracking.octoprint.org `_. + +The Anonymous Usage Tracking plugin has been bundled with OctoPrint since version 1.3.10. + +.. _sec-bundledplugins-tracking-configuration: + +Configuring the plugin +---------------------- + +The plugin supports the following configuration keys: + + * ``enabled``: Whether to enable usage tracking. Defaults to ``false``. + * ``unique_id``: Unique instance identifier, auto generated on first activation + * ``server``: The tracking server to track against. Defaults to a tracking endpoint on ``https://tracking.octoprint.org``. + * ``ping``: How often to send a ``ping`` tracking event, in seconds. Defaults to a 15min interval. + * ``events``: Granular configuration of enabled tracking events. All default to ``true``. + + * ``startup``: Whether to track startup/shutdown events + * ``printjob``: Whether to track print job related events (start, completion, cancel, ...) + * ``commerror``: Whether to track communication errors with the printer + * ``plugin``: Whether to track plugin related events (install, uninstall, ...) + * ``update``: Whether to track update related events (update successful or not, ...) + * ``printer``: Whether to track printer related events (connected, firmware, ...) + * ``printer_safety_check``: Whether to track warnings of the :ref:`Printer Safety Check ` + * ``throttled``: Whether to track throttle events detected on the underlying system + +.. _sec-bundledplugins-tracking-sourcecode: + +Source Code +----------- + +The source of the Anonymous Usage Tracking plugin is bundled with OctoPrint and can be +found in its source repository under ``src/octoprint/plugins/tracking``. diff --git a/docs/conf.py b/docs/conf.py index 3827b54fa..9de6f2608 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + # # OctoPrint documentation build configuration file, created by # sphinx-quickstart on Mon Dec 02 17:08:50 2013. @@ -49,8 +51,8 @@ source_suffix = '.rst' master_doc = 'index' # General information about the project. -project = u'OctoPrint' -copyright = u'%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else u'%d, Gina Häußge' % year_since +project = 'OctoPrint' +copyright = '%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else '%d, Gina Häußge' % year_since # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -207,8 +209,8 @@ htmlhelp_basename = 'OctoPrintdoc' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). #latex_documents = [ -# ('index', 'OctoPrint.tex', u'OctoPrint Documentation', -# u'Gina Häußge', 'manual'), +# ('index', 'OctoPrint.tex', 'OctoPrint Documentation', +# 'Gina Häußge', 'manual'), #] # The name of an image file (relative to this directory) to place at the top of @@ -237,8 +239,8 @@ htmlhelp_basename = 'OctoPrintdoc' # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - ('index', 'octoprint', u'OctoPrint Documentation', - [u'Gina Häußge'], 1) + ('index', 'octoprint', 'OctoPrint Documentation', + ['Gina Häußge'], 1) ] # If true, show URL addresses after external links. @@ -251,8 +253,8 @@ man_pages = [ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'OctoPrint', u'OctoPrint Documentation', - u'Gina Häußge', 'OctoPrint', 'One line description of project.', + ('index', 'OctoPrint', 'OctoPrint Documentation', + 'Gina Häußge', 'OctoPrint', 'One line description of project.', 'Miscellaneous'), ] diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 0f2a30453..271911218 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -29,7 +29,7 @@ Use the following settings to enable access control: # The user manager implementation to use for accessing user information. Currently only a filebased # user manager is implemented which stores configured accounts in a YAML file (Default: users.yaml # in the default configuration folder, see below) - userManager: octoprint.users.FilebasedUserManager + userManager: octoprint.access.users.FilebasedUserManager # The YAML user file to use. If left out defaults to users.yaml in the default configuration folder. userFile: /path/to/users.yaml @@ -62,6 +62,18 @@ Use the following settings to enable access control: # header and login the user without further checks. Use with caution. checkBasicAuthenticationPassword: true + # Whether to trust remote user headers. If you have setup authentication in front of + # OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will + # be logged into OctoPrint as the user provided in the header. Your should ONLY ENABLE THIS if your + # OctoPrint instance is only accessible through a connection locked down through an authenticating reverse proxy! + trustRemoteUser: false + + # Header used by the reverse proxy to convey the authenticated user. + remoteUserHeader: REMOTE_USER + + # If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint. + addRemoteUsers: false + .. _sec-configuration-config_yaml-api: API @@ -81,7 +93,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: @@ -277,6 +290,9 @@ The following settings are only relevant to you if you want to do OctoPrint deve # Whether to delete generated web assets on server startup (forcing a regeneration) clean_on_startup: true + # enable or disable the loading animation + showLoadingAnimation: true + # Settings for the virtual printer virtualPrinter: @@ -322,6 +338,9 @@ The following settings are only relevant to you if you want to do OctoPrint deve # Whether the simulated printer should also simulate a heated bed or not hasBed: true + # Whether the simulated printer should also simulate a heated chamber or not + hasChamber: false + # If enabled, reports the set target temperatures as separate messages from the firmware # # True: > M109 S220.0 @@ -409,8 +428,7 @@ The following settings are only relevant to you if you want to do OctoPrint deve # Lines to send on simulated reset resetLines: - start - - Marlin: Virtual Marlin! - - "\x80" + - "Marlin: Virtual Marlin!" - "SD card ok" # Initial set of prepared oks to use instead of regular ok (e.g. to simulate @@ -562,6 +580,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 @@ -666,6 +687,11 @@ plugins are tracked: _disabled: - ... + # Identifiers of plugins for which python compatibility information will be ignored and + # the plugin considered compatible in any case. Only for development, do NOT use in production. + _forcedCompatible: + - ... + # The rest are individual plugin settings, each tracked by their identifier, e.g.: some_plugin: some_setting: true @@ -806,6 +832,19 @@ Use the following settings to configure the serial connection to the printer: additionalBaudrates: - 123456 + # Commands which should not be sent to the printer, e.g. because they are known to block serial + # communication until physical interaction with the printer as is the case on most firmwares with + # the default M0 and M1. + blockedCommands: + - M0 + - M1 + + # Commands which should cause OctoPrint to pause any ongoing prints. + pausingCommands: + - M0 + - M1 + - M25 + # Commands which are known to take a long time to be acknowledged by the firmware. E.g. # homing, dwelling, auto leveling etc. Defaults to the below commands. longRunningCommands: @@ -932,6 +971,13 @@ Use the following settings to configure the server: # reset the setting to false startOnceInSafeMode: false + # Signals to OctoPrint that the last startup was incomplete. OctoPrint will then startup + # in safe mode + incompleteStartup: false + + # Set this to true to make OctoPrint ignore incomplete startups. Helpful for development. + ignoreIncompleteStartup: false + # Secret key for encrypting cookies and such, randomly generated on first run secretKey: someSecretKey @@ -1058,6 +1104,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:: @@ -1087,14 +1142,14 @@ Settings for the built-in slicing support: slicing: # Whether to enable slicing support or not - enabled: + enabled: true # Default slicer to use - defaultSlicer: cura + defaultSlicer: null # Default slicing profiles per slicer defaultProfiles: - cura: ... + curalegacy: ... .. _sec-configuration-config_yaml-system: @@ -1165,7 +1220,7 @@ Use `Javascript regular expressions ``: the plugin ````, e.g. ``octoprint.plugins.discovery`` to change the log level of - the `Discovery plugin `_ or ``octoprint.plugins.cura`` - to change the log level of the `Cura plugin `_. + the :ref:`Discovery plugin ` or ``octoprint.plugins.backup`` + to change the log level of the :ref:`Backup plugin `. * ``octoprint.slicing``: the slicing sub system This list will be expanded when deemed necessary. diff --git a/docs/development/environment.rst b/docs/development/environment.rst index 8308712b7..2fa09aac3 100644 --- a/docs/development/environment.rst +++ b/docs/development/environment.rst @@ -14,18 +14,25 @@ below. * Prerequisites: * `Python 2.7 `_ including ``pip``, ``setuptools`` and ``virtualenv`` + * `Python 3.7 `_ including ``pip``, ``setuptools`` and ``virtualenv`` * `Git `_ - * Checkout the OctoPrint sources from their Git repository: ``git clone https://github.com/foosel/OctoPrint.git`` + * Checkout the OctoPrint sources from their Git repository: + * ``git clone -b devel https://github.com/foosel/OctoPrint.git`` * Enter the checked out source folder: ``cd OctoPrint`` - * Create a virtual environment in the checked out source folder to use for installing and running OctoPrint and its - dependencies (this avoids potential versioning issues for the dependencies with system wide installed - instances): ``virtualenv venv`` - * Activate the virtual environment: ``source venv/bin/activate`` (Linux, MacOS) or - ``source venv/Scripts/activate`` (Git Bash under Windows, see below) - * Update ``pip`` in the virtual environment: ``pip install --upgrade pip`` + * Create virtual environments in the checked out source folder for both Python 2.7 and Python 3.7 to use for + installing and running OctoPrint and its dependencies (this avoids potential versioning issues for the dependencies + with system wide installed instances): + * PY2: ``virtualenv --python=python2 venv2`` + * PY3: ``virtualenv --python=python3 venv3`` + * Activate one of the virtual environments: + * PY2: ``source venv2/bin/activate`` (Linux, MacOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below) + * PY3: ``source venv3/bin/activate`` (Linux, MacOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below) + * Update ``pip`` in the virtual environment: + * ``pip install --upgrade pip`` * Install OctoPrint in `"editable" mode `_, - including its regular *and* development and plugin development dependencies: ``pip install -e .[develop,plugins]`` + including its regular *and* development and plugin development dependencies: + * ``pip install -e .[develop,plugins]`` When the virtual environment is activated you can then: @@ -33,11 +40,19 @@ When the virtual environment is activated you can then: * run the test suite from the checked out source folder via ``nosetests --with-doctest`` * build the documentation from the ``docs`` sub folder of the checked out sources via ``sphinx-build -b html . _build`` +To switch the activated virtual environment, simply activate the new environment as described above. + +To deactivate the virtual environment and return to the system's default Python: ``deactivate``. + .. _sec-development-environment-source-linux: Linux ..... +.. todo:: + + This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. + This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different location, please substitute accordingly. @@ -70,7 +85,7 @@ Then: .. code-block:: none cd ~/devel - git clone https://github.com/foosel/OctoPrint.git + git clone -b devel https://github.com/foosel/OctoPrint.git cd OctoPrint virtualenv venv source ./venv/bin/activate @@ -85,12 +100,16 @@ environment. Windows ....... +.. todo:: + + This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. + This assumes you'll host your OctoPrint development checkout at ``C:\Devel\OctoPrint``. If you want to use a different location, please substitute accordingly. First download & install: - * `Python 2.7.12 Windows x86 MSI installer `_ + * `Python 2.7.15 Windows x86 MSI installer `_ * make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too @@ -120,6 +139,10 @@ Mac OS X This guide is based on the `Setup Guide for Mac OS X on OctoPrint's wiki `_. Please report back if it works for you, due to lack of access to a Mac I cannot test it myself. Thanks. +.. todo:: + + This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. + This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different location, please substitute accordingly. @@ -158,6 +181,10 @@ You'll need a user account with administrator privileges. IDE Setup --------- +.. todo:: + + This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. + .. todo:: Using another IDE than the ones below? Please send a diff --git a/docs/events/index.rst b/docs/events/index.rst index a97e7e385..dec5f44f1 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 @@ -47,6 +38,13 @@ Example - event: PrintDone command: python ~/growl.py -t mygrowlserver -d "Completed {file}" -a OctoPrint -i http://raspi/Octoprint_logo.png type: system + - event: + - PrintStarted + - PrintFailed + - PrintDone + - PrintCancelled + command: python ~/growl.py -t mygrowlserver -d "Event {__eventname} ({name})" -a OctoPrint -i http://raspi/Octoprint_logo.png + type: system - event: Connected command: - M115 @@ -62,6 +60,7 @@ Placeholders You can use the following generic placeholders in your event hooks: * ``{__currentZ}``: the current Z position of the head if known, -1 if not available + * ``{__eventname}`` : the name of the event hook being triggered * ``{__filename}`` : name of currently selected file, or ``NO FILE`` if no file is selected * ``{__filepath}`` : path in origin location of currently selected file, or ``NO FILE`` if no file is selected * ``{__fileorigin}`` : origin of currently selected file, or ``NO FILE`` if no file is selected @@ -85,6 +84,12 @@ and its origin via the placeholder ``{origin}``. Available Events ================ +.. note:: + + Plugins may add additional events via the :ref:`octoprint.events.register_custom_events hook `. + +.. _sec-events-available_events-server: + Server ------ @@ -99,7 +104,8 @@ ClientOpened Payload: - * ``remoteAddress``: the remote address (IP) of the client that connected + * ``remoteAddress``: the remote address (IP) of the client that connected. On the push socket only available with + a valid login session. **Note:** Name changed in version 1.1.0 @@ -110,6 +116,19 @@ ClientClosed * ``remoteAddress``: the remote address (IP) of the client that disconnected +UserLoggedIn + A user logged in. On the push socket only available with a valid login session with admin rights. + + Payload: + + * ``username``: the name of the user who logged in + +UserLoggedOut + A user logged out. On the push socket only available with a valid login session with admin rights. + + Payload: + * ``username``: the name of the user who logged out + ConnectivityChanged The server's internet connectivity changed @@ -118,6 +137,8 @@ ConnectivityChanged * ``old``: Old connectivity value (true for online, false for offline) * ``new``: New connectivity value (true for online, false for offline) +.. _sec-events-available_events-printer_commmunication: + Printer communication --------------------- @@ -141,7 +162,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: @@ -156,6 +178,8 @@ PrinterStateChanged :func:`~octoprint.printer.PrinterInterface.get_state_id` for possible values. * ``state_string``: Text representation of the new state. +.. _sec-events-available_events-file_handling: + File handling ------------- @@ -169,9 +193,7 @@ Upload .. deprecated:: 1.3.0 - * ``file``: the file's path within its storage location - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's path within its storage location. To be removed in 1.4.0. FileAdded A file has been added to a storage. @@ -253,9 +275,7 @@ MetadataAnalysisStarted .. deprecated:: 1.3.0 - * ``file``: the file's path within its storage location - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's path within its storage location. To be removed in 1.4.0. MetadataAnalysisFinished The metadata analysis of a file has finished. @@ -269,9 +289,7 @@ MetadataAnalysisFinished .. deprecated:: 1.3.0 - * ``file``: the file's path within its storage location - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's path within its storage location. To be removed in 1.4.0. FileSelected A file has been selected for printing. @@ -284,10 +302,8 @@ FileSelected .. deprecated:: 1.3.0 - * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``) - * ``filename``: the file's name - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. + * ``filename``: the file's name. To be removed in 1.4.0. FileDeselected No file is selected any more for printing. @@ -311,6 +327,8 @@ TransferDone * ``local``: the file's name as stored locally * ``remote``: the file's name as stored on SD +.. _sec-events-available_events-printing: + Printing -------- @@ -322,13 +340,14 @@ PrintStarted * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``user``: the user who started the print job (if available) .. deprecated:: 1.3.0 - * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``) - * ``filename``: the file's name - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. + * ``filename``: the file's name. To be removed in 1.4.0. PrintFailed A print failed. @@ -338,13 +357,15 @@ PrintFailed * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``time``: the elapsed time of the print when it failed, in seconds (float) + * ``reason``: the reason the print failed, either ``cancelled`` or ``error`` .. deprecated:: 1.3.0 - * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``) - * ``filename``: the file's name - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. + * ``filename``: the file's name. To be removed in 1.4.0. PrintDone A print completed successfully. @@ -354,14 +375,14 @@ PrintDone * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) * ``time``: the time needed for the print, in seconds (float) .. deprecated:: 1.3.0 - * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``) - * ``filename``: the file's name - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. + * ``filename``: the file's name. To be removed in 1.4.0. PrintCancelling The print is about to be cancelled. @@ -371,6 +392,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 +405,12 @@ PrintCancelled * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` - * ``position``: the print head position at the time of cancelling, if available + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``time``: the elapsed time of the print when it was cancelled, in seconds (float) + * ``user``: the user who cancelled the print job (if available) + * ``position``: the print head position at the time of cancelling (if available, not available if recording of the + position on cancel is disabled) * ``position.x``: x coordinate, as reported back from the firmware through `M114` * ``position.y``: y coordinate, as reported back from the firmware through `M114` * ``position.z``: z coordinate, as reported back from the firmware through `M114` @@ -395,10 +424,8 @@ PrintCancelled .. deprecated:: 1.3.0 - * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``) - * ``filename``: the file's name - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. + * ``filename``: the file's name. To be removed in 1.4.0. PrintPaused The print has been paused. @@ -408,7 +435,11 @@ PrintPaused * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` - * ``position``: the print head position at the time of pausing, if available + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``user``: the user who paused the print job (if available) + * ``position``: the print head position at the time of pausing (if available, not available if the recording of + the position on pause is disabled or the pause is completely handled by the printer's firmware) * ``position.x``: x coordinate, as reported back from the firmware through `M114` * ``position.y``: y coordinate, as reported back from the firmware through `M114` * ``position.z``: z coordinate, as reported back from the firmware through `M114` @@ -422,10 +453,8 @@ PrintPaused .. deprecated:: 1.3.0 - * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``) - * ``filename``: the file's name - - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. + * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. + * ``filename``: the file's name. To be removed in 1.4.0. PrintResumed The print has been resumed. @@ -435,13 +464,16 @@ PrintResumed * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``user``: the user who resumed the print job (if available) .. deprecated:: 1.3.0 - * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``) - * ``filename``: the file's name + * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0. + * ``filename``: the file's name. To be removed in 1.4.0. - Still available for reasons of backwards compatibility. Will be removed with 1.4.0. +.. _sec-events-available_events-gcode_processing: GCODE processing ---------------- @@ -504,6 +536,8 @@ ToolChange * ``old``: old tool index * ``new``: new tool index +.. _sec-events-available_events-timelapses: + Timelapses ---------- @@ -558,6 +592,8 @@ MovieFailed returned a non-0 return code, ``no_frames`` if no frames were captured that could be rendered to a timelapse, or ``unknown`` for any other reason of failure to render. +.. _sec-events-available_events-slicing: + Slicing ------- @@ -566,6 +602,7 @@ SlicingStarted Payload: + * ``slicer``: the used slicer * ``stl``: the STL's filename * ``stl_location``: the STL's location * ``gcode``: the sliced GCODE's filename @@ -577,6 +614,7 @@ SlicingDone Payload: + * ``slicer``: the used slicer * ``stl``: the STL's filename * ``stl_location``: the STL's location * ``gcode``: the sliced GCODE's filename @@ -589,6 +627,7 @@ SlicingCancelled Payload: + * ``slicer``: the used slicer * ``stl``: the STL's filename * ``stl_location``: the STL's location * ``gcode``: the sliced GCODE's filename @@ -599,6 +638,7 @@ SlicingFailed Payload: + * ``slicer``: the used slicer * ``stl``: the STL's filename * ``stl_location``: the STL's location * ``gcode``: the sliced GCODE's filename @@ -614,7 +654,7 @@ SlicingProfileAdded * ``profile``: the profile that was added SlicingProfileModified - A new slicing profile was modified. + A slicing profile was modified. Payload: @@ -629,8 +669,25 @@ SlicingProfileDeleted * ``slicer``: the slicer for which the profile was deleted * ``profile``: the profile that was deleted +.. _sec-events-available_events-settings: + Settings -------- SettingsUpdated - The internal settings were updated. + The settings were updated via the REST API. + + This event may also be triggered if calling code of :py:class:`octoprint.settings.Settings.save` or + :py:class:`octoprint.plugin.PluginSettings.save` sets the ``trigger_event`` parameter to ``True``. + +.. _sec-events-available_events-printer_profile: + +Printer Profile +-------- + +PrinterProfileModified + A printer profile was modified. + + Payload: + + * ``identifier``: the identifier of the modified printer profile diff --git a/docs/features/accesscontrol.rst b/docs/features/accesscontrol.rst index 3207b1c42..06bcc253e 100644 --- a/docs/features/accesscontrol.rst +++ b/docs/features/accesscontrol.rst @@ -21,17 +21,23 @@ Commands, which are admin-only. If Access Control is disabled, everything is directly accessible. **That also includes all administrative functionality as well as full control over the -printer!** +printer**, and without the need for an :ref:`API key `! Upon first start a configuration wizard is provided which allows configuration of the first administrator account or alternatively disabling Access Control (which is **NOT** recommended for systems that are directly accessible via the -Internet!). +internet or other untrusted networks!). .. hint:: If you plan to have your OctoPrint instance accessible over the internet, - **always enable Access Control**. + **always enable Access Control** and ideally **don't make it accessible to + everyone over the internet but instead use a VPN** or at the very least + HTTP basic authentication on a layer above OctoPrint. + + A physical device that includes heaters and stepper motors really should not be + publicly reachable by everyone with an internet connection, even with access + control enabled. .. _sec-features-access_control-rerunning_wizard: diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index 4fb891eb4..73d8916f8 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -157,9 +157,13 @@ The ``disable_hotends`` snippet is defined as follows: .. code-block:: jinja :caption: Default ``disable_hotends`` snippet + {% if printer_profile.extruder.sharedNozzle %} + M104 T0 S0 + {% else %} {% for tool in range(printer_profile.extruder.count) %} M104 T{{ tool }} S0 {% endfor %} + {% endif %} The ``disable_bed`` snippet is defined as follows: diff --git a/docs/features/safemode.rst b/docs/features/safemode.rst index c90d30d60..56445e9e4 100644 --- a/docs/features/safemode.rst +++ b/docs/features/safemode.rst @@ -5,19 +5,20 @@ Safe mode ********* With the advent of support for plugins in OctoPrint, it quickly became apparent that some of the bugs -reported on OctoPrint's bug tracker were actually bugs with installed third party plugins instead of -OctoPrint itself. +reported on OctoPrint's bug tracker were actually bugs with installed third party plugins or language +packs instead of OctoPrint itself. To allow an easier identification of these cases, OctoPrint 1.3.0 introduced safe mode. Starting -OctoPrint in safe mode disables all plugins that are not bundled with OctoPrint, allowing to easier -identify most cases where a third party plugin is the culprit of an observed issue. +OctoPrint in safe mode disables all plugins (and starting with 1.3.13 also all language packs) that are +not bundled with OctoPrint, allowing to easier identify most cases where a third party plugin or language +pack is the culprit of an observed issue. -Additionally, OctoPrint allows uninstalling plugins in this mode, allowing recovery from cases where -a third party plugin causes the server to not start up or the web interface to not render or function -correctly anymore. +Additionally, OctoPrint allows uninstalling plugins and language packs in this mode, allowing recovery +from cases where a third party addition causes the server to not start up or the web interface to not +render or function correctly anymore. Whenever reporting an issue with OctoPrint, please always attempt to reproduce it in safe mode as well to -ensure it really is an issue in OctoPrint itself and now caused by one of your installed third party plugins. +ensure it really is an issue in OctoPrint itself and now caused by one of your installed third party additions. .. _sec-features-safemode-how: @@ -73,11 +74,17 @@ When OctoPrint is running in safe mode the following changes to its normal opera * OctoPrint will not enable any of the installed third party plugins. OctoPrint considers all plugins third party plugins that do not ship with OctoPrint's sources, so any plugins installed either via `pip` or - into OctoPrint's plugin folder at ``~/.octoprint/plugins`` (Linux), ``%APPDATA%/OctoPrint`` (Windows) and - ``~/Library/Application Support/OctoPrint`` (MacOS). + into OctoPrint's plugin folder at ``~/.octoprint/plugins`` (Linux), ``%APPDATA%/OctoPrint/plugins`` (Windows) and + ``~/Library/Application Support/OctoPrint/plugins`` (MacOS). + * OctoPrint will not enable any of the installed third party language packs. OctoPrint considers all language packs + third party language packs that do not ship with OctoPrint's sources, so any language plugins installed + through the language pack manager within settings and/or stored in the language pack folder at + ``~/.octoprint/translations`` (Linux), ``%APPDATA%/OctoPrint/translations`` (Windows) or + ``~/Library/Application Support/OctoPrint/translations`` (MacOS). * OctoPrint will still allow to uninstall third party plugins through the built-in Plugin Manager. * OctoPrint will still allow to disable (bundled) plugins that are still enabled. * OctoPrint will not allow to enable third party plugins. + * OctoPrint will still allow to manage language packs. * OctoPrint's web interface will display a notification to remind you that it is running in safe mode. 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/images/features-safemode-notification.png b/docs/images/features-safemode-notification.png index 4cdaa5f40..b9331c0b7 100644 Binary files a/docs/images/features-safemode-notification.png and b/docs/images/features-safemode-notification.png differ diff --git a/docs/index.rst b/docs/index.rst index ac0ed3ec5..cdfa4b217 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -11,7 +11,7 @@ and released under the `GNU Affero General Public License V3 `_. -The community forum is available at `discourse.octoprint.org `_. +The community forum is available at `community.octoprint.org `_. The FAQ can be accessed by following `faq.octoprint.org `_. @@ -23,7 +23,7 @@ If you enjoy OctoPrint, please consider becoming a regular supporter! .. note:: This documentation currently focuses primarily on developers and less on end users. If you are interested in - helping to change this, please get in touch `on the forum `_! + helping to change this, please get in touch `on the forum `_! Contents ======== 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/jsclientlib/printer.rst b/docs/jsclientlib/printer.rst index 14df29834..d79d3d6de 100644 --- a/docs/jsclientlib/printer.rst +++ b/docs/jsclientlib/printer.rst @@ -210,6 +210,64 @@ :param object opts: Additional options for the request :returns Promise: A `jQuery Promise `_ for the request's response +.. js:function:: OctoPrintClient.printer.getChamberState(data, opts) + + Retrieves the current printer chamber state/temperature information, and optionally also the temperature + history. + + The ``flags`` object can be used to specify the data to retrieve further via the following + properties: + + * ``history``: a boolean value to specify whether the temperature history should be included (``true``) + or not (``false``), defaults to it not being included + * ``limit``: an integer value to specify how many history entries to include + + See :ref:`Retrieve the current bed state ` for more details. + + :param object flags: Flags that further specify which data to retrieve, see above for details + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.printer.setChamberTargetTemperature(target, opts) + + Sets the given temperature on the printer's heated chamber (if available). + + ``target`` is expected to be the target temperature as a float value. + + **Example:** + + Set the chamber to 50°C. + + .. code-block:: javascript + + OctoPrint.printer.setChamberTargetTemperature(50.0); + + See the ``target`` command in :ref:`Issue a chamber command ` for more details. + + :param float target: The target to set + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.printer.setChamberTemperatureOffset(offset, opts) + + Sets the given temperature offset for the printer's heated chamber (if available). + + ``offset`` is expected to be the temperature offset to set. + + **Example:** + + Set the offset for the chamber to -5°C. + + .. code-block:: javascript + + OctoPrint.printer.setChamberTemperatureOffset(-5); + + See the ``offset`` command in :ref:`Issue a chamber command ` for more details. + + :param object offsets: The offsets to set + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + .. js:function:: OctoPrintClient.printer.jog(amounts, opts) Jogs the specified axes by the specified ``amounts``. diff --git a/docs/modules/users.rst b/docs/modules/users.rst index f147a46a3..2cf3163f5 100644 --- a/docs/modules/users.rst +++ b/docs/modules/users.rst @@ -1,9 +1,9 @@ .. _sec-modules-users: -octoprint.users ---------------- +octoprint.access.users +---------------------- -.. automodule:: octoprint.users +.. automodule:: octoprint.access.users :members: diff --git a/docs/modules/util.rst b/docs/modules/util.rst index 32a61b728..156a25ff3 100644 --- a/docs/modules/util.rst +++ b/docs/modules/util.rst @@ -6,4 +6,10 @@ octoprint.util .. automodule:: octoprint.util :members: +.. _sec-modules-util-commandline: +octoprint.util.commandline +-------------------------- + +.. automodule:: octoprint.util.commandline + :members: diff --git a/docs/plugins/controlproperties.rst b/docs/plugins/controlproperties.rst index 3bbb8d5ea..c8ac018a0 100644 --- a/docs/plugins/controlproperties.rst +++ b/docs/plugins/controlproperties.rst @@ -13,6 +13,7 @@ plugin subsystem about themselves. These are simple package attributes defined i # ... __plugin_name__ = "My Plugin" + __plugin_pythoncompat__ = ">=2.7,<4" def __plugin_load__(): # whatever you need to do to load your plugin, if anything at all pass @@ -52,6 +53,20 @@ The following properties are recognized: ``__plugin_license__`` License of your plugin, optional, overrides the license specified in ``setup.py`` if provided. +.. _sec-plugins-controlproperties-plugin_pythoncompat: + +``__plugin_pythoncompat__`` + Python compatibility string of your plugin, optional, defaults to ``>=2.7,<3`` if not set and thus Python 2 but no + Python 3 compatibility. + + If your plugin is compatible to Python 3, you should set this to ``>=2.7,<4``, otherwise your plugin will not load + on OctoPrint instances installed under Python 3. + + .. code-block:: python + + __plugin_pythoncompat__ = ">=2.7,<4" + + .. _sec-plugins-controlproperties-plugin_implementation: ``__plugin_implementation__`` diff --git a/docs/plugins/gettingstarted.rst b/docs/plugins/gettingstarted.rst index ac43e92ad..c83fbb7de 100644 --- a/docs/plugins/gettingstarted.rst +++ b/docs/plugins/gettingstarted.rst @@ -54,8 +54,8 @@ We'll start at the most basic form a plugin can take - just a few simple lines o .. code-block:: python :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals __plugin_name__ = "Hello World" __plugin_version__ = "1.0.0" @@ -89,8 +89,8 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t :emphasize-lines: 4-8,13 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -289,8 +289,8 @@ and ``__plugin_description__`` from ``__init__.py``: .. code-block:: python :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -314,8 +314,8 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the :emphasize-lines: 10 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -362,8 +362,8 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class: :emphasize-lines: 7 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -428,8 +428,8 @@ Let's take a look at how all that would look in our plugin's ``__init__.py``: :emphasize-lines: 8, 10, 12-13 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -462,8 +462,8 @@ Adjust your plugin's ``__init__.py`` like this: :emphasize-lines: 15-16 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -569,8 +569,8 @@ again since we don't use that anymore: :emphasize-lines: 15-19 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -666,8 +666,8 @@ like so: :emphasize-lines: 9,22-25 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -846,8 +846,8 @@ a reference to our CSS file: :emphasize-lines: 26 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin @@ -931,8 +931,8 @@ Then adjust our returned assets to include our LESS file as well: :emphasize-lines: 27 :linenos: - # coding=utf-8 - from __future__ import absolute_import + # -*- coding: utf-8 -*- + from __future__ import absolute_import, unicode_literals import octoprint.plugin diff --git a/docs/plugins/helpers.rst b/docs/plugins/helpers.rst index c411d3776..f8c5424f3 100644 --- a/docs/plugins/helpers.rst +++ b/docs/plugins/helpers.rst @@ -3,7 +3,7 @@ Helpers ======= -Helpers are methods that plugin can exposed to other plugins in order to make common functionality available on the +Helpers are methods that plugins can expose to other plugins in order to make common functionality available on the system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``. An example for providing some helper functions to the system can be found in the diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 4f4b3d5aa..8d35ea5a6 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -28,6 +28,7 @@ or as ``postfix`` (after the existing lines). .. code-block:: python :linenos: + from past import basestring self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.scripts") # ... @@ -35,7 +36,7 @@ or as ``postfix`` (after the existing lines). for hook in self._gcodescript_hooks: try: retval = self._gcodescript_hooks[hook](self, "gcode", scriptName) - except: + except Exception: self._logger.exception("Error while processing gcodescript hook %s" % hook) else: if retval is None: @@ -44,10 +45,8 @@ or as ``postfix`` (after the existing lines). continue def to_list(data): - if isinstance(data, str): - data = map(str.strip, data.split("\n")) - elif isinstance(data, unicode): - data = map(unicode.strip, data.split("\n")) + if isinstance(data, basestring): + data = map(x.strip() for x in data.split("\n")) if isinstance(data, (list, tuple)): return list(data) @@ -201,31 +200,6 @@ Available plugin hooks .. contents:: :local: -.. _sec-plugins-hook-accesscontrol-appkey: - -octoprint.accesscontrol.appkey -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. py:function:: acl_appkey_hook(*args, **kwargs) - - By handling this hook plugins may register additional :ref:`App session key providers ` - within the system. - - Overrides this to return your additional app information to be used for validating app session keys. You'll - need to return a list of 3-tuples of the format (id, version, public key). - - The ``id`` should be the (unique) identifier of the app. Using a domain prefix might make sense here, e.g. - ``org.octoprint.example.MyApp``. - - ``version`` should be a string specifying the version of the app for which the public key is valid. You can - provide the string ``any`` here, in which case the provided public key will be valid for all versions of the - app for which no specific public key is defined. - - Finally, the public key is expected to be provided as a PKCS1 string without newlines. - - :return: A list of 3-tuples as described above - :rtype: list - .. _sec-plugins-hook-accesscontrol-keyvalidator: octoprint.accesscontrol.keyvalidator @@ -237,7 +211,7 @@ octoprint.accesscontrol.keyvalidator ``apikey`` will be the API key as read from the request headers. - Hook handlers are expected to return a :class:`~octoprint.users.User` instance here that will then be considered that + Hook handlers are expected to return a :class:`~octoprint.access.users.User` instance here that will then be considered that user making the request. By returning ``None`` or nothing at all, hook handlers signal that they do not handle the provided key. @@ -255,7 +229,7 @@ octoprint.accesscontrol.keyvalidator :param str apikey: The API key to validate :return: The user in whose name the request will be processed further - :rtype: :class:`~octoprint.users.User` + :rtype: :class:`~octoprint.access.users.User` .. _sec-plugins-hook-cli-commands: @@ -380,10 +354,10 @@ octoprint.cli.commands OctoPrint's CLI. :rtype: list -.. _sec-plugins-hook-comm-firmware-info: +.. _sec-plugins-hook-comm-protocol-firmware-info: -octoprint.comm.firmware.info -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +octoprint.comm.protocol.firmware.info +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. py:function:: firmware_info_hook(comm_instance, firmware_name, firmware_data, *args, **kwargs) @@ -413,10 +387,10 @@ octoprint.comm.firmware.info :param str firmware_name: The name of the parsed capability :param dict firmware_data: All data contained in the ``M115`` report -.. _sec-plugins-hook-comm-firmware-capabilities: +.. _sec-plugins-hook-comm-protocol-firmware-capabilities: -octoprint.comm.firmware.capabilities -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +octoprint.comm.firmware.protocol.capabilities +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. py:function:: firmware_capability_hook(comm_instance, capability, enabled, already_defined, *args, **kwargs) @@ -762,9 +736,10 @@ octoprint.comm.protocol.scripts make sure to only proceed with returning additional scripts if the ``script_type`` and ``script_name`` match handled scripts. If not, None should be returned directly. - If the hook handler has something to add to the specified script, it may return a 2-tuple or a 3-tuple with the first entry + If the hook handler has something to add to the specified script, it may return a 2-tuple, a 3-tuple or a 4-tuple with the first entry defining the prefix (what to *prepend* to the script in question), the second entry defining the postfix (what to - *append* to the script in question), and finally if desired a dictionary of variables to be made available to the script. Both prefix and postfix can be None to signify that nothing should be prepended + *append* to the script in question), and finally if desired a dictionary of variables to be made available to the script on third and additional tags to set on the + commands on fourth position. Both prefix and postfix can be None to signify that nothing should be prepended respectively appended. The returned prefix and postfix entries may be either iterables of script lines or a string including newlines of the script lines (which @@ -903,6 +878,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 @@ -1029,9 +1032,8 @@ octoprint.printer.factory * ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue` * ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager` * ``file_manager``: The :class:`~octoprint.filemanager.FileManager` - * ``app_session_manager``: The :class:`~octoprint.server.util.flask.AppSessionManager` * ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager` - * ``user_manager``: The :class:`~octoprint.users.UserManager` + * ``user_manager``: The :class:`~octoprint.access.users.UserManager` * ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache` If the factory returns anything but ``None``, it will be assigned to the global ``printer`` instance. @@ -1089,6 +1091,139 @@ octoprint.printer.estimation.factory :return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method :rtype: class or function +.. _sec-plugins-hook-octoprint-printer-sdcardupload: + +octoprint.printer.sdcardupload +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: sd_card_upload_hook(printer, filename, path, start_callback, success_callback, failure_callback, *args, **kwargs) + + Via this hook plugins can change the way files are being uploaded to the sd card of the printer. + + Implementations **must** call the provided ``start_callback`` on start of the file transfer and either the ``success_callback`` + or ``failure_callback`` on the end of the file transfer, depending on whether it was successful or not. + + The ``start_callback`` has the following signature: + + .. code-block:: python + + def start_callback(local_filename, remote_filename): + # ... + + ``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file + to be created on the ``sdcard`` storage. + + ``success_callback`` and ``failure_callback`` both have the following signature: + + .. code-block:: python + + def success_or_failure_callback(local_filename, remote_filename, elapsed): + # ... + + ``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file + to be created on the ``sdcard`` storage. ``elapsed`` is the elapsed time in seconds. + + If the hook is going to handle the upload, it must return the (future) remote filename of the file on the ``sdcard`` + storage. If it returns ``None`` (or an otherwise falsy value), OctoPrint will interpret this as the hook not going to + handle the file upload, in which case the next hook or - if no other hook is registered - the default implementation + will be called. + + **Example** + + The following example creates a dummy SD card uploader that does nothing but sleep for ten seconds when a file + is supposed to be uploaded. Note that the long running process of sleeping for ten seconds is extracted into its + own thread, which is important in order to not block the main application! + + .. code-block:: python + + import threading + import logging + import time + + def nop_upload_to_sd(printer, filename, path, sd_upload_started, sd_upload_succeeded, sd_upload_failed, *args, **kwargs): + logger = logging.getLogger(__name__) + + remote_name = printer._get_free_remote_name(filename) + logger.info("Starting dummy SDCard upload from {} to {}".format(filename, remote_name)) + + sd_upload_started(filename, remote_name) + + def process(): + logger.info("Sleeping 10s...") + time.sleep(10) + logger.info("And done!") + sd_upload_succeeded(filename, remote_name, 10) + + thread = threading.Thread(target=process) + thread.daemon = True + thread.start() + + return remote_name + + __plugin_name__ = "No-op SDCard Upload Test" + __plugin_hooks__ = { + "octoprint.printer.sdcardupload": nop_upload_to_sd + } + + .. versionadded:: 1.3.11 + + :param object printer: the :py:class:`~octoprint.printer.PrinterInterface` instance the hook was called from + :param str filename: filename on the ``local`` storage + :param str path: path of the file in the local file system + :param function sd_upload_started: callback for when the upload started + :param function sd_upload_success: callback for successful finish of upload + :param function sd_upload_failure: callback for failure of upload + :return: the name of the file on the ``sdcard`` storage or ``None`` + :rtype: string or ``None`` + +.. _sec-plugins-hook-server-http-after_request: + +octoprint.server.api.after_request +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: after_request_handlers_hook(*args, **kwargs) + + Allows adding additional after-request-handlers to API endpoints defined by OctoPrint itself and installed plugins. + + Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a + usage example. + + .. important:: + + Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully. + +.. _sec-plugins-hook-server-http-before_request: + +octoprint.server.api.before_request +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: after_request_handlers_hook(*args, **kwargs) + + Allows adding additional before-request-handlers to API endpoints defined by OctoPrint itself and installed plugins. + + Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a + usage example. + + .. important:: + + Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully. + +.. _sec-plugins-hook-server-http-access_validator: + +octoprint.server.http.access_validator +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: access_validator_hook(request, *args, **kwargs) + + Allows adding additional access validators to the default tornado routers. + + Your plugin might need to this to restrict acccess to downloads and webcam snapshots further. See the bundled + "Force Login" plugin for a usage example. + + .. important:: + + Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully. + .. _sec-plugins-hook-server-http-bodysize: octoprint.server.http.bodysize @@ -1163,6 +1298,14 @@ octoprint.server.http.routes view of the blueprint will thus not be reachable since processing of the request will directly be handed over to your defined handler class. + .. important:: + + If you want your route to support CORS if it's enabled in OctoPrint, your `RequestHandler `_ + needs to implement the :class:`~octoprint.server.util.tornado.CorsSupportMixin` for this to work. Note that all of + :class:`~octoprint.server.util.tornado.LargeResponseHandler`, :class:`~octoprint.server.util.tornado.UrlProxyHandler`, + :class:`~octoprint.server.util.tornado.StaticDataHandler` and :class:`~octoprint.server.util.tornado.DeprecatedEndpointHandler` + already implement this mixin. + .. important:: Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully. @@ -1190,6 +1333,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 @@ -1331,12 +1527,12 @@ octoprint.ui.web.templatetypes .. _sec-plugins-hook-users-factory: -octoprint.users.factory -~~~~~~~~~~~~~~~~~~~~~~~ +octoprint.access.users.factory +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs) - Return a :class:`~octoprint.users.UserManager` instance to use as global user manager object. This will + Return a :class:`~octoprint.access.users.UserManager` instance to use as global user manager object. This will be called only once during initial server startup. The provided ``components`` is a dictionary containing the already initialized system components: @@ -1347,7 +1543,6 @@ octoprint.users.factory * ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue` * ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager` * ``file_manager``: The :class:`~octoprint.filemanager.FileManager` - * ``app_session_manager``: The :class:`~octoprint.server.util.flask.AppSessionManager` * ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager` * ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache` @@ -1355,7 +1550,7 @@ octoprint.users.factory If none of the registered factories return a user manager instance, the class referenced by the ``config.yaml`` entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock - :class:`~octoprint.users.FilebasedUserManager` will be instantiated, linked to the default user storage + :class:`~octoprint.access.users.FilebasedUserManager` will be instantiated, linked to the default user storage file ``~/.octoprint/users.yaml``. :param dict components: System components to use for user manager instance initialization diff --git a/docs/plugins/injectedproperties.rst b/docs/plugins/injectedproperties.rst index 7b4bf311a..15ee482d2 100644 --- a/docs/plugins/injectedproperties.rst +++ b/docs/plugins/injectedproperties.rst @@ -41,10 +41,8 @@ An overview of these properties follows. OctoPrint's file manager, an instance of :class:`octoprint.filemanager.FileManager`. ``self._printer`` OctoPrint's printer management object, an instance of :class:`octoprint.printer.PrinterInterface`. -``self._app_session_manager`` - OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`. ``self._user_manager`` - OctoPrint's user manager, an instance of :class:`octoprint.users.UserManager`. + OctoPrint's user manager, an instance of :class:`octoprint.access.users.UserManager`. ``self._connectivity_checker`` OctoPrint's connectivity checker, an instance of :class:`octoprint.util.ConnectivityChecker`. diff --git a/docs/plugins/mixins.rst b/docs/plugins/mixins.rst index fa73c1757..386ff3d26 100644 --- a/docs/plugins/mixins.rst +++ b/docs/plugins/mixins.rst @@ -68,11 +68,14 @@ calls are done is as follows: * Plugins with a return value that is not ``None`` for :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key` for the provided sorting context will be ordered among each other first. If the returned order number is equal for - two or more implementations, the plugin's identifier will be the next sorting criteria. - * After that follow plugins which returned ``None`` (the default). They are sorted by their identifier. + two or more implementations, they will be sorted first by whether they come bundled with OctoPrint or not, then by + their identifier. + * After that follow plugins which returned ``None`` (the default). They are first sorted by whether they come bundled + with OctoPrint or not, then by their identifier. -Example: Consider three plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called -``plugin_a``, ``plugin_b`` and ``plugin_c``. ``plugin_a`` doesn't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`. +Example: Consider four plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called +``plugin_a``, ``plugin_b``, ``plugin_c`` and ``plugin_d``, the latter coming bundled with OctoPrint. ``plugin_a`` +and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`. ``plugin_b`` and ``plugin_c`` both return ``1`` for the sorting context ``StartupPlugin.on_startup``, ``None`` otherwise: .. code-block:: python @@ -99,7 +102,7 @@ Example: Consider three plugin implementations implementing the :class:`~octopri class PluginB(octoprint.plugin.StartupPlugin): - def get_sorting_key(context): + def get_sorting_key(self, context): if context == "StartupPlugin.on_startup": return 1 return None @@ -120,7 +123,7 @@ Example: Consider three plugin implementations implementing the :class:`~octopri class PluginC(octoprint.plugin.StartupPlugin): - def get_sorting_key(context): + def get_sorting_key(self, context): if context == "StartupPlugin.on_startup": return 1 return None @@ -134,13 +137,45 @@ Example: Consider three plugin implementations implementing the :class:`~octopri __plugin_implementation__ = PluginC() +.. code-block:: python + :linenos: + :caption: plugin_d.py + + # in this example this is bundled with OctoPrint + import octoprint.plugin + + class PluginD(octoprint.plugin.StartupPlugin): + + def on_startup(self, *args, **kwargs): + self._logger.info("PluginD starting up") + + def on_after_startup(self, *args, **kwargs): + self._logger.info("PluginD started up") + + __plugin_implementation__ = PluginD() + OctoPrint will detect that ``plugin_b`` and ``plugin_c`` define a order number, and since it's identical for both (``1``) -will order both plugins based on their plugin identifier. ``plugin_a`` doesn't define a sort key and hence will be -put after the other two. The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_a``. +will order both plugins based first on their bundling status and then on their plugin identifier. +``plugin_a`` and ``plugin_d`` don't define a sort key and hence will be +put after the other two, with ``plugin_d`` coming *before* ``plugin_a`` since it comes bundled with OctoPrint. +The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_d``, ``plugin_a``. Now, the execution order of the ``on_after_startup`` method will be determined based on another sorting context, ``StartupPlugin.on_after_startup`` for which all of the plugins return ``None``. Hence, the execution order of the -``on_after_startup`` method will be purely ordered by plugin identifier, ``plugin_a``, ``plugin_b``, ``plugin_c``. +``on_after_startup`` method will be ordered first by bundle status, then by plugin identifier: ``plugin_d``, ``plugin_a``, ``plugin_b``, ``plugin_c``. + +This will result in the following messages to be generated: + +.. code-block:: plain + + Plugin B starting up + Plugin C starting up + Plugin D starting up + Plugin A starting up + Plugin D started up + Plugin A started up + Plugin B started up + Plugin C started up .. _sec-plugins-mixins-injectedproperties: diff --git a/docs/sphinxext/codeblockext.py b/docs/sphinxext/codeblockext.py index 048b57423..a5ed06548 100644 --- a/docs/sphinxext/codeblockext.py +++ b/docs/sphinxext/codeblockext.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'The MIT License ' @@ -160,10 +160,10 @@ class PygmentsBridgeExt(object): # for py3, recognize interactive sessions, but do not try parsing... lexer = sphinx.highlighting.lexers['pycon3'] elif lang == 'guess': - try: +# try: lexer = sphinx.highlighting.guess_lexer(source) - except Exception: - lexer = sphinx.highlighting.lexers['none'] +# except Exception: +# lexer = sphinx.highlighting.lexers['none'] else: if lang in sphinx.highlighting.lexers: lexer = sphinx.highlighting.lexers[lang] diff --git a/docs/sphinxext/onlineinclude.py b/docs/sphinxext/onlineinclude.py index b6d9a1810..4769faa21 100644 --- a/docs/sphinxext/onlineinclude.py +++ b/docs/sphinxext/onlineinclude.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'The MIT License ' diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 000000000..597e09bdb --- /dev/null +++ b/pytest.ini @@ -0,0 +1,5 @@ +[pytest] +testpaths = src tests +addopts = --doctest-modules + --doctest-repr=octoprint.util:pp + --ignore=src/octoprint/vendor diff --git a/run b/run index 1145a24fd..f67e9cbfd 100755 --- a/run +++ b/run @@ -1,4 +1,6 @@ -#!/usr/bin/env python2 +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals import os import sys @@ -8,15 +10,17 @@ basedir = os.path.dirname(os.path.realpath(__file__)) old = os.path.join(basedir, "octoprint") if os.path.exists(old): # rename left-overs from old file structure - print """ + print(""" Found left-overs from old file structure, renaming to "octoprint.backup". Please remove this manually (I don't dare to do so myself since you might have changes in there I don't know anything about). -""" +""") os.rename(old, os.path.join(basedir, "octoprint.backup")) sys.path.insert(0, os.path.join(basedir, "src")) import octoprint +if len(sys.argv) == 1: + sys.argv.append("serve") octoprint.main() diff --git a/scripts/README.md b/scripts/README.md new file mode 100644 index 000000000..51da00e50 --- /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/system/octoprint.service +``` diff --git a/scripts/octoprint.service b/scripts/octoprint.service new file mode 100644 index 000000000..e71e07b53 --- /dev/null +++ b/scripts/octoprint.service @@ -0,0 +1,12 @@ +[Unit] +Description=The snappy web interface for your 3D printer +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=pi +ExecStart=/home/pi/OctoPrint/venv/bin/octoprint + +[Install] +WantedBy=multi-user.target diff --git a/setup.cfg b/setup.cfg index 4320f0f8a..24ae4b6df 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,6 +1,9 @@ [metadata] license_file = LICENSE.txt +[bdist_wheel] +universal = 1 + [versioneer] VCS = git style = pep440-tag diff --git a/setup.py b/setup.py index 7537b84cf..ae4ba6a9a 100644 --- a/setup.py +++ b/setup.py @@ -9,53 +9,72 @@ import versioneer import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src")) import octoprint_setuptools +import setuptools #----------------------------------------------------------------------------------------------------------------------- +# Supported python versions +# we test against 2.7, 3.6 and 3.7, so that's what we'll mark as supported +PYTHON_REQUIRES = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4" + # Requirements for our application INSTALL_REQUIRES = [ - "flask>=0.12,<0.13", - "werkzeug>=0.11.1,<0.12", - "tornado==4.5.3", - "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 - #"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a - # vendored one - "PyYAML>=3.12,<3.13", - "Flask-Login>=0.4,<0.5", + # the following dependencies are non trivial to update since later versions introduce backwards incompatible + # changes that might affect plugins, or due to other observed problems + + "flask>=0.12,<0.13", # newer versions require newer Jinja versions + "Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't + # guarantee backwards compatibility for plugins and such with that + # version, hence we need to pin to a lower version for now. See #1697 + "tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585 + "regex!=2018.11.6", # avoid broken 2018.11.6. See #2874 + + # anything below this should be checked on releases for new versions + + "Flask-Login>=0.4.1,<0.5", "Flask-Principal>=0.4,<0.5", - "Flask-Babel>=0.11,<0.12", + "Flask-Babel>=0.12,<0.13", "Flask-Assets>=0.12,<0.13", - "markdown>=2.6.4,<2.7", + "werkzeug>=0.15.1,<0.16", + "cachelib>=0.1,<0.2", + "PyYAML>=5.1,<6", + "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.4,<3.5", - "pkginfo>=1.4.2,<1.5", - "requests>=2.18.4,<3", - "semantic_version>=2.6.0,<2.7", - "psutil>=5.4.6,<5.5", - "Click>=6.7,<6.8", + "netifaces>=0.10.9,<0.11", + "pylru>=1.2,<1.3", + "rsa>=4.0,<5", + "pkginfo>=1.5.0.1,<1.6", + "requests>=2.21.0,<3", + "semantic_version>=2.6,<2.7", + "psutil>=5.6.1,<5.7", + "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", - "wrapt>=1.10.11,<1.11", - "futures>=3.1.1,<3.2", - "emoji>=0.4.5,<0.5", - "monotonic>=1.3,<1.4", - "frozendict>=1.2,<1.3" + "future>=0.17,<0.18", + "websocket-client>=0.56,<0.57", + "wrapt>=1.11.1,<1.12", + "emoji>=0.5.1,<0.6", + "frozendict>=1.2,<1.3", + "sentry-sdk==0.7.7", + "filetype>=1.0.5,<2" ] -if sys.platform == "darwin": - INSTALL_REQUIRES.append("appdirs>=1.4.0") +# Python 2 specific requirements +INSTALL_REQUIRES_PYTHON2 = [ + "futures>=3.2,<3.3", + "monotonic>=1.5,<1.6", + "scandir>=1.10,<1.11", + "chainmap>=1.0.3,<1.1", + "typing>=3.6.6,<4" +] + +# OSX specific requirements +INSTALL_REQUIRES_OSX = [ + "appdirs>=1.4.0", +] # Additional requirements for optional install options EXTRA_REQUIRES = dict( @@ -63,28 +82,47 @@ EXTRA_REQUIRES = dict( develop=[ # Testing dependencies "mock>=2.0.0,<3", - "nose>=1.3.0,<1.4", + "pytest>=4.2.1,<5.0", + "pytest-doctest-custom>=1.0.0,<1.1", "ddt", + # linter + "flake8", + # Documentation dependencies "sphinx>=1.6,<1.7", "sphinxcontrib-httpdomain", "sphinxcontrib-mermaid>=0.3", "sphinx_rtd_theme", + "readthedocs-sphinx-ext==0.5.7" ], # Dependencies for developing OctoPrint plugins plugins=[ - "cookiecutter>=1.5,<1.7" + "cookiecutter>=1.6,<1.7" ] ) -# Additional requirements for setup -SETUP_REQUIRES = [] - # Dependency links for any of the aforementioned dependencies DEPENDENCY_LINKS = [] +# adapted from https://hynek.me/articles/conditional-python-dependencies/ +if int(setuptools.__version__.split(".", 1)[0]) < 18: + # no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies + # would get lost there + assert "bdist_wheel" not in sys.argv + + # add optional dependencies for setuptools versions < 18 that don't yet support environment markers + if sys.version_info[0] < 3: + INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2 + + if sys.platform == "darwin": + INSTALL_REQUIRES += INSTALL_REQUIRES_OSX +else: + # environment markers supported + EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2 + EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX + #----------------------------------------------------------------------------------------------------------------------- # Anything below here is just command setup and general setup configuration @@ -154,10 +192,10 @@ def params(): long_description = read_file_contents(os.path.join(here, "README.md")) long_description_content_type = "text/markdown" + python_requires = PYTHON_REQUIRES install_requires = INSTALL_REQUIRES extras_require = EXTRA_REQUIRES dependency_links = DEPENDENCY_LINKS - setup_requires = SETUP_REQUIRES classifiers = [ "Development Status :: 5 - Production/Stable", @@ -176,6 +214,9 @@ def params(): "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: JavaScript", "Topic :: Printing", @@ -188,7 +229,7 @@ def params(): keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint" project_urls={ - "Community Forum": "https://discourse.octoprint.org", + "Community Forum": "https://community.octoprint.org", "Bug Reports": "https://github.com/foosel/OctoPrint/issues", "Source": "https://github.com/foosel/OctoPrint", "Funding": "https://donate.octoprint.org" diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 3ee4ed588..876407781 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -1,7 +1,8 @@ -#!/usr/bin/env python2 -# coding=utf-8 -from __future__ import absolute_import, division, print_function +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals +import io import sys import logging as log @@ -103,8 +104,12 @@ 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"]) \ + and not settings.getBoolean(["server", "ignoreIncompleteStartup"]) \ + 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 +146,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): @@ -293,7 +298,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con config_from_file = {} if os.path.exists(logging_file) and os.path.isfile(logging_file): import yaml - with open(logging_file, "r") as f: + with io.open(logging_file, 'rt', encoding='utf-8') as f: config_from_file = yaml.safe_load(f) # we merge that with the default config @@ -342,9 +347,12 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti import os + # we need this so that octoprint.plugins is in sys.modules and no warnings are caused when loading bundled plugins + import octoprint.plugins + logger = log.getLogger(__name__ + ".startup") - plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True), + plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), "octoprint.plugins", True), settings.getBaseFolder("plugins")] plugin_entry_points = ["octoprint.plugin"] plugin_disabled_list = settings.get(["plugins", "_disabled"]) @@ -363,13 +371,16 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti return True plugin_validators.append(validator) + compatibility_ignored_list = settings.get(["plugins", "_forcedCompatible"]) + from octoprint.plugin import plugin_manager pm = plugin_manager(init=True, plugin_folders=plugin_folders, plugin_entry_points=plugin_entry_points, plugin_disabled_list=plugin_disabled_list, plugin_blacklist=plugin_blacklist, - plugin_validators=plugin_validators) + plugin_validators=plugin_validators, + compatibility_ignored_list=compatibility_ignored_list) settings_overlays = dict() disabled_from_overlays = dict() @@ -399,7 +410,9 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti if not startup: return - sorted_disabled_from_overlays = sorted([(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], key=lambda x: (x[2] is None, x[2], x[0])) + from octoprint.util import sv + + sorted_disabled_from_overlays = sorted([(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], key=lambda x: (x[2] is None, sv(x[2]), sv(x[0]))) disabled_list = pm.plugin_disabled_list already_processed = [] @@ -447,7 +460,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None): def format_blacklist(entries): format_entry = lambda x: "{} ({})".format(x[0], x[1]) if isinstance(x, (list, tuple)) and len(x) == 2 \ else "{} (any)".format(x) - return ", ".join(list(map(format_entry, entries))) + return ", ".join(map(format_entry, entries)) def process_blacklist(entries): result = [] @@ -482,7 +495,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None): if os.stat(path).st_mtime + ttl < time.time(): return None - with bom_aware_open(path, encoding="utf-8", mode="r") as f: + with bom_aware_open(path, encoding="utf-8", mode='rt') as f: result = yaml.safe_load(f) if isinstance(result, list): @@ -496,12 +509,12 @@ def get_plugin_blacklist(settings, connectivity_checker=None): if cache is not None: try: - with bom_aware_open(cache, encoding="utf-8", mode="w") as f: + with bom_aware_open(cache, encoding="utf-8", mode='wt') as f: yaml.safe_dump(result, f) - except: - logger.info("Fetched plugin blacklist but couldn't write it to its cache file.") - except: - logger.info("Unable to fetch plugin blacklist from {}, proceeding without it.".format(url)) + except Exception as e: + logger.info("Fetched plugin blacklist but couldn't write it to its cache file: %s", e) + except Exception as e: + logger.info("Unable to fetch plugin blacklist from {}, proceeding without it: {}".format(url, e)) return result try: @@ -528,7 +541,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None): logger.info("Blacklist processing done") return blacklist - except: + except Exception: logger.exception("Something went wrong while processing the plugin blacklist. Proceeding without it.") @@ -595,6 +608,9 @@ def main(): # cut off stuff from the beginning args = args[-1 * sys_args_length:] if sys_args_length else [] + from octoprint.util.fixes import patch_sarge_async_on_py2 + patch_sarge_async_on_py2() + from octoprint.cli import octo octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT") diff --git a/src/octoprint/__main__.py b/src/octoprint/__main__.py index 3dd81998d..23e03429c 100644 --- a/src/octoprint/__main__.py +++ b/src/octoprint/__main__.py @@ -1,6 +1,10 @@ -#!/usr/bin/env python2 -# coding=utf-8 -from __future__ import absolute_import, division, print_function +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +#import sys +#if sys.version_info[0] >= 3: +# raise RuntimeError("Sorry, OctoPrint does not yet support Python 3") if __name__ == "__main__": import octoprint diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py index a08e11a97..5895ced6a 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag @@ -9,13 +11,14 @@ # versioneer-0.15+dev (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" -from __future__ import absolute_import, division, print_function import errno +import io import os import re import subprocess import sys +import logging def get_keywords(): @@ -41,7 +44,7 @@ def get_config(): # _version.py cfg = VersioneerConfig() cfg.VCS = "git" - cfg.style = "pep440-post" + cfg.style = "pep440-tag" cfg.tag_prefix = "" cfg.parentdir_prefix = "" cfg.versionfile_source = "src/octoprint/_version.py" @@ -130,7 +133,7 @@ def git_get_keywords(versionfile_abs): # _version.py. keywords = {} try: - f = open(versionfile_abs, "r") + f = io.open(versionfile_abs, "rt", encoding="utf-8") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) @@ -156,11 +159,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = set(r.strip() for r in refnames.strip("()").split(",")) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = set(r[len(TAG):] for r in refs if r.startswith(TAG)) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -169,7 +172,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = set(r for r in refs if re.search(r'\d', r)) if verbose: print("discarding '%s', no digits" % ",".join(refs-tags)) @@ -254,7 +257,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): abbrev_ref_out = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) - if abbrev_ref_out is not None: + if abbrev_ref_out is not None and abbrev_ref_out != "HEAD": pieces["branch"] = abbrev_ref_out.strip() # now we have TAG-NUM-gHEX or HEX @@ -305,11 +308,12 @@ def git_parse_lookup_file(path): if not os.path.exists(path): return [] + import re lookup = [] - with open(path, "r") as f: + with io.open(path, "rt", encoding="utf-8") as f: for line in f: if '#' in line: - line = line[:line.rindex("#")] + line = line[:line.index("#")] line = line.strip() if not line: continue @@ -336,7 +340,8 @@ def git_parse_lookup_file(path): continue lookup.append(entry) - except: + except Exception: + logging.getLogger(__name__).exception("Versioneer problem") break return lookup @@ -354,6 +359,9 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command): raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed") current_branch = stdout.strip() + if current_branch == "HEAD": + raise NotThisMethod("not on a branch") + for matcher, render, tag, ref_commit in lookup: if matcher.match(current_branch): if tag is None or ref_commit is None: @@ -441,6 +449,31 @@ def render_pep440(pieces): return rendered +def render_pep440_tag(pieces): + """TAG[[.postDISTANCE].dev0+gHEX] -- Just the tag if not dirty, else more info + + Useful for projects that want commit based tracking on some branches + but have the master branch only report tags, to allow for commits that + do not modify actual code (e.g. to .github/* or docs). + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + return rendered + + def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. @@ -591,6 +624,8 @@ def render(pieces, style): rendered = render_pep440_old(pieces) elif style == "pep440-dev": rendered = render_pep440_dev(pieces) + elif style == "pep440-tag": + rendered = render_pep440_tag(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": diff --git a/src/octoprint/access/__init__.py b/src/octoprint/access/__init__.py index eed3bf88b..599123f9b 100644 --- a/src/octoprint/access/__init__.py +++ b/src/octoprint/access/__init__.py @@ -1,6 +1,7 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals ADMIN_GROUP = "admins" USER_GROUP = "users" GUEST_GROUP = "guests" +READONLY_GROUP = "readonly" diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py index 8b2f02c66..9694b7d28 100644 --- a/src/octoprint/access/groups.py +++ b/src/octoprint/access/groups.py @@ -1,10 +1,11 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Marc Hannappel " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" +import io import logging import os from functools import partial @@ -15,7 +16,7 @@ from past.builtins import basestring from octoprint.settings import settings from octoprint.util import atomic_write -from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP +from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP, READONLY_GROUP from octoprint.access.permissions import Permissions, OctoPrintPermission from flask_principal import Need, Permission @@ -90,6 +91,7 @@ class GroupManager(object): "Admins", "Administrators", self.default_permissions_for_group(ADMIN_GROUP), + [], changeable=False, removable=False, save=False) @@ -97,6 +99,7 @@ class GroupManager(object): "Users", "All logged in users", self.default_permissions_for_group(USER_GROUP), + [], default=True, removable=False, toggleable=False, @@ -105,8 +108,17 @@ class GroupManager(object): "Guests", "Anyone who is not currently logged in", self.default_permissions_for_group(GUEST_GROUP), + [], removable=False, toggleable=False, + save=False), + self.add_group(READONLY_GROUP, + "Read-only Access", + "Group to gain read-only access", + self.default_permissions_for_group(READONLY_GROUP), + [], + changeable=False, + removable=False, save=False) def register_listener(self, listener): @@ -115,10 +127,11 @@ class GroupManager(object): def unregister_listener(self, listener): self._group_change_listeners.remove(listener) - def add_group(self, key, name, description, permissions, default=False, removable=True, changeable=True, toggleable=True, save=True, notify=True): + def add_group(self, key, name, description, permissions, subgroups, + default=False, removable=True, changeable=True, toggleable=True, save=True, notify=True): pass - def update_group(self, key, description=None, permissions=None, default=None, save=True, notify=True): + def update_group(self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True): pass def remove_group(self, key, save=True, notify=True): @@ -128,12 +141,19 @@ class GroupManager(object): return None def _to_permissions(self, *permissions): - return filter(lambda x: x is not None, - [Permissions.find(permission) for permission in permissions]) + return list(filter(lambda x: x is not None, + [Permissions.find(permission) for permission in permissions])) def _from_permissions(self, *permissions): return [permission.key for permission in permissions] + def _from_groups(self, *groups): + return [group.key for group in groups] + + def _to_groups(self, *groups): + return filter(lambda x: x is not None, + [self._to_group(g) for g in groups]) + def _to_group(self, group): # noinspection PyCompatibility if isinstance(group, Group): @@ -150,7 +170,7 @@ class GroupManager(object): for listener in self._group_change_listeners: try: getattr(listener, method)(group, *args, **kwargs) - except: + except Exception: self._logger.exception("Error notifying listener {!r} via {}".format(listener, method)) class GroupChangeListener(object): @@ -164,6 +184,9 @@ class GroupChangeListener(object): def on_group_permissions_changed(self, group, added=None, removed=None): pass + def on_group_subgroups_changed(self, group, added=None, removed=None): + pass + class FilebasedGroupManager(GroupManager): def __init__(self, path=None): @@ -183,45 +206,53 @@ class FilebasedGroupManager(GroupManager): def _load(self): if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile): try: - with open(self._groupfile, "r") as f: + with io.open(self._groupfile, 'rt', encoding='utf-8') as f: data = yaml.safe_load(f) - if not "groups" in data: - groups = data - data = dict(groups=groups) + if not "groups" in data: + groups = data + data = dict(groups=groups) - groups = data.get("groups", dict()) - tracked_permissions = data.get("tracked", list()) + groups = data.get("groups", dict()) + tracked_permissions = data.get("tracked", list()) - for key, attributes in groups.items(): - if key in self._groups: - # group is already there (from the defaults most likely) - if not self._groups[key].is_changeable(): - # group may not be changed -> bail - continue + for key, attributes in groups.items(): + if key in self._groups: + # group is already there (from the defaults most likely) + if not self._groups[key].is_changeable(): + # group may not be changed -> bail + continue - removable = self._groups[key].is_removable() - changeable = self._groups[key].is_changeable() - toggleable = self._groups[key].is_toggleable() - else: - removable = True - changeable = True - toggleable = True + removable = self._groups[key].is_removable() + changeable = self._groups[key].is_changeable() + toggleable = self._groups[key].is_toggleable() + else: + removable = True + changeable = True + toggleable = True - permissions = self._to_permissions(*attributes.get("permissions", [])) - default_permissions = self.default_permissions_for_group(key) - for permission in default_permissions: - if not permission.key in tracked_permissions and not permission in permissions: - permissions.append(permission) + permissions = self._to_permissions(*attributes.get("permissions", [])) + default_permissions = self.default_permissions_for_group(key) + for permission in default_permissions: + if not permission.key in tracked_permissions and not permission in permissions: + permissions.append(permission) - self._groups[key] = Group(key, attributes.get("name", ""), - description=attributes.get("description", ""), - permissions=permissions, - default=attributes.get("default", False), - removable=removable, - changeable=changeable, - toggleable=toggleable) - except: + subgroups = attributes.get("subgroups", []) + + group = Group(key, attributes.get("name", ""), + description=attributes.get("description", ""), + permissions=permissions, + subgroups=subgroups, + default=attributes.get("default", False), + removable=removable, + changeable=changeable, + toggleable=toggleable) + self._groups[key] = group + + for group in self._groups.values(): + group._subgroups = self._to_groups(*group._subgroups) + + except Exception: self._logger.exception("Error while loading groups from file {}".format(self._groupfile)) def _save(self, force=False): @@ -235,13 +266,14 @@ class FilebasedGroupManager(GroupManager): name=group._name, description=group._description, permissions=self._from_permissions(*group._permissions), + subgroups=self._from_groups(*group._subgroups), default=group._default ) data = dict(groups=groups, tracked=[x.key for x in Permissions.all()]) - with atomic_write(self._groupfile, "wb", permissions=0o600, max_permissions=0o666) as f: + with atomic_write(self._groupfile, mode='wt', permissions=0o600, max_permissions=0o666) as f: import yaml yaml.safe_dump(data, f, default_flow_style=False, indent=4, allow_unicode=True) self._dirty = False @@ -260,9 +292,9 @@ class FilebasedGroupManager(GroupManager): return None return self._groups.get(key) - def add_group(self, key, name, description, permissions, default=False, removable=True, + def add_group(self, key, name, description, permissions, subgroups, default=False, removable=True, changeable=True, toggleable=True, overwrite=False, notify=True, save=True): - if key in self._groups.keys() and not overwrite: + if key in self._groups and not overwrite: raise GroupAlreadyExists(key) if not permissions: @@ -271,9 +303,13 @@ class FilebasedGroupManager(GroupManager): permissions = self._to_permissions(*permissions) assert(all(map(lambda p: isinstance(p, OctoPrintPermission), permissions))) + subgroups = self._to_groups(*subgroups) + assert(all(map(lambda g: isinstance(g, Group), subgroups))) + group = Group(key, name, description=description, permissions=permissions, + subgroups=subgroups, default=default, changeable=changeable, removable=removable, @@ -305,7 +341,7 @@ class FilebasedGroupManager(GroupManager): if notify: self._notify_listeners("removed", group) - def update_group(self, key, description=None, permissions=None, default=None, save=True, notify=True): + def update_group(self, key, description=None, permissions=None, subgroups=None, default=None, save=True, notify=True): group = self._to_group(key) if group is None: raise UnknownGroup(key) @@ -334,6 +370,21 @@ class FilebasedGroupManager(GroupManager): notifications.append((("permissions_changed", group), dict(added=added_permissions, removed=removed_permissions))) + if subgroups is not None: + subgroups = self._to_groups(*subgroups) + assert(all(map(lambda g: isinstance(g, Group), subgroups))) + + removed_subgroups = list(set(group._subgroups) - set(subgroups)) + added_subgroups = list(set(subgroups) - set(group._subgroups)) + + if removed_subgroups: + self._dirty = group.remove_subgroups_from_group(removed_subgroups) + if added_subgroups: + self._dirty = group.add_subgroups_to_group(added_subgroups) + + notifications.append((("subgroups_changed", group), + dict(added=added_subgroups, removed=removed_subgroups))) + if default is not None: group.change_default(default) self._dirty = True @@ -368,11 +419,12 @@ class GroupCantBeChanged(Exception): class Group(object): - def __init__(self, key, name, description="", permissions=None, default=False, removable=True, changeable=True, toggleable=True): + def __init__(self, key, name, description="", permissions=None, subgroups=None, default=False, removable=True, changeable=True, toggleable=True): self._key = key self._name = name self._description = description self._permissions = permissions + self._subgroups = subgroups self._default = default self._removable = removable self._changeable = changeable @@ -385,6 +437,7 @@ class Group(object): name=self.get_name(), description=self._description, permissions=list(map(lambda p: p.key, self._permissions)), + subgroups=list(map(lambda g: g.key, self._subgroups)), needs=OctoPrintPermission.convert_needs_to_dict(self.needs), default=self._default, removable=self._removable, @@ -452,6 +505,45 @@ class Group(object): return dirty + def add_subgroups_to_group(self, subgroups): + """Adds a list of subgroups to a group""" + if not self.is_changeable(): + raise GroupCantBeChanged(self.key) + + # Make sure the subgroups variable is of type list + if not isinstance(subgroups, list): + subgroups = [subgroups] + + assert(all(map(lambda g: isinstance(g, Group), subgroups))) + + dirty = False + for group in subgroups: + if group.is_toggleable() and group not in self._subgroups: + self._subgroups.append(group) + dirty = True + + return dirty + + def remove_subgroups_from_group(self, subgroups): + """Removes a list of subgroups from a group""" + """Adds a list of subgroups to a group""" + if not self.is_changeable(): + raise GroupCantBeChanged(self.key) + + # Make sure the subgroups variable is of type list + if not isinstance(subgroups, list): + subgroups = [subgroups] + + assert (all(map(lambda g: isinstance(g, Group), subgroups))) + + dirty = False + for group in subgroups: + if group.is_toggleable() and group in self._subgroups: + self._subgroups.remove(group) + dirty = True + + return dirty + def change_default(self, default): """Changes the default flag of a Group""" if not self.is_changeable(): @@ -468,7 +560,11 @@ class Group(object): if Permissions.ADMIN in self._permissions: return Permissions.all() - return filter(lambda p: p is not None, self._permissions) + return list(filter(lambda p: p is not None, self._permissions)) + + @property + def subgroups(self): + return filter(lambda g: g is not None, self._subgroups) @property def needs(self): @@ -476,6 +572,8 @@ class Group(object): needs.add(GroupNeed(self.key)) for p in self.permissions: needs = needs.union(p.needs) + for g in self.subgroups: + needs = needs.union(g.needs) return needs diff --git a/src/octoprint/access/permissions.py b/src/octoprint/access/permissions.py index c39af8c5e..035814df0 100644 --- a/src/octoprint/access/permissions.py +++ b/src/octoprint/access/permissions.py @@ -1,11 +1,11 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Marc Hannappel " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" - +from future.utils import with_metaclass from flask import g, abort from flask_babel import gettext from flask_principal import Permission, PermissionDenied, RoleNeed, Need @@ -16,7 +16,7 @@ from collections import OrderedDict, defaultdict # noinspection PyCompatibility from past.builtins import basestring -from octoprint.access import ADMIN_GROUP, USER_GROUP, GUEST_GROUP +from octoprint.access import ADMIN_GROUP, USER_GROUP, READONLY_GROUP class OctoPrintPermission(Permission): @@ -44,7 +44,7 @@ class OctoPrintPermission(Permission): def __init__(self, name, description, *needs, **kwargs): self._name = name self._description = description - self._dangerous = kwargs.pop("dangerous", False) == True + self._dangerous = kwargs.pop("dangerous", False) self._default_groups = kwargs.pop("default_groups", []) self._key = None @@ -102,7 +102,7 @@ class OctoPrintPermission(Permission): return '{}({!r}, {!r}, {})'.format(self.__class__.__name__, self.get_name(), self.get_description(), - ', '.join(list(map(repr, self.needs)))) + ', '.join(map(repr, self.needs))) def __hash__(self): return self.get_name().__hash__() @@ -217,10 +217,10 @@ class PermissionsMetaClass(type): return permission def all(cls): - return cls.permissions.values() + return list(cls.permissions.values()) def filter(cls, cb): - return filter(cb, cls.all()) + return list(filter(cb, cls.all())) def find(cls, p, filter=None): key = None @@ -249,8 +249,7 @@ class PermissionsMetaClass(type): return None -class Permissions(object): - __metaclass__ = PermissionsMetaClass +class Permissions(with_metaclass(PermissionsMetaClass)): # Special permission ADMIN = OctoPrintPermission("Admin", @@ -263,7 +262,7 @@ class Permissions(object): gettext("Allows to gather status information, e.g. job progress, " "printer state, temperatures, ..."), RoleNeed("status"), - default_groups=[USER_GROUP, GUEST_GROUP]) + default_groups=[USER_GROUP, READONLY_GROUP]) CONNECTION = OctoPrintPermission("Connection", gettext("Allows to connect to and disconnect from a printer"), @@ -273,7 +272,7 @@ class Permissions(object): WEBCAM = OctoPrintPermission("Webcam", gettext("Allows to watch the webcam stream"), RoleNeed("webcam"), - default_groups=[USER_GROUP, GUEST_GROUP]) + default_groups=[USER_GROUP, READONLY_GROUP]) SYSTEM = OctoPrintPermission("System", gettext("Allows to run system commands, e.g. restart OctoPrint, " @@ -285,7 +284,7 @@ class Permissions(object): gettext("Allows to retrieve a list of all uploaded files, including" "their metadata (e.g. date, file size, analysis results, ...)"), RoleNeed("files_list"), - default_groups=[USER_GROUP, GUEST_GROUP]) + default_groups=[USER_GROUP, READONLY_GROUP]) FILES_UPLOAD = OctoPrintPermission("File Upload", gettext("Allows users to upload new files"), RoleNeed("files_upload"), @@ -294,7 +293,7 @@ class Permissions(object): gettext("Allows users to download files. The GCODE viewer is " "affected by this as well."), RoleNeed("files_download"), FILES_LIST, - default_groups=[USER_GROUP, GUEST_GROUP]) + default_groups=[USER_GROUP, READONLY_GROUP]) FILES_DELETE = OctoPrintPermission("File Delete", gettext("Allows users to delete files"), RoleNeed("files_delete"), FILES_LIST, @@ -314,13 +313,13 @@ class Permissions(object): gettext("Allows access to the GCODE viewer. Includes the \"File Download\"" "permission."), RoleNeed("gcodeviewer"), FILES_DOWNLOAD, - default_groups=[USER_GROUP, GUEST_GROUP]) + default_groups=[USER_GROUP, READONLY_GROUP]) MONITOR_TERMINAL = OctoPrintPermission("Terminal", gettext("Allows to watch the terminal tab but not to send commands " "to the printer from it"), RoleNeed("monitor_terminal"), - default_groups=[USER_GROUP, GUEST_GROUP]) + default_groups=[USER_GROUP, READONLY_GROUP]) CONTROL = OctoPrintPermission("Control", gettext("Allows to control of the printer by using the temperature controls," @@ -336,11 +335,11 @@ class Permissions(object): TIMELAPSE_LIST = OctoPrintPermission("Timelapse List", gettext("Allows to list timelapse videos"), RoleNeed("timelapse_list"), - default_groups=[USER_GROUP, GUEST_GROUP]) + default_groups=[USER_GROUP, READONLY_GROUP]) TIMELAPSE_DOWNLOAD = OctoPrintPermission("Timelapse Download", gettext("Allows to download timelapse videos"), RoleNeed("timelapse_download"), - default_groups=[USER_GROUP, GUEST_GROUP]) + default_groups=[USER_GROUP, READONLY_GROUP]) TIMELAPSE_DELETE = OctoPrintPermission("Timelapse Delete", gettext("Allows to delete timelapse videos and unrendered timelapses"), RoleNeed("timelapse_delete"), diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index 54ee6ec00..077a03539 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from flask_login import UserMixin, AnonymousUserMixin from werkzeug.local import LocalProxy import hashlib +import io import os import yaml import uuid @@ -18,14 +19,18 @@ import logging # noinspection PyCompatibility from builtins import range, bytes -from octoprint.settings import settings -from octoprint.util import atomic_write, to_str, deprecated +from octoprint.settings import settings as s + +from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time +from octoprint.util import get_fully_qualified_classname as fqcn + from octoprint.access.permissions import Permissions, OctoPrintPermission from octoprint.access.groups import GroupChangeListener, Group +from past.builtins import basestring class UserManager(GroupChangeListener, object): - def __init__(self, group_manager): + def __init__(self, group_manager, settings=None): self._group_manager = group_manager self._group_manager.register_listener(self) @@ -34,6 +39,10 @@ class UserManager(GroupChangeListener, object): self._sessionids_by_userid = dict() self._enabled = True + if settings is None: + settings = s() + self._settings = settings + self._login_status_listeners = [] def register_login_status_listener(self, listener): @@ -87,8 +96,11 @@ class UserManager(GroupChangeListener, object): self._sessionids_by_userid[userid].add(user.session) for listener in self._login_status_listeners: - try: listener.on_user_logged_in(user) - except: self._logger.exception("Error in on_user_logged_in on {!r}".format(listener)) + try: + listener.on_user_logged_in(user) + except Exception: + self._logger.exception("Error in on_user_logged_in on {!r}".format(listener), + extra=dict(callback=fqcn(listener))) self._logger.debug("Logged in user: %r" % user) @@ -117,45 +129,52 @@ class UserManager(GroupChangeListener, object): del self._session_users_by_session[sessionid] for listener in self._login_status_listeners: - try: listener.on_user_logged_out(user) - except: self._logger.exception("Error in on_user_logged_out on {!r}".format(listener)) + try: + listener.on_user_logged_out(user) + except Exception: + self._logger.exception("Error in on_user_logged_out on {!r}".format(listener), + extra=dict(callback=fqcn(listener))) self._logger.debug("Logged out user: %r" % user) def _cleanup_sessions(self): - import time - for session, user in self._session_users_by_session.items(): + for session, user in list(self._session_users_by_session.items()): if not isinstance(user, SessionUser): continue - if user.created + (24 * 60 * 60) < time.time(): + if user.created + (24 * 60 * 60) < monotonic_time(): self.logout_user(user) @staticmethod - def create_password_hash(password, salt=None): + def create_password_hash(password, salt=None, settings=None): if not salt: - salt = settings().get(["accessControl", "salt"]) + if settings is None: + settings = s() + salt = settings.get(["accessControl", "salt"]) if salt is None: import string from random import choice chars = string.ascii_lowercase + string.ascii_uppercase + string.digits salt = "".join(choice(chars) for _ in range(32)) - settings().set(["accessControl", "salt"], salt) - settings().save() + settings.set(["accessControl", "salt"], salt) + settings.save() - return hashlib.sha512(to_str(password, encoding="utf-8", errors="replace") + to_str(salt)).hexdigest() + return hashlib.sha512(to_bytes(password, encoding="utf-8", errors="replace") + to_bytes(salt)).hexdigest() def check_password(self, username, password): user = self.find_user(username) if not user: return False - hash = UserManager.create_password_hash(password) + hash = UserManager.create_password_hash(password, + settings=self._settings) if user.check_password(hash): # new hash matches, correct password return True else: # new hash doesn't match, but maybe the old one does, so check that! - oldHash = UserManager.create_password_hash(password, salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW") + oldHash = UserManager.create_password_hash(password, + salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW", + settings=self._settings) if user.check_password(oldHash): # old hash matches, we migrate the stored password hash to the new one and return True since it's the correct password self.change_user_password(username, password) @@ -255,8 +274,20 @@ class UserManager(GroupChangeListener, object): try: for user in users: listener.on_user_modified(user) - except: - self._logger.exception("Error in on_user_modified on {!r}".format(listener)) + except Exception: + self._logger.exception("Error in on_user_modified on {!r}".format(listener), + extra=dict(callback=fqcn(listener))) + + def on_group_subgroups_changed(self, group, added=None, removed=None): + users = self.find_sessions_for(lambda u: group in u.groups) + for listener in self._login_status_listeners: + # noinspection PyBroadException + try: + for user in users: + listener.on_user_modified(user) + except Exception: + self._logger.exception("Error in on_user_modified on {!r}".format(listener), + extra=dict(callback=fqcn(listener))) def _trigger_on_user_modified(self, user): if isinstance(user, basestring): @@ -284,15 +315,17 @@ class UserManager(GroupChangeListener, object): try: for user in users: listener.on_user_modified(user) - except: - self._logger.exception("Error in on_user_modified on {!r}".format(listener)) + except Exception: + self._logger.exception("Error in on_user_modified on {!r}".format(listener), + extra=dict(callback=fqcn(listener))) def _trigger_on_user_removed(self, username): for listener in self._login_status_listeners: try: listener.on_user_removed(username) - except: - self._logger.exception("Error in on_user_removed on {!r}".format(listener)) + except Exception: + self._logger.exception("Error in on_user_removed on {!r}".format(listener), + extra=dict(callback=fqcn(listener))) #~~ Deprecated methods follow @@ -413,13 +446,13 @@ class LoginStatusListener(object): ##~~ FilebasedUserManager, takes available users from users.yaml file class FilebasedUserManager(UserManager): - def __init__(self, group_manager, path=None): - UserManager.__init__(self, group_manager) + def __init__(self, group_manager, path=None, settings=None): + UserManager.__init__(self, group_manager, settings=settings) if path is None: - path = settings().get(["accessControl", "userfile"]) + path = self._settings.get(["accessControl", "userfile"]) if path is None: - path = os.path.join(settings().getBaseFolder("base"), "users.yaml") + path = os.path.join(s().getBaseFolder("base"), "users.yaml") self._userfile = path @@ -432,10 +465,9 @@ class FilebasedUserManager(UserManager): def _load(self): if os.path.exists(self._userfile) and os.path.isfile(self._userfile): self._customized = True - with open(self._userfile, "r") as f: + with io.open(self._userfile, 'rt', encoding='utf-8') as f: data = yaml.safe_load(f) - for name in data.keys(): - attributes = data[name] + for name, attributes in data.items(): permissions = [] if "permissions" in attributes: permissions = attributes["permissions"] @@ -480,9 +512,7 @@ class FilebasedUserManager(UserManager): return data = {} - for name in self._users.keys(): - user = self._users[name] - + for name, user in self._users.items(): if not user or not isinstance(user, User): continue @@ -498,7 +528,7 @@ class FilebasedUserManager(UserManager): "roles": user._roles } - with atomic_write(self._userfile, "wb", permissions=0o600, max_permissions=0o666) as f: + with atomic_write(self._userfile, mode='wt', permissions=0o600, max_permissions=0o666) as f: yaml.safe_dump(data, f, default_flow_style=False, indent=4, allow_unicode=True) self._dirty = False self._load() @@ -511,7 +541,7 @@ class FilebasedUserManager(UserManager): return [self._group_manager.user_group] def _refresh_groups(self, user): - user._groups = self._to_groups(*list(map(lambda g: g.key, user.groups))) + user._groups = self._to_groups(*map(lambda g: g.key, user.groups)) def add_user(self, username, password, active=False, permissions=None, groups=None, apikey=None, overwrite=False): if not permissions: @@ -522,15 +552,21 @@ class FilebasedUserManager(UserManager): groups = self._group_manager.default_groups groups = self._to_groups(*groups) - if username in self._users.keys() and not overwrite: + if username in self._users and not overwrite: raise UserAlreadyExists(username) - self._users[username] = User(username, UserManager.create_password_hash(password), active, permissions, groups, apikey=apikey) + self._users[username] = User(username, + UserManager.create_password_hash(password, + settings=self._settings), + active, + permissions, + groups, + apikey=apikey) self._dirty = True self._save() def change_user_activation(self, username, active): - if username not in self._users.keys(): + if username not in self._users: raise UnknownUser(username) if self._users[username].is_active != active: @@ -541,7 +577,7 @@ class FilebasedUserManager(UserManager): self._trigger_on_user_modified(username) def change_user_permissions(self, username, permissions): - if username not in self._users.keys(): + if username not in self._users: raise UnknownUser(username) user = self._users[username] @@ -564,7 +600,7 @@ class FilebasedUserManager(UserManager): self._trigger_on_user_modified(username) def add_permissions_to_user(self, username, permissions): - if username not in self._users.keys(): + if username not in self._users: raise UnknownUser(username) if self._users[username].add_permissions_to_user(self._to_permissions(*permissions)): @@ -573,7 +609,7 @@ class FilebasedUserManager(UserManager): self._trigger_on_user_modified(username) def remove_permissions_from_user(self, username, permissions): - if username not in self._users.keys(): + if username not in self._users: raise UnknownUser(username) if self._users[username].remove_permissions_from_user(self._to_permissions(*permissions)): @@ -583,7 +619,7 @@ class FilebasedUserManager(UserManager): def remove_permissions_from_users(self, permissions): modified = [] - for user in self._users.keys(): + for user in self._users: dirty = user.remove_permissions_from_user(self._to_permissions(*permissions)) if dirty: self._dirty = True @@ -595,7 +631,7 @@ class FilebasedUserManager(UserManager): self._trigger_on_user_modified(username) def change_user_groups(self, username, groups): - if username not in self._users.keys(): + if username not in self._users: raise UnknownUser(username) user = self._users[username] @@ -615,7 +651,7 @@ class FilebasedUserManager(UserManager): self._trigger_on_user_modified(username) def add_groups_to_user(self, username, groups, save=True, notify=True): - if username not in self._users.keys(): + if username not in self._users: raise UnknownUser(username) if self._users[username].add_groups_to_user(self._to_groups(*groups)): @@ -628,7 +664,7 @@ class FilebasedUserManager(UserManager): self._trigger_on_user_modified(username) def remove_groups_from_user(self, username, groups, save=True, notify=True): - if username not in self._users.keys(): + if username not in self._users: raise UnknownUser(username) if self._users[username].remove_groups_from_user(self._to_groups(*groups)): @@ -642,8 +678,8 @@ class FilebasedUserManager(UserManager): def remove_groups_from_users(self, groups): modified = [] - for username in self._users.keys(): - dirty = self._users[username].remove_groups_from_user(self._to_groups(*groups)) + for username, user in self._users.items(): + dirty = user.remove_groups_from_user(self._to_groups(*groups)) if dirty: self._dirty = True modified.append(username) @@ -655,10 +691,11 @@ class FilebasedUserManager(UserManager): self._trigger_on_user_modified(username) def change_user_password(self, username, password): - if not username in self._users.keys(): + if not username in self._users: raise UnknownUser(username) - passwordHash = UserManager.create_password_hash(password) + passwordHash = UserManager.create_password_hash(password, + settings=self._settings) user = self._users[username] if user._passwordHash != passwordHash: user._passwordHash = passwordHash @@ -666,7 +703,7 @@ class FilebasedUserManager(UserManager): self._save() def change_user_setting(self, username, key, value): - if not username in self._users.keys(): + if not username in self._users: raise UnknownUser(username) user = self._users[username] @@ -688,21 +725,21 @@ class FilebasedUserManager(UserManager): self._save() def get_all_user_settings(self, username): - if not username in self._users.keys(): + if not username in self._users: raise UnknownUser(username) user = self._users[username] return user.get_all_settings() def get_user_setting(self, username, key): - if not username in self._users.keys(): + if not username in self._users: raise UnknownUser(username) user = self._users[username] return user.get_setting(key) def generate_api_key(self, username): - if not username in self._users.keys(): + if not username in self._users: raise UnknownUser(username) user = self._users[username] @@ -712,7 +749,7 @@ class FilebasedUserManager(UserManager): return user._apikey def delete_api_key(self, username): - if not username in self._users.keys(): + if not username in self._users: raise UnknownUser(username) user = self._users[username] @@ -723,7 +760,7 @@ class FilebasedUserManager(UserManager): def remove_user(self, username): UserManager.remove_user(self, username) - if not username in self._users.keys(): + if not username in self._users: raise UnknownUser(username) del self._users[username] @@ -737,7 +774,7 @@ class FilebasedUserManager(UserManager): return user if userid is not None: - if userid not in self._users.keys(): + if userid not in self._users: return None return self._users[userid] @@ -765,21 +802,30 @@ class FilebasedUserManager(UserManager): # call parent UserManager.on_group_permissions_changed(self, group, added=added, removed=removed) + def on_group_subgroups_changed(self, group, added=None, removed=None): + # refresh our group references + for user in self.get_all_users(): + if group in user.groups: + self._refresh_groups(user) + + # call parent + UserManager.on_group_subgroups_changed(self, group, added=added, removed=removed) + #~~ Helpers def _to_groups(self, *groups): return list(set(filter(lambda x: x is not None, - [self._group_manager._to_group(group) for group in groups]))) + (self._group_manager._to_group(group) for group in groups)))) def _to_permissions(self, *permissions): return list(set(filter(lambda x: x is not None, - [Permissions.find(permission) for permission in permissions]))) + (Permissions.find(permission) for permission in permissions)))) def _from_groups(self, *groups): - return list(set([group.key for group in groups])) + return list(set(group.key for group in groups)) def _from_permissions(self, *permissions): - return list(set([permission.key for permission in permissions])) + return list(set(permission.key for permission in permissions)) # ~~ Deprecated methods follow @@ -791,6 +837,39 @@ class FilebasedUserManager(UserManager): deleteApiKey = deprecated("deleteApiKey has been renamed to delete_api_key", includedoc="Replaced by :func:`delete_api_key`", since="1.4.0")(delete_api_key) + addUser = deprecated("addUser has been renamed to add_user", + includedoc="Replaced by :func:`add_user`", + since="1.4.0")(add_user) + changeUserActivation = deprecated("changeUserActivation has been renamed to change_user_activation", + includedoc="Replaced by :func:`change_user_activation`", + since="1.4.0")(change_user_activation) + changeUserPassword = deprecated("changeUserPassword has been renamed to change_user_password", + includedoc="Replaced by :func:`change_user_password`", + since="1.4.0")(change_user_password) + getUserSetting = deprecated("getUserSetting has been renamed to get_user_setting", + includedoc="Replaced by :func:`get_user_setting`", + since="1.4.0")(get_user_setting) + getAllUserSettings = deprecated("getAllUserSettings has been renamed to get_all_user_settings", + includedoc="Replaced by :func:`get_all_user_settings`", + since="1.4.0")(get_all_user_settings) + changeUserSetting = deprecated("changeUserSetting has been renamed to change_user_setting", + includedoc="Replaced by :func:`change_user_setting`", + since="1.4.0")(change_user_setting) + changeUserSettings = deprecated("changeUserSettings has been renamed to change_user_settings", + includedoc="Replaced by :func:`change_user_settings`", + since="1.4.0")(change_user_settings) + removeUser = deprecated("removeUser has been renamed to remove_user", + includedoc="Replaced by :func:`remove_user`", + since="1.4.0")(remove_user) + findUser = deprecated("findUser has been renamed to find_user", + includedoc="Replaced by :func:`find_user`", + since="1.4.0")(find_user) + getAllUsers = deprecated("getAllUsers has been renamed to get_all_users", + includedoc="Replaced by :func:`get_all_users`", + since="1.4.0")(get_all_users) + hasBeenCustomized = deprecated("hasBeenCustomized has been renamed to has_been_customized", + includedoc="Replaced by :func:`has_been_customized`", + since="1.4.0")(has_been_customized) ##~~ Exceptions @@ -1037,7 +1116,7 @@ class User(UserMixin): if Permissions.ADMIN in self._permissions: return Permissions.all() - return filter(lambda p: p is not None, self._permissions) + return list(filter(lambda p: p is not None, self._permissions)) @property def groups(self): @@ -1136,8 +1215,8 @@ class SessionUser(wrapt.ObjectProxy): wrapt.ObjectProxy.__init__(self, user) self._self_session = "".join('%02X' % z for z in bytes(uuid.uuid4().bytes)) - self._self_created = time.time() - self._self_touched = time.time() + self._self_created = monotonic_time() + self._self_touched = monotonic_time() @property def session(self): @@ -1152,7 +1231,7 @@ class SessionUser(wrapt.ObjectProxy): return self._self_touched def touch(self): - self._self_touched = time.time() + self._self_touched = monotonic_time() @deprecated("SessionUser.get_session() has been deprecated, use SessionUser.session instead", since="1.3.5") def get_session(self): diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index 34ad3f30e..4a2a8c38b 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -1,11 +1,12 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click +click.disable_unicode_literals_warning = True import octoprint import sys @@ -137,9 +138,10 @@ from .dev import dev_commands from .client import client_commands from .config import config_commands from .analysis import analysis_commands +from .user import user_commands @click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection, - sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands]) + sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands, user_commands]) @standard_options() @legacy_options @click.version_option(version=octoprint.__version__, allow_from_autoenv=False) diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index 1d6bf598e..d549e5424 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -1,10 +1,11 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import click +click.disable_unicode_literals_warning = True #~~ "octoprint util" commands @@ -34,6 +35,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle import time import yaml + from octoprint.util import monotonic_time from octoprint.util.gcodeInterpreter import gcode throttle_callback = None @@ -52,7 +54,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle if len(offsets) < maxt: offsets += [(0, 0)] * (maxt - len(offsets)) - start_time = time.time() + start_time = monotonic_time() progress_callback = None if progress: @@ -68,7 +70,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle max_extruders=maxt, g90_extruder=g90_extruder) - click.echo("DONE:{}s".format(time.time() - start_time)) + click.echo("DONE:{}s".format(monotonic_time() - start_time)) click.echo("RESULTS:") click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=4, allow_unicode=True)) diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index b40f710c3..01e316319 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -1,10 +1,13 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click +click.disable_unicode_literals_warning = True + +import io import json import octoprint_client @@ -12,6 +15,7 @@ import octoprint_client from octoprint.cli import get_ctx_obj_option, bulk_options from octoprint import init_settings, FatalStartupError +from past.builtins import unicode class JsonStringParamType(click.ParamType): name = "json" @@ -19,7 +23,7 @@ class JsonStringParamType(click.ParamType): def convert(self, value, param, ctx): try: return json.loads(value) - except: + except Exception: self.fail("%s is not a valid json string" % value, param, ctx) @@ -143,16 +147,16 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): """POSTs JSON data to the specified server path, taking the data from the specified file.""" if json_flag or yaml_flag: if json_flag: - with open(file_path, "rb") as fp: + with io.open(file_path, 'rt') as fp: data = json.load(fp) else: import yaml - with open(file_path, "rb") as fp: + with io.open(file_path, 'rt') as fp: data = yaml.safe_load(fp) r = ctx.obj.client.post_json(path, data, timeout=timeout) else: - with open(file_path, "rb") as fp: + with io.open(file_path, 'rb') as fp: data = fp.read() r = ctx.obj.client.post(path, data, timeout=timeout) diff --git a/src/octoprint/cli/config.py b/src/octoprint/cli/config.py index 0cd1734ef..c6f2a4df8 100644 --- a/src/octoprint/cli/config.py +++ b/src/octoprint/cli/config.py @@ -1,11 +1,12 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click +click.disable_unicode_literals_warning = True import logging from octoprint import init_settings, FatalStartupError diff --git a/src/octoprint/cli/dev.py b/src/octoprint/cli/dev.py index 0d8dd57a1..a9649cd16 100644 --- a/src/octoprint/cli/dev.py +++ b/src/octoprint/cli/dev.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms import click +click.disable_unicode_literals_warning = True from past.builtins import basestring @@ -116,7 +117,8 @@ class OctoPrintDevelCommands(click.MultiCommand): if key in options: val = options[key] else: - raw = raw if isinstance(raw, basestring) else str(raw) + if not isinstance(raw, basestring): + raw = str(raw) val = env.from_string(raw).render(cookiecutter=cookiecutter_dict) if not no_input: diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index facfc80cb..e628ae4c6 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -1,11 +1,12 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click +click.disable_unicode_literals_warning = True import logging from octoprint.cli import pass_octoprint_ctx, OctoPrintContext, get_ctx_obj_option @@ -88,11 +89,12 @@ class OctoPrintPluginCommands(click.MultiCommand): commands = hook(self, pass_octoprint_ctx) for command in commands: if not isinstance(command, click.Command): - self._logger.warn("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command)) + self._logger.warning("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command)) continue result[name + self.sep + command.name] = command - except: - self._logger.exception("Error while retrieving cli commands for plugin {}".format(name)) + except Exception: + self._logger.exception("Error while retrieving cli commands for plugin {}".format(name), + extra=dict(plugin=name)) return result diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index dc9ff6cbf..ab9ea5fe4 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -1,17 +1,18 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import click +click.disable_unicode_literals_warning = True import logging import sys from octoprint.cli import bulk_options, standard_options, set_ctx_obj_option, get_ctx_obj_option -def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode, +def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logging_config, verbosity, safe_mode, ignore_blacklist, octoprint_daemon=None): """Initializes the environment and starts up the server.""" @@ -26,6 +27,15 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi logger.info("Starting OctoPrint {}".format(__display_version__)) if safe_mode: logger.info("Starting in SAFE MODE. Third party plugins will be disabled!") + if safe_mode == "flag": + reason = "command line flag" + elif safe_mode == "settings": + reason = "setting in config.yaml" + elif safe_mode == "incomplete_startup": + reason = "problem during last startup" + else: + reason = "unknown" + logger.info("Reason for safe mode: {}".format(reason)) if recorder and len(recorder): logger.info(get_divider_line("-", "Logged during platform initialization:")) @@ -101,6 +111,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi environment_detector=environment_detector, host=host, port=port, + v6_only=v6_only, debug=debug, safe_mode=safe_mode, allow_root=allow_root, @@ -111,9 +122,13 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi server_options = bulk_options([ click.option("--host", type=click.STRING, callback=set_ctx_obj_option, - help="Specify the host on which to bind the server."), + help="Specify the host address on which to bind the server."), click.option("--port", type=click.INT, callback=set_ctx_obj_option, help="Specify the port on which to bind the server."), + click.option("-4", "--ipv4", "v4", is_flag=True, callback=set_ctx_obj_option, + help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present."), + click.option("-6", "--ipv6", "v6", is_flag=True, callback=set_ctx_obj_option, + help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present."), click.option("--logging", type=click.Path(), callback=set_ctx_obj_option, help="Specify the config file to use for configuring logging."), click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option, @@ -123,7 +138,7 @@ server_options = bulk_options([ click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option, help="Disable processing of the plugin blacklist.") ]) -"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, +"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``-4``, ``-6`` ``--logging``, ``--iknowwhatimdoing`` and ``--debug``.""" daemon_options = bulk_options([ @@ -153,11 +168,11 @@ def enable_safemode(ctx, **kwargs): click.echo(e.message, err=True) click.echo("There was a fatal error initializing the settings manager.", err=True) ctx.exit(-1) + else: + settings.setBoolean(["server", "startOnceInSafeMode"], True) + settings.save() - settings.setBoolean(["server", "startOnceInSafeMode"], True) - settings.save() - - click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.") + click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.") @server_commands.command(name="serve") @@ -172,6 +187,8 @@ def serve_command(ctx, **kwargs): host = get_value("host") port = get_value("port") + v4 = get_value("v4") + v6 = get_value("v6") logging = get_value("logging") allow_root = get_value("allow_root") debug = get_value("debug") @@ -179,10 +196,13 @@ 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, + if v4 and not host: + host = "0.0.0.0" + + run_server(basedir, configfile, host, port, v6, debug, allow_root, logging, verbosity, safe_mode, ignore_blacklist) @@ -209,6 +229,8 @@ if sys.platform != "win32" and sys.platform != "darwin": host = get_value("host") port = get_value("port") + v4 = get_value("v4") + v6 = get_value("v6") logging = get_value("logging") allow_root = get_value("allow_root") debug = get_value("debug") @@ -217,9 +239,12 @@ 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 v4 and not host: + host = "0.0.0.0" + if pid is None: click.echo("No path to a pidfile set", file=sys.stderr) @@ -227,14 +252,15 @@ if sys.platform != "win32" and sys.platform != "darwin": from octoprint.daemon import Daemon class OctoPrintDaemon(Daemon): - def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, - safe_mode, ignore_blacklist): + def __init__(self, pidfile, basedir, configfile, host, port, v6_only, debug, allow_root, logging_config, + verbosity, safe_mode, ignore_blacklist): Daemon.__init__(self, pidfile) self._basedir = basedir self._configfile = configfile self._host = host self._port = port + self._v6_only = v6_only self._debug = debug self._allow_root = allow_root self._logging_config = logging_config @@ -243,12 +269,12 @@ if sys.platform != "win32" and sys.platform != "darwin": self._ignore_blacklist = ignore_blacklist def run(self): - run_server(self._basedir, self._configfile, self._host, self._port, self._debug, + run_server(self._basedir, self._configfile, self._host, self._port, self._v6_only, self._debug, self._allow_root, self._logging_config, self._verbosity, self._safe_mode, self._ignore_blacklist, octoprint_daemon=self) - octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity, - safe_mode, ignore_blacklist) + octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, v6, debug, allow_root, logging, + verbosity, safe_mode, ignore_blacklist) if command == "start": octoprint_daemon.start() diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py new file mode 100644 index 000000000..488612a43 --- /dev/null +++ b/src/octoprint/cli/user.py @@ -0,0 +1,184 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import click +import logging + +from octoprint import init_settings +from octoprint.cli import get_ctx_obj_option +from octoprint.access.groups import FilebasedGroupManager +from octoprint.access.users import FilebasedUserManager, UnknownUser, UserAlreadyExists +from octoprint.util import get_class, sv + +click.disable_unicode_literals_warning = True + +#~~ "octoprint user" commands + + +@click.group() +def user_commands(): + pass + + +@user_commands.group(name="user") +@click.pass_context +def user(ctx): + """ + User management. + + Note that this currently only supports managing user accounts stored in the configured user manager, not any + user managers added through plugins and the "octoprint.users.factory" hook. + """ + try: + logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN) + settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None)) + + group_manager_name = settings.get(["accessControl", "groupManager"]) + try: + clazz = get_class(group_manager_name) + group_manager = clazz() + except AttributeError: + click.echo("Could not instantiate group manager {}, " + "falling back to FilebasedGroupManager!".format(group_manager_name), err=True) + group_manager = FilebasedGroupManager() + + ctx.obj.group_manager = group_manager + + name = settings.get(["accessControl", "userManager"]) + try: + clazz = get_class(name) + user_manager = clazz(group_manager=group_manager, settings=settings) + except Exception: + click.echo("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name), err=True) + user_manager = FilebasedUserManager(group_manager, settings=settings) + finally: + user_manager.enabled = settings.getBoolean(["accessControl", "enabled"]) + + ctx.obj.user_manager = user_manager + + except Exception: + click.echo("Could not instantiate user manager", err=True) + return + + +@user.command(name="list") +@click.pass_context +def list_users_command(ctx): + """Lists user information""" + users = ctx.obj.user_manager.get_all_users() + _print_list(users) + + +@user.command(name="add") +@click.argument("username", type=click.STRING, required=True) +@click.password_option("--password", "password", help="Password for the user") +@click.option("-g", "--group", "groups", multiple=True, + help="Groups to set on the user") +@click.option("-p", "--permission", "permissions", multiple=True, + help="Individual permissions to set on the user") +@click.option("--admin", "is_admin", type=click.BOOL, is_flag=True, default=False, + help="Adds user to admin group") +@click.pass_context +def add_user_command(ctx, username, password, groups, permissions, is_admin): + """Add a new user.""" + if not groups: + groups = [] + + if is_admin: + groups.append(ctx.obj.group_manager.admin_group) + + try: + ctx.obj.user_manager.add_user(username, + password, + groups=groups, + permissions=permissions, + active=True) + + user = ctx.obj.user_manager.find_user(username) + if user: + click.echo("User created:") + click.echo("\t{}".format(_user_to_line(user.as_dict()))) + except UserAlreadyExists: + click.echo("A user with the name {} does already exist!".format(username), err=True) + + +@user.command(name="remove") +@click.argument("username", type=click.STRING) +@click.pass_context +def remove_user_command(ctx, username): + """Remove an existing user.""" + confirm = click.prompt("This is will irreversibly destroy the user account! Enter 'yes' to confirm", + type=click.STRING) + + if confirm.lower() == "yes": + ctx.obj.user_manager.remove_user(username) + click.echo("User {} removed.".format(username)) + else: + click.echo("User {} not removed.".format(username)) + + +@user.command(name="password") +@click.argument("username", type=click.STRING) +@click.password_option("--password", "password", help="New password for user") +@click.pass_context +def change_password_command(ctx, username, password): + """Change an existing user's password.""" + try: + ctx.obj.user_manager.change_user_password(username, password) + click.echo("Password changed for user {}.".format(username)) + except UnknownUser: + click.echo("User {} does not exist!".format(username), err=True) + + +@user.command(name="activate") +@click.argument("username", type=click.STRING) +@click.pass_context +def activate_command(ctx, username): + """Activate a user account.""" + try: + ctx.obj.user_manager.change_user_activation(username, True) + click.echo("User {} activated.".format(username)) + + user = ctx.obj.user_manager.find_user(username) + if user: + click.echo("User created:") + click.echo("\t{}".format(_user_to_line(user.asDict()))) + except UnknownUser: + click.echo("User {} does not exist!".format(username), err=True) + + +@user.command(name="deactivate") +@click.argument("username", type=click.STRING) +@click.pass_context +def deactivate_command(ctx, username): + """Activate a user account.""" + try: + ctx.obj.user_manager.change_user_activation(username, False) + click.echo("User {} activated.".format(username)) + + user = ctx.obj.user_manager.find_user(username) + if user: + click.echo("User created:") + click.echo("\t{}".format(_user_to_line(user.asDict()))) + except UnknownUser: + click.echo("User {} does not exist!".format(username), err=True) + + +def _print_list(users): + click.echo("{} users registered in the system:".format(len(users))) + for user in sorted(map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name"))): + click.echo("\t{}".format(_user_to_line(user))) + + +def _user_to_line(user): + return "{name}" \ + "\n\t\tactive: {active}" \ + "\n\t\tgroups: {groups}" \ + "\n\t\tpermissions: {permissions}".format(name=user.get("name"), + active=user.get("active", "False"), + groups=", ".join(user.get("groups", [])), + permissions=", ".join(user.get("permissions", []))) diff --git a/src/octoprint/daemon.py b/src/octoprint/daemon.py index 6b42e1d88..dab6751bd 100644 --- a/src/octoprint/daemon.py +++ b/src/octoprint/daemon.py @@ -1,12 +1,13 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + """ Generic linux daemon base class Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35 """ -from __future__ import absolute_import, division, print_function -import sys, os, time, signal +import io, sys, os, time, signal class Daemon: """ @@ -60,9 +61,9 @@ class Daemon: # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() - si = open(os.devnull, 'r') - so = open(os.devnull, 'a+') - se = open(os.devnull, 'a+') + si = io.open(os.devnull, 'rt', encoding='utf-8') + so = io.open(os.devnull, 'at+', encoding='utf-8') + se = io.open(os.devnull, 'at+', encoding='utf-8') os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) @@ -133,7 +134,7 @@ class Daemon: except OSError: try: self.remove_pidfile() - except: + except Exception: self.error("Daemon found not running, but could not remove stale pidfile") return False else: @@ -142,7 +143,7 @@ class Daemon: def get_pid(self): """Get the pid from the pidfile.""" try: - with open(self.pidfile,'r') as pf: + with io.open(self.pidfile,'rt', encoding='utf-8') as pf: pid = int(pf.read().strip()) except (IOError, ValueError): pid = None @@ -150,7 +151,7 @@ class Daemon: def set_pid(self, pid): """Write the pid to the pidfile.""" - with open(self.pidfile,'w+') as f: + with io.open(self.pidfile,'wt+', encoding='utf-8') as f: f.write(str(pid) + '\n') def remove_pidfile(self): diff --git a/src/octoprint/environment.py b/src/octoprint/environment.py index be72651d8..d1fb6dc56 100644 --- a/src/octoprint/environment.py +++ b/src/octoprint/environment.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -7,7 +7,6 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms import copy import logging import os -import platform import sys import threading import yaml @@ -16,6 +15,7 @@ import psutil from octoprint.plugin import EnvironmentDetectionPlugin from octoprint.util.platform import get_os +from octoprint.util.version import get_python_version_string class EnvironmentDetector(object): @@ -25,10 +25,15 @@ class EnvironmentDetector(object): self._cache = None self._cache_lock = threading.RLock() - self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin) - self._logger = logging.getLogger(__name__) + try: + self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin) + except Exception: + # just in case, see #3100... + self._logger.exception("There was an error fetching EnvironmentDetectionPlugins from the plugin manager") + self._environment_plugins = [] + @property def environment(self): with self._cache_lock: @@ -54,7 +59,7 @@ class EnvironmentDetector(object): self.notify_plugins() return environment - except: + except Exception: self._logger.exception("Unexpected error while detecting environment") with self._cache_lock: self._cache = dict() @@ -70,22 +75,22 @@ class EnvironmentDetector(object): # determine python version try: - result["version"] = platform.python_version() - except: + result["version"] = get_python_version_string() + except Exception: self._logger.exception("Error detecting python version") # determine if we are running from a virtual environment try: if hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)): result["virtualenv"] = sys.prefix - except: + except Exception: self._logger.exception("Error detecting whether we are running in a virtual environment") # try to find pip version try: import pkg_resources result["pip"] = pkg_resources.get_distribution("pip").version - except: + except Exception: self._logger.exception("Error detecting pip version") return result @@ -105,7 +110,7 @@ class EnvironmentDetector(object): result["freq"] = cpu_freq.max if ram and hasattr(ram, "total"): result["ram"] = ram.total - except: + except Exception: self._logger.exception("Error while detecting hardware environment") return result @@ -118,9 +123,10 @@ class EnvironmentDetector(object): additional = implementation.get_additional_environment() if additional is not None and isinstance(additional, dict) and len(additional): result[implementation._identifier] = additional - except: + except Exception: self._logger.exception("Error while fetching additional " - "environment data from plugin {}".format(implementation._identifier)) + "environment data from plugin {}".format(implementation._identifier), + extra=dict(plugin=implementation._identifier)) return result @@ -134,7 +140,7 @@ class EnvironmentDetector(object): try: _log(self._format()) - except: + except Exception: self._logger.exception("Error logging detected environment") def _format(self): @@ -148,7 +154,7 @@ class EnvironmentDetector(object): indent=4, allow_unicode=True).strip() environment_lines = "\n".join(map(lambda l: "| {}".format(l), dumped_environment.split("\n"))) - return u"Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"], + return "Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"], environment["os"]["id"].title(), environment["os"]["platform"], environment_lines) @@ -162,6 +168,6 @@ class EnvironmentDetector(object): for implementation in self._environment_plugins: try: implementation.on_environment_detected(environment) - except: + except Exception: self._logger.exception("Error while sending environment " "detection result to plugin {}".format(implementation._identifier)) diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 5a638a128..526e0e3e7 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge , Lars Norpchen" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -14,6 +14,7 @@ except ImportError: import Queue as queue import threading import collections +import re from octoprint.settings import settings import octoprint.plugin @@ -23,7 +24,7 @@ _instance = None def all_events(): - return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("__")] + return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("_") and not name in ("register_event",)] class Events(object): @@ -46,6 +47,10 @@ class Events(object): CLIENT_OPENED = "ClientOpened" CLIENT_CLOSED = "ClientClosed" + # user login/logout + USER_LOGGED_IN = "UserLoggedIn" + USER_LOGGED_OUT = "UserLoggedOut" + # File management UPLOAD = "Upload" FILE_SELECTED = "FileSelected" @@ -119,6 +124,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 +157,7 @@ class EventManager(object): def __init__(self): self._registeredListeners = collections.defaultdict(list) self._logger = logging.getLogger(__name__) + self._logger_fire = logging.getLogger("{}.fire".format(__name__)) self._startup_signaled = False self._shutdown_signaled = False @@ -156,21 +179,20 @@ class EventManager(object): self._shutdown_signaled = True eventListeners = self._registeredListeners[event] - self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload)) + self._logger_fire.debug("Firing event: {} (Payload: {!r})".format(event, payload)) for listener in eventListeners: - self._logger.debug("Sending action to %r" % listener) + self._logger.debug("Sending action to {!r}".format(listener)) try: listener(event, payload) - except: - self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener)) + except Exception: + self._logger.exception("Got an exception while sending event {} (Payload: {!r}) to {}".format(event, payload, listener)) octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin, "on_event", - args=(event, payload), - initialized=True) + args=(event, payload)) self._logger.info("Event loop shut down") - except: + except Exception: self._logger.exception("Ooops, the event bus worker loop crashed") def fire(self, event, payload=None): @@ -209,14 +231,6 @@ class EventManager(object): q.put((event, payload)) - if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables": - # when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode" - # TODO v1.3.0 Remove again - import copy - legacy_payload = copy.deepcopy(payload) - legacy_payload["type"] = "gcode" - q.put((event, legacy_payload)) - def subscribe(self, event, callback): """ Subscribe a listener to an event -- pass in the event name (as a string) and the callback object @@ -227,7 +241,7 @@ class EventManager(object): return self._registeredListeners[event].append(callback) - self._logger.debug("Subscribed listener %r for event %s" % (callback, event)) + self._logger.debug("Subscribed listener {!r} for event {}".format(callback, event)) def unsubscribe (self, event, callback): """ @@ -236,7 +250,6 @@ class EventManager(object): try: self._registeredListeners[event].remove(callback) - self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event)) except ValueError: # not registered pass @@ -282,7 +295,7 @@ class DebugEventListener(GenericEventListener): def __init__(self): GenericEventListener.__init__(self) - events = filter(lambda x: not x.startswith("__"), dir(Events)) + events = list(filter(lambda x: not x.startswith("__"), dir(Events))) self.subscribe(events) def eventCallback(self, event, payload): @@ -316,26 +329,33 @@ class CommandTrigger(GenericEventListener): self._logger.info("Invalid subscription definition, not a dictionary: {!r}".format(subscription)) continue - if not "event" in subscription.keys() or not "command" in subscription.keys() \ - or not "type" in subscription.keys() or not subscription["type"] in ["system", "gcode"]: + if not "event" in subscription or not "command" in subscription \ + or not "type" in subscription or not subscription["type"] in ["system", "gcode"]: self._logger.info("Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format(subscription)) continue - if "enabled" in subscription.keys() and not subscription["enabled"]: + if "enabled" in subscription and not subscription["enabled"]: self._logger.info("Disabled command trigger: {!r}".format(subscription)) continue - event = subscription["event"] + events = subscription["event"] command = subscription["command"] commandType = subscription["type"] debug = subscription["debug"] if "debug" in subscription else False - if not event in self._subscriptions.keys(): - self._subscriptions[event] = [] - self._subscriptions[event].append((command, commandType, debug)) + # "event" in the configuration can be a string, or + # a list of strings. If it's the former, convert it + # into the latter. + if not isinstance(events, (tuple, list, set)): + events = [events] - if not event in eventsToSubscribe: - eventsToSubscribe.append(event) + for event in events: + if event not in self._subscriptions: + self._subscriptions[event] = [] + self._subscriptions[event].append((command, commandType, debug)) + + if event not in eventsToSubscribe: + eventsToSubscribe.append(event) self.subscribe(eventsToSubscribe) @@ -355,12 +375,12 @@ class CommandTrigger(GenericEventListener): if isinstance(command, (tuple, list, set)): processedCommand = [] for c in command: - processedCommand.append(self._processCommand(c, payload)) + processedCommand.append(self._processCommand(c, event, payload)) else: - processedCommand = self._processCommand(command, payload) + processedCommand = self._processCommand(command, event, payload) self.executeCommand(processedCommand, commandType, debug=debug) - except KeyError as e: - self._logger.warn("There was an error processing one or more placeholders in the following command: %s" % command) + except KeyError: + self._logger.warning("There was an error processing one or more placeholders in the following command: %s" % command) def executeCommand(self, command, commandType, debug=False): if commandType == "system": @@ -388,10 +408,10 @@ class CommandTrigger(GenericEventListener): commandExecutioner(command) except subprocess.CalledProcessError as e: if debug: - self._logger.warn("Command failed with return code {}: {}".format(e.returncode, str(e))) + self._logger.warning("Command failed with return code {}: {}".format(e.returncode, str(e))) else: - self._logger.warn("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode)) - except: + self._logger.warning("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode)) + except Exception: self._logger.exception("Command failed") t = threading.Thread(target=process) @@ -406,13 +426,14 @@ class CommandTrigger(GenericEventListener): self._logger.info("Executing GCode commands: %r" % command) self._printer.commands(commands) - def _processCommand(self, command, payload): + def _processCommand(self, command, event, payload): """ Performs string substitutions in the command string based on a few current parameters. The following substitutions are currently supported: - {__currentZ} : current Z position of the print head, or -1 if not available + - {__eventname} : the name of the event hook being triggered - {__filename} : name of currently selected file, or "NO FILE" if no file is selected - {__filepath} : path in origin location of currently selected file, or "NO FILE" if no file is selected - {__fileorigin} : origin of currently selected file, or "NO FILE" if no file is selected @@ -429,11 +450,13 @@ class CommandTrigger(GenericEventListener): import json try: json_string = json.dumps(payload) - except: + except Exception: + self._logger.exception("JSON: Cannot dump %r", payload) json_string = "" params = { "__currentZ": "-1", + "__eventname": event, "__filename": "NO FILE", "__filepath": "NO PATH", "__progress": "0", diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index df179d1ee..a70acfc3d 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -1,11 +1,12 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging +import io import os import octoprint.plugin @@ -17,6 +18,7 @@ from .destinations import FileDestinations from .analysis import QueueEntry, AnalysisQueue from .storage import LocalFileStorage from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper +from octoprint.util import get_fully_qualified_classname as fqcn from collections import namedtuple @@ -30,10 +32,6 @@ extensions = dict( def full_extension_tree(): result = dict( - # extensions for 3d model files - model=dict( - stl=ContentTypeMapping(["stl"], "application/sla") - ), # extensions for printable machine code machinecode=dict( gcode=ContentTypeMapping(["gcode", "gco", "g"], "text/plain") @@ -74,6 +72,18 @@ def full_extension_tree(): else: return merged + slicer_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin) + for plugin in slicer_plugins: + try: + plugin_result = plugin.get_slicer_extension_tree() + if plugin_result is None or not isinstance(plugin_result, dict): + continue + result = octoprint.util.dict_merge(result, plugin_result, leaf_merger=leaf_merger) + except Exception: + logging.getLogger(__name__).exception("Exception while retrieving additional extension " + "tree entries from SlicerPlugin {name}".format(name=plugin._identifier), + extra=dict(plugin=plugin._identifier)) + extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree") for name, hook in extension_tree_hooks.items(): try: @@ -81,13 +91,15 @@ def full_extension_tree(): if hook_result is None or not isinstance(hook_result, dict): continue result = octoprint.util.dict_merge(result, hook_result, leaf_merger=leaf_merger) - except: - logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from hook {name}".format(name=name)) + except Exception: + logging.getLogger(__name__).exception("Exception while retrieving additional extension " + "tree entries from hook {name}".format(name=name), + extra=dict(plugin=name)) return result def get_extensions(type, subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() for key, value in subtree.items(): @@ -101,7 +113,7 @@ def get_extensions(type, subtree=None): return None def get_all_extensions(subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() result = [] @@ -120,7 +132,7 @@ def get_all_extensions(subtree=None): return result def get_path_for_extension(extension, subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() for key, value in subtree.items(): @@ -136,11 +148,11 @@ def get_path_for_extension(extension, subtree=None): return None def get_content_type_mapping_for_extension(extension, subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() for key, value in subtree.items(): - content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value. extensions + content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions list_extension_matches = isinstance(value, (list, tuple)) and extension in value if content_extension_matches or list_extension_matches: @@ -319,38 +331,41 @@ class FileManager(object): printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None): try: if _error: - eventManager().fire(Events.SLICING_FAILED, dict(stl=source_path, - stl_location=source_location, - gcode=dest_path, - gcode_location=dest_location, - reason=_error)) + eventManager().fire(Events.SLICING_FAILED, dict(slicer=slicer_name, + stl=source_path, + stl_location=source_location, + gcode=dest_path, + gcode_location=dest_location, + reason=_error)) elif _cancelled: - eventManager().fire(Events.SLICING_CANCELLED, dict(stl=source_path, - stl_location=source_location, - gcode=dest_path, - gcode_location=dest_location)) + eventManager().fire(Events.SLICING_CANCELLED, dict(slicer=slicer_name, + stl=source_path, + stl_location=source_location, + gcode=dest_path, + gcode_location=dest_location)) else: source_meta = self.get_metadata(source_location, source_path) - hash = source_meta["hash"] + hash = source_meta.get("hash", "n/a") import io links = [("model", dict(name=source_path))] _, stl_name = self.split_path(source_location, source_path) file_obj = StreamWrapper(os.path.basename(dest_path), - io.BytesIO(u";Generated from {stl_name} {hash}\n".format(**locals()).encode("ascii", "replace")), - io.FileIO(tmp_path, "rb")) + io.BytesIO(";Generated from {stl_name} (hash: {hash})\n".format(**locals()).encode("ascii", "replace")), + io.FileIO(tmp_path, 'rb')) printer_profile = self._printer_profile_manager.get(printer_profile_id) self.add_file(dest_location, dest_path, file_obj, display=display, links=links, allow_overwrite=True, printer_profile=printer_profile, analysis=_analysis) - end_time = time.time() - eventManager().fire(Events.SLICING_DONE, dict(stl=source_path, - stl_location=source_location, - gcode=dest_path, - gcode_location=dest_location, - time=end_time - start_time)) + end_time = octoprint.util.monotonic_time() + eventManager().fire(Events.SLICING_DONE, dict(slicer=slicer_name, + stl=source_path, + stl_location=source_location, + gcode=dest_path, + gcode_location=dest_location, + time=end_time - start_time)) if callback is not None: if callback_args is None: @@ -370,9 +385,9 @@ class FileManager(object): slicer = self._slicing_manager.get_slicer(slicer_name) - import time - start_time = time.time() - eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, + start_time = octoprint.util.monotonic_time() + eventManager().fire(Events.SLICING_STARTED, {"slicer": slicer_name, + "stl": source_path, "stl_location": source_location, "gcode": dest_path, "gcode_location": dest_location, @@ -415,16 +430,20 @@ class FileManager(object): if self._last_slicing_progress != progress_int: self._last_slicing_progress = progress_int for callback in self._slicing_progress_callbacks: - try: callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int) - except: self._logger.exception("Exception while pushing slicing progress") + try: + callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int) + except Exception: + self._logger.exception("Exception while pushing slicing progress", + extra=dict(callback=fqcn(callback))) if progress_int: def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress): for plugin in self._progress_plugins: try: plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress) - except: - self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier) + except Exception: + self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier, + extra=dict(plugin=plugin._identifier)) import threading thread = threading.Thread(target=call_plugins, args=(slicer, source_location, source_path, dest_location, dest_path, progress_int)) @@ -446,8 +465,8 @@ class FileManager(object): def list_files(self, destinations=None, path=None, filter=None, recursive=None): if not destinations: - destinations = self._storage_managers.keys() - if isinstance(destinations, (str, unicode, basestring)): + destinations = list(self._storage_managers.keys()) + if isinstance(destinations, basestring): destinations = [destinations] result = dict() @@ -459,11 +478,11 @@ class FileManager(object): if printer_profile is None: printer_profile = self._printer_profile_manager.get_current_or_default() - for hook in self._preprocessor_hooks.values(): + for name, hook in self._preprocessor_hooks.items(): try: hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite) - except: - self._logger.exception("Error when calling preprocessor hook {}, ignoring".format(hook)) + except Exception: + self._logger.exception("Error when calling preprocessor hook for plugin {}, ignoring".format(name), extra=dict(plugin=name)) continue if hook_file_object is not None: @@ -622,9 +641,9 @@ class FileManager(object): pos=pos, date=time.time()) try: - with atomic_write(self._recovery_file, max_permissions=0o666) as f: + with atomic_write(self._recovery_file, mode='wt', max_permissions=0o666) as f: yaml.safe_dump(data, stream=f, default_flow_style=False, indent=2, allow_unicode=True) - except: + except Exception: self._logger.exception("Could not write recovery data to file {}".format(self._recovery_file)) def delete_recovery_data(self): @@ -633,7 +652,7 @@ class FileManager(object): try: os.remove(self._recovery_file) - except: + except Exception: self._logger.exception("Error deleting recovery data file {}".format(self._recovery_file)) def get_recovery_data(self): @@ -642,10 +661,12 @@ class FileManager(object): import yaml try: - with open(self._recovery_file) as f: + with io.open(self._recovery_file, 'rt', encoding='utf-8') as f: data = yaml.safe_load(f) + if not isinstance(data, dict) or not all(map(lambda x: x in data, ("origin", "path", "pos", "date"))): + raise ValueError("Invalid recovery data structure") return data - except: + except Exception: self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file)) self.delete_recovery_data() diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index b8b9dd246..1e40069a1 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -18,6 +18,8 @@ import time from octoprint.events import Events, eventManager from octoprint.settings import settings +from octoprint.util import monotonic_time +from octoprint.util import get_fully_qualified_classname as fqcn class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")): @@ -95,27 +97,28 @@ class AnalysisQueue(object): self._queues[entry.type].dequeue(entry.location, entry.path) def dequeue_folder(self, destination, path): - for queue in self._queues.values(): - queue.dequeue_folder(destination, path) + for q in self._queues.values(): + q.dequeue_folder(destination, path) def pause(self): - for queue in self._queues.values(): - queue.pause() + for q in self._queues.values(): + q.pause() def resume(self): - for queue in self._queues.values(): - queue.resume() + for q in self._queues.values(): + q.resume() def _analysis_finished(self, entry, result): for callback in self._callbacks: - callback(entry, result) + try: + callback(entry, result) + except: + self._logger.exception(u"Error while pushing analysis data to callback {}".format(callback), + extra=dict(callback=fqcn(callback))) eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"name": entry.name, "path": entry.path, "origin": entry.location, - "result": result, - - # TODO: deprecated, remove in a future release - "file": entry.path}) + "result": result}) class AbstractAnalysisQueue(object): """ @@ -249,20 +252,17 @@ class AbstractAnalysisQueue(object): self._current_progress = 0 try: - start_time = time.time() + start_time = monotonic_time() self._logger.info("Starting analysis of {}".format(entry)) eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name, "path": entry.path, "origin": entry.location, - "type": entry.type, - - # TODO deprecated, remove in 1.4.0 - "file": entry.path}) + "type": entry.type}) try: result = self._do_analysis(high_priority=high_priority) except TypeError: result = self._do_analysis() - self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, time.time() - start_time)) + self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, monotonic_time() - start_time)) self._finished_callback(self._current, result) finally: self._current = None @@ -382,7 +382,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): if not p.commands[0].process: # the process might have been set to None in case of any exception - raise RuntimeError(u"Error while trying to run command {}".format(" ".join(command))) + raise RuntimeError("Error while trying to run command {}".format(" ".join(command))) try: # let's wait for stuff to finish diff --git a/src/octoprint/filemanager/destinations.py b/src/octoprint/filemanager/destinations.py index 11a971884..1659a01eb 100644 --- a/src/octoprint/filemanager/destinations.py +++ b/src/octoprint/filemanager/destinations.py @@ -1,5 +1,6 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' class FileDestinations(object): diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 9cafb0811..925e1e812 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -1,16 +1,17 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" - +import io import logging import os -import pylru import shutil import re +import pylru +import copy try: from os import scandir, walk @@ -19,7 +20,6 @@ except ImportError: from octoprint.util import atomic_write from contextlib import contextmanager -from copy import deepcopy from past.builtins import basestring @@ -28,7 +28,7 @@ from slugify import Slugify import octoprint.filemanager -from octoprint.util import is_hidden_path, to_unicode +from octoprint.util import is_hidden_path, to_unicode, to_bytes class StorageInterface(object): """ @@ -450,11 +450,11 @@ class LocalFileStorage(StorageInterface): This storage type implements :func:`path_on_disk`. """ - _UNICODE_VARIATIONS = re.compile(u"[\uFE00-\uFE0F]") + _UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U) @classmethod def _no_unicode_variations(cls, text): - return cls._UNICODE_VARIATIONS.sub(u"", text) + return cls._UNICODE_VARIATIONS.sub("", text) _SLUGIFY = Slugify() _SLUGIFY.safe_chars = "-_.()[] " @@ -463,7 +463,7 @@ class LocalFileStorage(StorageInterface): def _slugify(cls, text): text = to_unicode(text) text = cls._no_unicode_variations(text) - text = demojize(text, delimiters=(u"", u"")) + text = demojize(text, delimiters=("", "")) return cls._SLUGIFY(text) def __init__(self, basefolder, create=False): @@ -485,6 +485,8 @@ class LocalFileStorage(StorageInterface): import threading self._metadata_lock_mutex = threading.RLock() self._metadata_locks = dict() + self._persisted_metadata_lock_mutex = threading.RLock() + self._persisted_metadata_locks = dict() self._metadata_cache = pylru.lrucache(10) @@ -500,10 +502,10 @@ class LocalFileStorage(StorageInterface): if os.path.exists(old_metadata_path): # load the old metadata file try: - with open(old_metadata_path) as f: + with io.open(old_metadata_path, 'rt', encoding='utf-8') as f: import yaml self._old_metadata = yaml.safe_load(f) - except: + except Exception: self._logger.exception("Error while loading old metadata file") # make sure the metadata is initialized as far as possible @@ -514,7 +516,7 @@ class LocalFileStorage(StorageInterface): try: import shutil shutil.move(old_metadata_path, backup_path) - except: + except Exception: self._logger.exception("Could not rename old metadata.yaml file") else: @@ -597,10 +599,10 @@ class LocalFileStorage(StorageInterface): path = self.sanitize_path(to_unicode(path)) base = self.path_in_storage(path) if base: - base += u"/" + base += "/" else: path = self.basefolder - base = u"" + base = "" return self._list_folder(path, base=base, entry_filter=filter, recursive=recursive) def add_folder(self, path, ignore_existing=True, display=None): @@ -883,6 +885,8 @@ class LocalFileStorage(StorageInterface): if not name in metadata: return + metadata = self._copied_metadata(metadata, name) + if not key in metadata[name] or overwrite: metadata[name][key] = data metadata_dirty = True @@ -907,19 +911,20 @@ class LocalFileStorage(StorageInterface): if not key in metadata[name]: return + metadata = self._copied_metadata(metadata, name) del metadata[name][key] self._save_metadata(path, metadata) def split_path(self, path): path = to_unicode(path) - split = path.split(u"/") + split = path.split("/") if len(split) == 1: - return u"", split[0] + return "", split[0] else: return self.join_path(*split[:-1]), split[-1] def join_path(self, *path): - return u"/".join(map(to_unicode, path)) + return "/".join(map(to_unicode, path)) def sanitize(self, path): """ @@ -948,23 +953,23 @@ class LocalFileStorage(StorageInterface): path = to_unicode(path) if path.startswith(self.basefolder): path = path[len(self.basefolder):] - path = path.replace(os.path.sep, u"/") - path = path.split(u"/") + path = path.replace(os.path.sep, "/") + path = path.split("/") if isinstance(path, (list, tuple)): if len(path) == 1: name = to_unicode(path[0]) - path = u"" + path = "" else: name = to_unicode(path[-1]) path = self.join_path(*map(to_unicode, path[:-1])) if not path: - path = u"" + path = "" return path, name def sanitize_name(self, name): """ - Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise + Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``, ``(``, and ``)`` as is. """ @@ -973,11 +978,11 @@ class LocalFileStorage(StorageInterface): if name is None: return None - if u"/" in name or u"\\" in name: + if "/" in name or "\\" in name: raise ValueError("name must not contain / or \\") - result = self._slugify(name).replace(u" ", u"_") - if result and result != u"." and result != u".." and result[0] == u".": + result = self._slugify(name).replace(" ", "_") + if result and result != "." and result != ".." and result[0] == ".": # hidden files under *nix result = result[1:] return result @@ -991,12 +996,12 @@ class LocalFileStorage(StorageInterface): path = to_unicode(path) if len(path): - if path[0] == u"/": + if path[0] == "/": path = path[1:] - elif path[0] == u"." and path[1] == u"/": + elif path[0] == "." and path[1] == "/": path = path[2:] - path_elements = path.split(u"/") + path_elements = path.split("/") joined_path = self.basefolder for path_element in path_elements: joined_path = os.path.join(joined_path, self.sanitize_name(path_element)) @@ -1016,16 +1021,16 @@ class LocalFileStorage(StorageInterface): counter = 1 while os.path.exists(sanitized_path): counter += 1 - sanitized = self.sanitize_name(u"{}_({}){}".format(sanitized_name, counter, sanitized_ext)) + sanitized = self.sanitize_name("{}_({}){}".format(sanitized_name, counter, sanitized_ext)) sanitized_path = os.path.join(path, sanitized) try: shutil.move(entry_path, sanitized_path) - self._logger.info(u"Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path)) + self._logger.info("Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path)) return sanitized, sanitized_path - except: - self._logger.exception(u"Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path)) + except Exception: + self._logger.exception("Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path)) raise return entry, entry_path @@ -1033,12 +1038,12 @@ class LocalFileStorage(StorageInterface): def path_in_storage(self, path): if isinstance(path, (tuple, list)): path = self.join_path(*path) - if isinstance(path, (str, unicode, basestring)): + if isinstance(path, basestring): path = to_unicode(path) if path.startswith(self.basefolder): path = path[len(self.basefolder):] - path = path.replace(os.path.sep, u"/") - if path.startswith(u"/"): + path = path.replace(os.path.sep, "/") + if path.startswith("/"): path = path[1:] return path @@ -1050,10 +1055,7 @@ class LocalFileStorage(StorageInterface): ##~~ internals def _add_history(self, name, path, data): - metadata = self._get_metadata(path) - - if not name in metadata: - metadata[name] = dict() + metadata = self._copied_metadata(self._get_metadata(path), name) if not "hash" in metadata[name]: metadata[name]["hash"] = self._create_hash(os.path.join(path, name)) @@ -1071,6 +1073,8 @@ class LocalFileStorage(StorageInterface): if not name in metadata or not "history" in metadata[name]: return + metadata = self._copied_metadata(metadata, name) + try: metadata[name]["history"][index].update(data) self._calculate_stats_from_history(name, path, metadata=metadata, save=False) @@ -1084,6 +1088,8 @@ class LocalFileStorage(StorageInterface): if not name in metadata or not "history" in metadata[name]: return + metadata = self._copied_metadata(metadata, name) + try: del metadata[name]["history"][index] self._calculate_stats_from_history(name, path, metadata=metadata, save=False) @@ -1093,9 +1099,9 @@ class LocalFileStorage(StorageInterface): def _calculate_stats_from_history(self, name, path, metadata=None, save=True): if metadata is None: - metadata = self._get_metadata(path) + metadata = self._copied_metadata(self._get_metadata(path), name) - if not name in metadata or not "history" in metadata[name]: + if not "history" in metadata[name]: return # collect data from history @@ -1114,8 +1120,8 @@ class LocalFileStorage(StorageInterface): print_time = history_entry["printTime"] try: print_time = float(print_time) - except: - self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time)) + except Exception: + self._logger.warning("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time)) continue if not printer_profile in former_print_times: @@ -1164,12 +1170,9 @@ class LocalFileStorage(StorageInterface): if file_type: file_type = file_type[0] - metadata = self._get_metadata(path) + metadata = self._copied_metadata(self._get_metadata(path), name) metadata_dirty = False - if not name in metadata: - metadata[name] = dict() - if not "hash" in metadata[name]: metadata[name]["hash"] = self._create_hash(os.path.join(path, name)) @@ -1241,13 +1244,10 @@ class LocalFileStorage(StorageInterface): self._save_metadata(path, metadata) def _remove_links(self, name, path, links): - metadata = self._get_metadata(path) + metadata = self._copied_metadata(self._get_metadata(path), name) metadata_dirty = False - if not name in metadata or not "hash" in metadata[name]: - hash = self._create_hash(os.path.join(path, name)) - else: - hash = metadata[name]["hash"] + hash = metadata[name].get("hash", self._create_hash(os.path.join(path, name))) for rel, data in links: if (rel == "model" or rel == "machinecode") and "name" in data: @@ -1255,6 +1255,7 @@ class LocalFileStorage(StorageInterface): ref_rel = "model" if rel == "machinecode" else "machinecode" for link in metadata[data["name"]]["links"]: if link["rel"] == ref_rel and "name" in link and link["name"] == name and "hash" in link and link["hash"] == hash: + metadata[data["name"]] = copy.deepcopy(metadata[data["name"]]) metadata[data["name"]]["links"].remove(link) metadata_dirty = True @@ -1299,7 +1300,7 @@ class LocalFileStorage(StorageInterface): entry_is_file = entry.is_file() entry_is_dir = entry.is_dir() entry_stat = entry.stat() - except: + except Exception: # error while trying to fetch file metadata, that might be thanks to file already having # been moved or deleted - ignore it and continue continue @@ -1311,7 +1312,7 @@ class LocalFileStorage(StorageInterface): entry_name = new_entry_name entry_path = new_entry_path entry_stat = os.stat(entry_path) - except: + except Exception: # error while trying to rename the file, we'll continue here and ignore it continue @@ -1330,10 +1331,14 @@ class LocalFileStorage(StorageInterface): if entry_name in metadata and isinstance(metadata[entry_name], dict): entry_metadata = metadata[entry_name] if not "display" in entry_metadata and entry_display != entry_name: + if not metadata_dirty: + metadata = self._copied_metadata(metadata, entry_name) metadata[entry_name]["display"] = entry_display entry_metadata["display"] = entry_display metadata_dirty = True else: + if not metadata_dirty: + metadata = self._copied_metadata(metadata, entry_name) entry_metadata = self._add_basic_metadata(path, entry_name, display_name=entry_display, save=False, @@ -1363,10 +1368,14 @@ class LocalFileStorage(StorageInterface): if entry_name in metadata and isinstance(metadata[entry_name], dict): entry_metadata = metadata[entry_name] if not "display" in entry_metadata and entry_display != entry_name: + if not metadata_dirty: + metadata = self._copied_metadata(metadata, entry_name) metadata[entry_name]["display"] = entry_display entry_metadata["display"] = entry_display metadata_dirty = True elif entry_name != entry_display: + if not metadata_dirty: + metadata = self._copied_metadata(metadata, entry_name) entry_metadata = self._add_basic_metadata(path, entry_name, display_name=entry_display, save=False, @@ -1408,7 +1417,7 @@ class LocalFileStorage(StorageInterface): extended_entry_data["size"] = get_size() result[entry_name] = extended_entry_data - except: + except Exception: # So something went wrong somewhere while processing this file entry - log that and continue self._logger.exception("Error while processing entry {}".format(entry_path)) continue @@ -1450,6 +1459,8 @@ class LocalFileStorage(StorageInterface): entry_data["display"] = display_name entry_data.update(additional_metadata) + + metadata = copy.copy(metadata) metadata[entry] = entry_data if save: @@ -1462,7 +1473,7 @@ class LocalFileStorage(StorageInterface): blocksize = 65536 hash = hashlib.sha1() - with open(path, "rb") as f: + with io.open(path, 'rb') as f: buffer = f.read(blocksize) while len(buffer) > 0: hash.update(buffer) @@ -1481,6 +1492,8 @@ class LocalFileStorage(StorageInterface): if not name in metadata: return + metadata = copy.copy(metadata) + if "hash" in metadata[name]: hash = metadata[name]["hash"] for m in metadata.values(): @@ -1494,7 +1507,7 @@ class LocalFileStorage(StorageInterface): def _update_metadata_entry(self, path, name, data): with self._get_metadata_lock(path): - metadata = self._get_metadata(path) + metadata = copy.copy(self._get_metadata(path)) metadata[name] = data self._save_metadata(path, metadata) @@ -1513,58 +1526,91 @@ class LocalFileStorage(StorageInterface): with self._get_metadata_lock(destination_path): self._update_metadata_entry(destination_path, destination_name, source_data) - def _get_metadata(self, path): - with self._get_metadata_lock(path): - if path in self._metadata_cache: - return deepcopy(self._metadata_cache[path]) + def _get_metadata(self, path, force=False): + import json - self._migrate_metadata(path) + if not force: + metadata = self._metadata_cache.get(path) + if metadata: + return metadata - metadata_path = os.path.join(path, ".metadata.json") + self._migrate_metadata(path) + + metadata_path = os.path.join(path, ".metadata.json") + + metadata = None + with self._get_persisted_metadata_lock(path): if os.path.exists(metadata_path): - with open(metadata_path) as f: + with io.open(metadata_path, 'rt', encoding='utf-8') as f: try: - import json metadata = json.load(f) - except: + except Exception: self._logger.exception("Error while reading .metadata.json from {path}".format(**locals())) - else: - if isinstance(metadata, dict): - self._metadata_cache[path] = deepcopy(metadata) - return metadata + + def valid_json(value): + try: + json.dumps(value, allow_nan=False) + return True + except: + return False + + if isinstance(metadata, dict): + old_size = len(metadata) + metadata = { k: v for k, v in metadata.items() if valid_json(v) } + metadata = { k: v for k, v in metadata.items() if os.path.exists(os.path.join(path, k)) } + new_size = len(metadata) + if new_size != old_size: + self._logger.info("Deleted {} stale or invalid entries from metadata for path {}".format(old_size - new_size, + path)) + self._save_metadata(path, metadata) + else: + with self._get_metadata_lock(path): + self._metadata_cache[path] = metadata + return metadata + else: return dict() def _save_metadata(self, path, metadata): + import json + with self._get_metadata_lock(path): + self._metadata_cache[path] = metadata + + with self._get_persisted_metadata_lock(path): metadata_path = os.path.join(path, ".metadata.json") try: - import json - with atomic_write(metadata_path) as f: - json.dump(metadata, f, indent=4, separators=(",", ": ")) - except: + with atomic_write(metadata_path, mode='wb') as f: + f.write(to_bytes(json.dumps(metadata, indent=4, separators=(",", ": ")))) + except Exception: self._logger.exception("Error while writing .metadata.json to {path}".format(**locals())) - else: - self._metadata_cache[path] = deepcopy(metadata) def _delete_metadata(self, path): with self._get_metadata_lock(path): + if path in self._metadata_cache: + del self._metadata_cache[path] + + with self._get_persisted_metadata_lock(path): metadata_files = (".metadata.json", ".metadata.yaml") for metadata_file in metadata_files: metadata_path = os.path.join(path, metadata_file) if os.path.exists(metadata_path): try: os.remove(metadata_path) - except: + except Exception: self._logger.exception("Error while deleting {metadata_file} from {path}".format(**locals())) - if path in self._metadata_cache: - del self._metadata_cache[path] + + @staticmethod + def _copied_metadata(metadata, name): + metadata = copy.copy(metadata) + metadata[name] = copy.deepcopy(metadata.get(name, dict())) + return metadata def _migrate_metadata(self, path): # we switched to json in 1.3.9 - if we still have yaml here, migrate it now import yaml import json - with self._get_metadata_lock(path): + with self._get_persisted_metadata_lock(path): metadata_path_yaml = os.path.join(path, ".metadata.yaml") metadata_path_json = os.path.join(path, ".metadata.json") @@ -1574,13 +1620,16 @@ class LocalFileStorage(StorageInterface): if os.path.exists(metadata_path_json): # already migrated - # TODO 1.3.10 Remove ".metadata.yaml" files + try: + os.remove(metadata_path_yaml) + except Exception: + self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals())) return - with open(metadata_path_yaml) as f: + with io.open(metadata_path_yaml, 'rt', encoding='utf-8') as f: try: metadata = yaml.safe_load(f) - except: + except Exception: self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals())) return @@ -1588,10 +1637,13 @@ class LocalFileStorage(StorageInterface): # looks invalid, ignore it return - with atomic_write(metadata_path_json) as f: - json.dump(metadata, f, indent=4, separators=(",", ": ")) + with atomic_write(metadata_path_json, mode='wb') as f: + f.write(to_bytes(json.dumps(metadata, indent=4, separators=(",", ": ")))) - # TODO 1.3.10 Remove ".metadata.yaml" files + try: + os.remove(metadata_path_yaml) + except Exception: + self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals())) @contextmanager def _get_metadata_lock(self, path): @@ -1613,3 +1665,24 @@ class LocalFileStorage(StorageInterface): del self._metadata_locks[path] else: self._metadata_locks[path] = (counter, lock) + + @contextmanager + def _get_persisted_metadata_lock(self, path): + with self._persisted_metadata_lock_mutex: + if path not in self._persisted_metadata_locks: + import threading + self._persisted_metadata_locks[path] = (0, threading.RLock()) + + counter, lock = self._persisted_metadata_locks[path] + counter += 1 + self._persisted_metadata_locks[path] = (counter, lock) + + yield lock + + with self._persisted_metadata_lock_mutex: + counter = self._persisted_metadata_locks[path][0] + counter -= 1 + if counter <= 0: + del self._persisted_metadata_locks[path] + else: + self._persisted_metadata_locks[path] = (counter, lock) diff --git a/src/octoprint/filemanager/util.py b/src/octoprint/filemanager/util.py index d8bd9561f..4a247e62b 100644 --- a/src/octoprint/filemanager/util.py +++ b/src/octoprint/filemanager/util.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -64,7 +64,7 @@ class DiskFileWrapper(AbstractFileWrapper): shutil.copy2(self.path, path) def stream(self): - return io.open(self.path, "rb") + return io.open(self.path, 'rb') class StreamWrapper(AbstractFileWrapper): """ @@ -87,7 +87,7 @@ class StreamWrapper(AbstractFileWrapper): """ import shutil - with atomic_write(path, "wb") as dest: + with atomic_write(path, mode='wb') as dest: with self.stream() as source: shutil.copyfileobj(source, dest) @@ -142,7 +142,7 @@ class MultiStream(io.RawIOBase): for stream in self.streams: try: stream.close() - except: + except Exception: pass def readable(self, *args, **kwargs): diff --git a/src/octoprint/logging/__init__.py b/src/octoprint/logging/__init__.py index 1021b169a..10dae37d7 100644 --- a/src/octoprint/logging/__init__.py +++ b/src/octoprint/logging/__init__.py @@ -1,8 +1,12 @@ -# coding=utf-8 -from __future__ import absolute_import +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + +from past.builtins import basestring, unicode from octoprint.logging import handlers +from typing import Union + def log_to_handler(logger, handler, level, msg, exc_info=None, extra=None, *args): """ Logs to the provided handler only. @@ -77,17 +81,17 @@ def get_divider_line(c, message=None, length=78, indent=3): Examples: - >>> get_divider_line("-") + >>> get_divider_line("-") # doctest: +ALLOW_UNICODE '------------------------------------------------------------------------------' - >>> get_divider_line("=", length=10) + >>> get_divider_line("=", length=10) # doctest: +ALLOW_UNICODE '==========' - >>> get_divider_line("-", message="Hi", length=10) + >>> get_divider_line("-", message="Hi", length=10) # doctest: +ALLOW_UNICODE '--- Hi ---' - >>> get_divider_line("-", message="A slightly longer text") + >>> get_divider_line("-", message="A slightly longer text") # doctest: +ALLOW_UNICODE '--- A slightly longer text ---------------------------------------------------' - >>> get_divider_line("-", message="A slightly longer text", indent=5) + >>> get_divider_line("-", message="A slightly longer text", indent=5) # doctest: +ALLOW_UNICODE '----- A slightly longer text -------------------------------------------------' - >>> get_divider_line("-", message="Hello World!", length=10) + >>> get_divider_line("-", message="Hello World!", length=10) # doctest: +ALLOW_UNICODE '--- Hello World!' >>> get_divider_line(None) Traceback (most recent call last): @@ -120,7 +124,7 @@ def get_divider_line(c, message=None, length=78, indent=3): formatted divider line """ - assert isinstance(c, (str, unicode, bytes)), "c is not text" + assert isinstance(c, basestring), "c is not text" assert len(c) == 1, "c is not a single character" assert isinstance(length, int), "length is not an int" assert isinstance(indent, int), "indent is not an int" @@ -128,7 +132,7 @@ def get_divider_line(c, message=None, length=78, indent=3): if message is None: return c * length - assert isinstance(message, (str, unicode, bytes)), "message is not text" + assert isinstance(message, basestring), "message is not text" space = length - 2 * (indent + 1) if space >= len(message): @@ -137,14 +141,16 @@ def get_divider_line(c, message=None, length=78, indent=3): return c * indent + " " + message -def prefix_multilines(text, prefix=": "): +def prefix_multilines(text, prefix=u": "): + # type: (Union[unicode, bytes], unicode) -> unicode + from octoprint.util import to_unicode + lines = text.splitlines() if not lines: - return "" + return u"" if len(lines) == 1: - return lines[0] - - return lines[0] + "\n" + "\n".join(map(lambda line: prefix + line, - lines[1:])) + return to_unicode(lines[0]) + return to_unicode(lines[0]) + u"\n" + u"\n".join(map(lambda line: prefix + to_unicode(line), + lines[1:])) diff --git a/src/octoprint/logging/handlers.py b/src/octoprint/logging/handlers.py index 9c8b07acc..adc079b56 100644 --- a/src/octoprint/logging/handlers.py +++ b/src/octoprint/logging/handlers.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals import logging.handlers import os @@ -18,7 +18,7 @@ class AsyncLogHandlerMixin(logging.Handler): def emit(self, record): try: self._executor.submit(self._emit, record) - except: + except Exception: self.handleError(record) def _emit(self, record): @@ -29,6 +29,8 @@ class AsyncLogHandlerMixin(logging.Handler): class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler): def __init__(self, *args, **kwargs): + kwargs["encoding"] = kwargs.get("encoding", "utf-8") + super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs) # clean up old files on handler start @@ -40,6 +42,10 @@ class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler): rollover_callbacks = [] + def __init__(self, *args, **kwargs): + kwargs["encoding"] = kwargs.get("encoding", "utf-8") + super(OctoPrintLogHandler, self).__init__(*args, **kwargs) + @classmethod def registerRolloverCallback(cls, callback, *args, **kwargs): cls.rollover_callbacks.append((callback, args, kwargs)) @@ -67,6 +73,7 @@ class SerialLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandle cls.do_rollover = True def __init__(self, *args, **kwargs): + kwargs["encoding"] = kwargs.get("encoding", "utf-8") super(SerialLogHandler, self).__init__(*args, **kwargs) self.cleanupFiles() diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index f99f441fb..e718a7aa3 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -1,4 +1,6 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + """ This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the registered plugin types. @@ -13,40 +15,30 @@ registered plugin types. :members: """ -from __future__ import absolute_import, division, print_function - __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import os import logging +import threading from octoprint.settings import settings as s from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin) -from octoprint.plugin.types import * +from octoprint.plugin.types import OctoPrintPlugin, SettingsPlugin +from octoprint.plugin.types import * # noqa: F403 ## used by multiple other modules -from octoprint.util import deprecated +from octoprint.util import deprecated, to_native_str # singleton _instance = None def _validate_plugin(phase, plugin_info): - if phase == "after_load": - if plugin_info.implementation is not None and isinstance(plugin_info.implementation, AppPlugin): - # transform app plugin into hook - import warnings - warnings.warn("{name} uses deprecated plugin mixin AppPlugin, use octoprint.accesscontrol.appkey hook instead".format(name=plugin_info.key), DeprecationWarning) - - hooks = plugin_info.hooks - if not "octoprint.accesscontrol.appkey" in hooks: - hooks["octoprint.accesscontrol.appkey"] = plugin_info.implementation.get_additional_apps - setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks) return True def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, - plugin_validators=None): + plugin_validators=None, compatibility_ignored_list=None): """ Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager` singleton. @@ -72,6 +64,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en plugin_obsolete_hooks (list): A list of hooks that have been declared obsolete. Plugins implementing them will not be enabled since they might depend on functionality that is no longer available. plugin_validators (list): A list of additional plugin validators through which to process each plugin. + compatibility_ignored_list (list): A list of plugin keys for which it will be ignored if they are flagged as + incompatible. This is for development purposes only and should not be used in production. Returns: PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin @@ -114,7 +108,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en plugin_blacklist=plugin_blacklist, plugin_restart_needing_hooks=plugin_restart_needing_hooks, plugin_obsolete_hooks=plugin_obsolete_hooks, - plugin_validators=plugin_validators) + plugin_validators=plugin_validators, + compatibility_ignored_list=compatibility_ignored_list) else: raise ValueError("Plugin Manager not initialized yet") return _instance @@ -162,14 +157,15 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None): try: get_preprocessors, set_preprocessors = instance.get_settings_preprocessors() - except: + except Exception: logging.getLogger(__name__).exception("Error while retrieving preprocessors for plugin {}".format(plugin_key)) return None return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings) -def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True): +def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, + initialized=True): """ Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success @@ -205,9 +201,7 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call error_callback (function): A callback to invoke after the call of an implementation resulted in an exception. Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception. - initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status - is determined be presence of injected ``_identifier`` property. - + initialized (boolean): Ignored. """ if not isinstance(types, (list, tuple)): @@ -217,18 +211,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"): + if 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, extra=dict(plugin=plugin._identifier)) if error_callback: error_callback(plugin._identifier, plugin, exc) @@ -304,6 +301,17 @@ class PluginSettings(object): .. method:: set_boolean(path, value, force=False) Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it. + + .. method:: save(force=False, trigger_event=False) + + Saves the settings to ``config.yaml`` if there are active changes. If ``force`` is set to ``True`` the settings + will be saved even if there are no changes. Settings ``trigger_event`` to ``True`` will cause a ``SettingsUpdated`` + :ref:`event ` to get triggered. + + :param force: Force saving to ``config.yaml`` even if there are no changes. + :type force: boolean + :param trigger_event: Trigger the ``SettingsUpdated`` :ref:`event ` on save. + :type trigger_event: boolean """ def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None): @@ -498,7 +506,7 @@ class PluginSettings(object): self.settings.remove(self._prefix_path()) def __getattr__(self, item): - all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys() + all_access_methods = list(self.access_methods.keys()) + list(self.deprecated_access_methods.keys()) if item in all_access_methods: decorator = None if item in self.deprecated_access_methods: @@ -514,44 +522,9 @@ class PluginSettings(object): def _func(*args, **kwargs): return orig_func(*args_mapper(args), **kwargs_mapper(kwargs)) - _func.__name__ = item + _func.__name__ = to_native_str(item) _func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None return _func return getattr(self.settings, item) - - ##~~ deprecated methods follow - - # TODO: Remove with release of 1.3.0 - - globalGet = deprecated("globalGet has been renamed to global_get", - includedoc="Replaced by :func:`global_get`", - since="1.2.0-dev-546")(global_get) - globalGetInt = deprecated("globalGetInt has been renamed to global_get_int", - includedoc="Replaced by :func:`global_get_int`", - since="1.2.0-dev-546")(global_get_int) - globalGetFloat = deprecated("globalGetFloat has been renamed to global_get_float", - includedoc="Replaced by :func:`global_get_float`", - since="1.2.0-dev-546")(global_get_float) - globalGetBoolean = deprecated("globalGetBoolean has been renamed to global_get_boolean", - includedoc="Replaced by :func:`global_get_boolean`", - since="1.2.0-dev-546")(global_get_boolean) - globalSet = deprecated("globalSet has been renamed to global_set", - includedoc="Replaced by :func:`global_set`", - since="1.2.0-dev-546")(global_set) - globalSetInt = deprecated("globalSetInt has been renamed to global_set_int", - includedoc="Replaced by :func:`global_set_int`", - since="1.2.0-dev-546")(global_set_int) - globalSetFloat = deprecated("globalSetFloat has been renamed to global_set_float", - includedoc="Replaced by :func:`global_set_float`", - since="1.2.0-dev-546")(global_set_float) - globalSetBoolean = deprecated("globalSetBoolean has been renamed to global_set_boolean", - includedoc="Replaced by :func:`global_set_boolean`", - since="1.2.0-dev-546")(global_set_boolean) - globalGetBaseFolder = deprecated("globalGetBaseFolder has been renamed to global_get_basefolder", - includedoc="Replaced by :func:`global_get_basefolder`", - since="1.2.0-dev-546")(global_get_basefolder) - getPluginLogfilePath = deprecated("getPluginLogfilePath has been renamed to get_plugin_logfile_path", - includedoc="Replaced by :func:`get_plugin_logfile_path`", - since="1.2.0-dev-546")(get_plugin_logfile_path) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 79240bff7..05a46ff22 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -1,4 +1,6 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + """ In this module resides the core data structures and logic of the plugin system. It is implemented in an OctoPrint-agnostic way and could be extracted into a separate Python module in the future. @@ -20,32 +22,58 @@ way and could be extracted into a separate Python module in the future. """ -from __future__ import absolute_import, division, print_function - -__author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import os -import imp +import io from collections import defaultdict, namedtuple, OrderedDict import logging import fnmatch import inspect +import sys import pkg_resources import pkginfo -from past.builtins import basestring +from past.builtins import unicode + +from octoprint.util import to_unicode, sv +from octoprint.util.version import is_python_compatible, get_python_version_string try: from os import scandir except ImportError: from scandir import scandir + +if sys.version_info[0] == 2: + # noinspection PyDeprecation + import imp +else: + # deprecated in Python 3.4+ and hence vendored for now + import octoprint.vendor.imp as imp + + +# noinspection PyDeprecation +def _find_module(name, path=None): + if path is not None: + spec = imp.find_module(name, [path]) + else: + spec = imp.find_module(name) + return spec[1], spec + + +# noinspection PyDeprecation +def _load_module(name, spec): + f, filename, details = spec + return imp.load_module(name, f, filename, details) + + EntryPointOrigin = namedtuple("EntryPointOrigin", "type, entry_point, module_name, package_name, package_version") FolderOrigin = namedtuple("FolderOrigin", "type, folder") +ModuleOrigin = namedtuple("PackageOrigin", "type, module_name, folder") class PluginInfo(object): """ @@ -90,6 +118,18 @@ class PluginInfo(object): attr_license = '__plugin_license__' """ Module attribute from which to retrieve the plugin's license. """ + attr_pythoncompat = '__plugin_pythoncompat__' + """ + Module attribute from which to retrieve the plugin's python compatibility string. + + If unset a default of ``>=2.7,<3`` will be assumed, meaning that the plugin will be considered compatible to + Python 2 but not Python 3. + + To mark a plugin as Python 3 compatible, a string of ``>=2.7,<4`` is recommended. + + Bundled plugins will automatically be assumed to be compatible. + """ + attr_hooks = '__plugin_hooks__' """ Module attribute from which to retrieve the plugin's provided hooks. """ @@ -145,10 +185,12 @@ class PluginInfo(object): self.enabled = True self.blacklisted = False self.forced_disabled = False + self.incompatible = False self.bundled = False self.loaded = False self.managable = True self.needs_restart = False + self.invalid_syntax = False self._name = name self._version = version @@ -160,12 +202,14 @@ class PluginInfo(object): self._logger = logging.getLogger(__name__) self._cached_parsed_metadata = parsed_metadata + if self._cached_parsed_metadata is None: + self._cached_parsed_metadata = self._parse_metadata() def validate(self, phase, additional_validators=None): result = True if phase == "before_import": - result = not self.forced_disabled and not self.blacklisted and result + result = not self.forced_disabled and not self.blacklisted and not self.incompatible and not self.invalid_syntax and result elif phase == "before_load": # if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__ @@ -209,11 +253,11 @@ class PluginInfo(object): if self.version: return "{name} ({version})".format(name=self.name, version=self.version) else: - return self.name + return to_unicode(self.name) def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""), show_location=False, location_str=" - {location}", - show_enabled=False, enabled_strs=("* ", " ", "X ")): + show_enabled=False, enabled_strs=("* ", " ", "X ", "C ")): """ Long string representation of the plugin's information. Will return a string of the format ````. @@ -221,8 +265,9 @@ class PluginInfo(object): The will be filled from ``enabled_str``, ``bundled_str`` and ``location_str`` as follows: ``enabled_str`` - a 3-tuple, the first entry being the string to insert when the plugin is enabled, the second - entry the string to insert when it is not, the third entry the string when it is blacklisted. + a 4-tuple, the first entry being the string to insert when the plugin is enabled, the second + entry the string to insert when it is not, the third entry the string when it is blacklisted + and the fourth when it is incompatible. ``bundled_str`` a 2-tuple, the first entry being the string to insert when the plugin is bundled, the second entry the string to insert when it is not. @@ -242,17 +287,24 @@ class PluginInfo(object): str: The long string representation of the plugin as described above """ if show_enabled: - ret = enabled_strs[2] if self.blacklisted else (enabled_strs[0] if self.enabled else enabled_strs[1]) + if self.incompatible: + ret = to_unicode(enabled_strs[3]) + elif self.blacklisted: + ret = to_unicode(enabled_strs[2]) + elif not self.enabled: + ret = to_unicode(enabled_strs[1]) + else: + ret = to_unicode(enabled_strs[0]) else: ret = "" - ret += str(self) + ret += unicode(self) if show_bundled: - ret += bundled_strs[0] if self.bundled else bundled_strs[1] + ret += to_unicode(bundled_strs[0]) if self.bundled else to_unicode(bundled_strs[1]) if show_location and self.location: - ret += location_str.format(location=self.location) + ret += to_unicode(location_str).format(location=self.location) return ret @@ -379,6 +431,19 @@ class PluginInfo(object): default=self._license, incl_metadata=True) + @property + def pythoncompat(self): + """ + Python compatibility string of the plugin module as defined in :attr:`attr_pythoncompat` if available, otherwise + defaults to ``>=2.7,<3``. + + Returns: + str: Python compatibility string of the plugin + """ + return self._get_instance_attribute(self.__class__.attr_pythoncompat, + default=">=2.7,<3", + incl_metadata=True) + @property def hooks(self): """ @@ -486,8 +551,6 @@ class PluginInfo(object): @property def parsed_metadata(self): - if self._cached_parsed_metadata is None: - self._cached_parsed_metadata = self._parse_metadata() return self._cached_parsed_metadata def _parse_metadata(self): @@ -512,18 +575,19 @@ class PluginInfo(object): try: import ast - with open(path, "rb") as f: - root = ast.parse(f.read()) + with io.open(path, 'rb') as f: + root = ast.parse(f.read(), filename=path) - assignments = filter(lambda x: isinstance(x, ast.Assign) and x.targets, - root.body) + assignments = list(filter(lambda x: isinstance(x, ast.Assign) and x.targets, + root.body)) def extract_target_ids(node): return list(map(lambda x: x.id, filter(lambda x: isinstance(x, ast.Name), node.targets))) for key in (self.__class__.attr_name, self.__class__.attr_version, self.__class__.attr_author, - self.__class__.attr_description, self.__class__.attr_url, self.__class__.attr_license): + self.__class__.attr_description, self.__class__.attr_url, self.__class__.attr_license, + self.__class__.attr_pythoncompat): for a in reversed(assignments): targets = extract_target_ids(a) if key in targets: @@ -536,8 +600,11 @@ class PluginInfo(object): result[key] = a.value.args[0].s break - except: - pass + except SyntaxError: + self._logger.exception("Invalid syntax in {} for plugin {}".format(path, self.key)) + self.invalid_syntax = True + except Exception: + self._logger.exception("Error while parsing AST from {} for plugin {}".format(path, self.key)) return result @@ -552,7 +619,7 @@ class PluginManager(object): def __init__(self, plugin_folders, plugin_bases, plugin_entry_points, logging_prefix=None, plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None, - plugin_obsolete_hooks=None, plugin_validators=None): + plugin_obsolete_hooks=None, plugin_validators=None, compatibility_ignored_list=None): self.logger = logging.getLogger(__name__) if logging_prefix is None: @@ -567,6 +634,8 @@ class PluginManager(object): plugin_disabled_list = [] if plugin_blacklist is None: plugin_blacklist = [] + if compatibility_ignored_list is None: + compatibility_ignored_list = [] self.plugin_folders = plugin_folders self.plugin_bases = plugin_bases @@ -577,6 +646,7 @@ class PluginManager(object): self.plugin_obsolete_hooks = plugin_obsolete_hooks self.plugin_validators = plugin_validators self.logging_prefix = logging_prefix + self.compatibility_ignored_list = compatibility_ignored_list self.enabled_plugins = dict() self.disabled_plugins = dict() @@ -651,7 +721,7 @@ class PluginManager(object): ignored_uninstalled=ignore_uninstalled) result_added.update(added) result_found += found - except: + except Exception: self.logger.exception("Error fetching plugins from folders") if self.plugin_entry_points: @@ -662,7 +732,7 @@ class PluginManager(object): ignore_uninstalled=ignore_uninstalled) result_added.update(added) result_found += found - except: + except Exception: self.logger.exception("Error fetching plugins from entry points") return result_added, result_found @@ -674,15 +744,18 @@ class PluginManager(object): for folder in folders: try: flagged_readonly = False + package = None if isinstance(folder, (list, tuple)): if len(folder) == 2: folder, flagged_readonly = folder + elif len(folder) == 3: + folder, package, flagged_readonly = folder else: continue actual_readonly = not os.access(folder, os.W_OK) if not os.path.exists(folder): - self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder)) + self.logger.warning("Plugin folder {folder} could not be found, skipping it".format(folder=folder)) continue for entry in scandir(folder): @@ -714,15 +787,22 @@ class PluginManager(object): bundled = flagged_readonly - plugin = self._import_plugin_from_module(key, folder=folder, bundled=bundled) + module_name = None + if package: + module_name = "{}.{}".format(package, key) + + plugin = self._import_plugin_from_module(key, module_name=module_name, folder=folder, bundled=bundled) if plugin: - plugin.origin = FolderOrigin("folder", folder) + if module_name: + plugin.origin = ModuleOrigin("module", module_name, folder) + else: + plugin.origin = FolderOrigin("folder", folder) plugin.managable = not flagged_readonly and not actual_readonly plugin.enabled = False added[key] = plugin - except: + except Exception: self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder)) - except: + except Exception: self.logger.exception("Error processing folder {}".format(folder)) return added, found @@ -752,7 +832,7 @@ class PluginManager(object): for entry in gen: try: yield entry - except: + except Exception: self.logger.exception("Something went wrong while processing the entry points of a package in the " "Python environment - broken entry_points.txt in some package?") @@ -772,7 +852,7 @@ class PluginManager(object): package_name = entry_point.dist.project_name try: entry_point_metadata = EntryPointMetadata(entry_point) - except: + except Exception: self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name)) else: kwargs.update(dict( @@ -802,7 +882,7 @@ class PluginManager(object): plugin.location)) added[key] = plugin - except: + except Exception: self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group)) return added, found @@ -812,17 +892,17 @@ class PluginManager(object): # TODO error handling try: if folder: - module = imp.find_module(key, [folder]) + location, spec = _find_module(key, path=folder) elif module_name: - module = imp.find_module(module_name) + location, spec = _find_module(module_name) else: return None - except: - self.logger.warn("Could not locate plugin {key}".format(key=key)) + except Exception: + self.logger.exception("Could not locate plugin {key}".format(key=key)) return None # Create a simple dummy entry first ... - plugin = PluginInfo(key, module[1], None, name=name, version=version, description=summary, author=author, + plugin = PluginInfo(key, location, None, name=name, version=version, description=summary, author=author, url=url, license=license) plugin.bundled = bundled @@ -831,21 +911,34 @@ class PluginManager(object): plugin.forced_disabled = True if self._is_plugin_blacklisted(key) or (plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version)): - self.logger.warn("Plugin {} is blacklisted.".format(plugin)) + self.logger.warning("Plugin {} is blacklisted.".format(plugin)) plugin.blacklisted = True + python_version = get_python_version_string() + if self._is_plugin_incompatible(key, plugin): + if plugin.invalid_syntax: + self.logger.warning("Plugin {} can't be compiled under Python {} due to invalid syntax".format(plugin, python_version)) + else: + self.logger.warning("Plugin {} is not compatible to Python {} (compatibility string: {}).".format(plugin, python_version, plugin.pythoncompat)) + plugin.incompatible = True + if not plugin.validate("before_import", additional_validators=self.plugin_validators): return plugin # ... then create and return the real one - return self._import_plugin(key, *module, - name=name, version=version, summary=summary, author=author, url=url, - license=license, bundled=bundled, parsed_metadata=plugin.parsed_metadata) + return self._import_plugin(key, spec, + module_name=module_name, name=name, location=plugin.location, 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, spec, module_name=None, name=None, location=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None): try: - instance = imp.load_module(key, f, filename, description) - plugin = PluginInfo(key, filename, instance, + if module_name: + module = _load_module(module_name, spec) + else: + module = _load_module(key, spec) + + plugin = PluginInfo(key, location, module, name=name, version=version, description=summary, @@ -853,8 +946,9 @@ class PluginManager(object): url=url, license=license, parsed_metadata=parsed_metadata) + plugin.bundled = bundled - except: + except Exception: self.logger.exception("Error loading plugin {key}".format(key=key)) return None @@ -870,6 +964,11 @@ class PluginManager(object): def _is_plugin_blacklisted(self, key): return key in self.plugin_blacklist + def _is_plugin_incompatible(self, key, plugin): + return not plugin.bundled \ + and not is_python_compatible(plugin.pythoncompat) \ + and key not in self.compatibility_ignored_list + def _is_plugin_version_blacklisted(self, key, version): def matches_plugin(entry): if isinstance(entry, (tuple, list)) and len(entry) == 2: @@ -892,7 +991,7 @@ class PluginManager(object): incl_all_found=True) # let's clean everything we DIDN'T find first - removed = [key for key in self.enabled_plugins.keys() + self.disabled_plugins.keys() if key not in found] + removed = [key for key in list(self.enabled_plugins.keys()) + list(self.disabled_plugins.keys()) if key not in found] for key in removed: try: del self.enabled_plugins[key] @@ -925,7 +1024,7 @@ class PluginManager(object): try: if plugin.loaded and not plugin.forced_disabled: if plugin.blacklisted: - self.logger.warn("Plugin {} is blacklisted. Not enabling it.".format(plugin)) + self.logger.warning("Plugin {} is blacklisted. Not enabling it.".format(plugin)) continue self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup) except PluginNeedsRestart: @@ -967,7 +1066,7 @@ class PluginManager(object): def load_plugin(self, name, plugin=None, startup=False, initialize_implementation=True): if not name in self.plugins: - self.logger.warn("Trying to load an unknown plugin {name}".format(**locals())) + self.logger.warning("Trying to load an unknown plugin {name}".format(**locals())) return if plugin is None: @@ -985,12 +1084,12 @@ class PluginManager(object): self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals())) except PluginLifecycleException as e: raise e - except: + except Exception: self.logger.exception("There was an error loading plugin %s" % name) def unload_plugin(self, name): if not name in self.plugins: - self.logger.warn("Trying to unload unknown plugin {name}".format(**locals())) + self.logger.warning("Trying to unload unknown plugin {name}".format(**locals())) return plugin = self.plugins[name] @@ -1013,7 +1112,7 @@ class PluginManager(object): self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals())) except PluginLifecycleException as e: raise e - except: + except Exception: self.logger.exception("There was an error unloading plugin {name}".format(**locals())) # make sure the plugin is NOT in the list of enabled plugins but in the list of disabled plugins @@ -1024,7 +1123,7 @@ class PluginManager(object): def enable_plugin(self, name, plugin=None, initialize_implementation=True, startup=False): if not name in self.disabled_plugins: - self.logger.warn("Tried to enable plugin {name}, however it is not disabled".format(**locals())) + self.logger.warning("Tried to enable plugin {name}, however it is not disabled".format(**locals())) return if plugin is None: @@ -1044,7 +1143,7 @@ class PluginManager(object): self._activate_plugin(name, plugin) except PluginLifecycleException as e: raise e - except: + except Exception: self.logger.exception("There was an error while enabling plugin {name}".format(**locals())) return False else: @@ -1066,7 +1165,7 @@ class PluginManager(object): def disable_plugin(self, name, plugin=None): if not name in self.enabled_plugins: - self.logger.warn("Tried to disable plugin {name}, however it is not enabled".format(**locals())) + self.logger.warning("Tried to disable plugin {name}, however it is not enabled".format(**locals())) return if plugin is None: @@ -1080,7 +1179,7 @@ class PluginManager(object): self._deactivate_plugin(name, plugin) except PluginLifecycleException as e: raise e - except: + except Exception: self.logger.exception("There was an error while disabling plugin {name}".format(**locals())) return False else: @@ -1105,7 +1204,7 @@ class PluginManager(object): try: callback, order = self._get_callback_and_order(definition) except ValueError as e: - self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) + self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) continue self._plugin_hooks[hook].append((order, name, callback)) @@ -1124,7 +1223,7 @@ class PluginManager(object): try: callback, order = self._get_callback_and_order(definition) except ValueError as e: - self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) + self.logger.warning("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) continue try: @@ -1183,7 +1282,7 @@ class PluginManager(object): if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): hooks = hooks[0] - hooks = filter(lambda hook: hook is not None, hooks) + hooks = list(filter(lambda hook: hook is not None, hooks)) if not hooks: return False if not plugin or not plugin.hooks: @@ -1217,7 +1316,7 @@ class PluginManager(object): if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): hooks = hooks[0] - hooks = filter(lambda hook: hook is not None, hooks) + hooks = list(filter(lambda hook: hook is not None, hooks)) if not hooks: return False if not hook: @@ -1255,7 +1354,7 @@ class PluginManager(object): if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)): mixins = mixins[0] - mixins = filter(lambda mixin: mixin is not None, mixins) + mixins = list(filter(lambda mixin: mixin is not None, mixins)) if not mixins: return False if not plugin or not plugin.implementation: @@ -1325,7 +1424,7 @@ class PluginManager(object): for factory in inject_factories: try: return_value = factory(name, implementation) - except: + except Exception: self.logger.exception("Exception while executing injection factory %r" % factory) else: if return_value is not None: @@ -1360,9 +1459,9 @@ class PluginManager(object): def log_all_plugins(self, show_bundled=True, bundled_str=(" (bundled)", ""), show_location=True, - location_str=" = {location}", show_enabled=True, enabled_str=(" ", "!", "#"), + location_str=" = {location}", show_enabled=True, enabled_str=(" ", "!", "#", "*"), only_to_handler=None): - all_plugins = self.enabled_plugins.values() + self.disabled_plugins.values() + all_plugins = list(self.enabled_plugins.values()) + list(self.disabled_plugins.values()) def _log(message, level=logging.INFO): if only_to_handler is not None: @@ -1380,9 +1479,11 @@ class PluginManager(object): location_str=location_str, show_enabled=show_enabled, enabled_strs=enabled_str), - sorted(self.plugins.values(), key=lambda x: str(x).lower()))) - _log("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins), - plugins=formatted_plugins)) + sorted(self.plugins.values(), key=lambda x: unicode(x).lower()))) + legend = "Prefix legend: {1} = disabled, {2} = blacklisted, {3} = incompatible".format(*enabled_str) + _log("{count} plugin(s) registered with the system:\n{plugins}\n{legend}".format(count=len(all_plugins), + plugins=formatted_plugins, + legend=legend)) def get_plugin(self, identifier, require_enabled=True): """ @@ -1473,17 +1574,18 @@ class PluginManager(object): if sorting_context is not None and isinstance(impl[1], SortablePlugin): try: sorting_value = impl[1].get_sorting_key(sorting_context) - except: + except Exception: self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0])) if sorting_value is not None: try: - int(sorting_value) + sorting_value = int(sorting_value) except ValueError: - self.logger.warn("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context)) + self.logger.warning("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context)) sorting_value = None - return sorting_value is None, sorting_value, impl[0] + plugin_info = self.get_plugin_info(impl[0], require_enabled=False) + return sorting_value is None, sv(sorting_value), not plugin_info.bundled if plugin_info else True, sv(impl[0]) return [impl[1] for impl in sorted(result, key=sort_func)] @@ -1563,12 +1665,14 @@ class PluginManager(object): """ for client in self.registered_clients: - try: client(plugin, data, permissions=permissions) - except: self.logger.exception("Exception while sending plugin data to client") + try: + client(plugin, data, permissions=permissions) + except Exception: + self.logger.exception("Exception while sending plugin data to client") def _sort_hooks(self, hook): self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook], - key=lambda x: (x[0] is None, x[0], x[1], x[2])) + key=lambda x: (x[0] is None, sv(x[0]), sv(x[1]), sv(x[2]))) def _get_callback_and_order(self, hook): if callable(hook): @@ -1619,13 +1723,14 @@ def is_editable_install(install_dir, package, module, location): if os.path.isfile(package_link): expected_target = os.path.normcase(os.path.realpath(location)) try: - with open(package_link) as f: + with io.open(package_link, 'rt', encoding='utf-8') as f: contents = f.readlines() for line in contents: target = os.path.normcase(os.path.realpath(os.path.join(line.strip(), module))) if target == expected_target: return True - except: + except Exception: + raise # TODO really ignore this? pass return False @@ -1645,10 +1750,13 @@ class EntryPointMetadata(pkginfo.Distribution): for metadata_file in metadata_files: try: return self.entry_point.dist.get_metadata(metadata_file) - except: + except (IOError, OSError): + # file not found, metadata file might be missing, ignore + # IOError: file not found in Py2 + # OSError (specifically FileNotFoundError): file not found in Py3 pass - warnings.warn('No package metadata found for package: {}'.format(self.entry_point.module_name)) + warnings.warn('No package metadata found for package {}'.format(self.entry_point.module_name)) class Plugin(object): diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index b96a9af46..d625844ec 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1,4 +1,6 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals + """ This module bundles all of OctoPrint's supported plugin implementation types as well as their common parent class, :class:`OctoPrintPlugin`. @@ -16,8 +18,6 @@ Please note that the plugin implementation types are documented in the section """ -from __future__ import absolute_import, division, print_function - __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -25,9 +25,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from .core import (Plugin, RestartNeedingPlugin, SortablePlugin) -# noinspection PyCompatibility -from past.builtins import basestring - class OctoPrintPlugin(Plugin): """ The parent class of all OctoPrint plugin mixins. @@ -69,7 +66,7 @@ class OctoPrintPlugin(Plugin): .. attribute:: _app_session_manager - The :class:`~octoprint.users.SessionManager` instance. Injected by the plugin core system upon initialization of + The :class:`~octoprint.access.users.SessionManager` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _plugin_lifecycle_manager @@ -79,7 +76,7 @@ class OctoPrintPlugin(Plugin): .. attribute:: _user_manager - The :class:`~octoprint.users.UserManager` instance. Injected by the plugin core system upon initialization + The :class:`~octoprint.access.users.UserManager` instance. Injected by the plugin core system upon initialization of the implementation. .. attribute:: _connectivity_checker @@ -159,6 +156,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin): is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be externally reachable, use :func:`on_after_startup` instead or additionally. + .. warning:: + + Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. + The relevant sorting context is ``StartupPlugin.on_startup``. :param string host: the host the server will listen on, may be ``0.0.0.0`` @@ -171,6 +172,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin): """ Called just after launch of the server, so when the listen loop is actually running already. + .. warning:: + + Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. + The relevant sorting context is ``StartupPlugin.on_after_startup``. """ @@ -191,6 +196,10 @@ class ShutdownPlugin(OctoPrintPlugin, SortablePlugin): """ Called upon the imminent shutdown of OctoPrint. + .. warning:: + + Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. + The relevant sorting context is ``ShutdownPlugin.on_shutdown``. """ pass @@ -225,6 +234,8 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin): js JavaScript files, such as additional view models + jsclient + JavaScript files containing additional parts for the JS Client Library (since 1.3.10) css CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode. less @@ -239,6 +250,7 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin): def get_assets(self): return dict( js=['js/my_file.js', 'js/my_other_file.js'], + clientjs=['clientjs/my_file.js'], css=['css/my_styles.css'], less=['less/my_styles.less'] ) @@ -782,7 +794,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): def get_ui_custom_etag(self): """ Allows to use a custom way to calculate the ETag, instead of the default method (hashing - OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value). + OctoPrint's version, tracked file paths and ``LastModified`` value). Returns: str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default). @@ -1379,8 +1391,9 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): # noinspection PyMethodMayBeStatic def is_blueprint_protected(self): """ - Whether a valid API key is needed to access the blueprint (the default) or not. Note that this only restricts - access to the blueprint's dynamic methods, static files are always accessible without API key. + Whether a login session is needed to access the blueprint if the forcelogin plugin is enabled or not. Requiring + a session is the default. Note that this only restricts access to the blueprint's dynamic methods, static files + are always accessible. """ return True @@ -1483,7 +1496,7 @@ class SettingsPlugin(OctoPrintPlugin): """ from flask_login import current_user import copy - + from octoprint.access.permissions import Permissions data = copy.deepcopy(self._settings.get_all_data(merged=True)) @@ -1801,6 +1814,10 @@ class EventHandlerPlugin(OctoPrintPlugin): """ Called by OctoPrint upon processing of a fired event on the platform. + .. warning:: + + Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server. + Arguments: event (str): The type of event that got fired, see :ref:`the list of events ` for possible values @@ -1839,8 +1856,9 @@ class SlicerPlugin(OctoPrintPlugin): The human readable name of the slicer. This will be displayed to the user during slicer selection. same_device True if the slicer runs on the same device as OctoPrint, False otherwise. Slicers running on the same - device will not be allowed to slice while a print is running due to performance reasons. Slice requests - against slicers running on the same device will result in an error. + device will not be allowed to slice on systems with less than two CPU cores (or an unknown number) while a + print is running due to performance reasons. Slice requests against slicers running on the same device and + less than two cores will result in an error. progress_report ``True`` if the slicer can report back slicing progress to OctoPrint ``False`` otherwise. source_file_types @@ -1863,6 +1881,21 @@ class SlicerPlugin(OctoPrintPlugin): destination_extensions=["gco", "gcode", "g"] ) + # noinspection PyMethodMayBeStatic + def get_slicer_extension_tree(self): + """ + Fetch additional entries to put into the extension tree for accepted files + + By default, a subtree for ``model`` files with ``stl`` extension is returned. Slicers who want to support + additional/other file types will want to override this. + + For the extension tree format, take a look at the docs of the :ref:`octoprint.filemanager.extension_tree hook `. + + Returns: (dict) a dictionary containing a valid extension subtree. + """ + from octoprint.filemanager import ContentTypeMapping + return dict(model=dict(stl=ContentTypeMapping(["stl"], "application/sla"))) + def get_slicer_profiles(self, profile_path): """ Fetch all :class:`~octoprint.slicing.SlicingProfile` stored for this slicer. @@ -2045,20 +2078,3 @@ class ProgressPlugin(OctoPrintPlugin): :param int progress: Current progress as a value between 0 and 100 """ pass - - -class AppPlugin(OctoPrintPlugin): - """ - Using the :class:`AppPlugin mixin` plugins may register additional :ref:`App session key providers ` - within the system. - - .. deprecated:: 1.2.0 - - Refer to the :ref:`octoprint.accesscontrol.appkey hook ` instead. - - """ - - # noinspection PyMethodMayBeStatic - def get_additional_apps(self): - return [] - diff --git a/src/octoprint/plugins/__init__.py b/src/octoprint/plugins/__init__.py index 1b0510c60..092cd3e34 100644 --- a/src/octoprint/plugins/__init__.py +++ b/src/octoprint/plugins/__init__.py @@ -1 +1,2 @@ -# make our plugins testable +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 62862c815..73ea2f77a 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -1,4 +1,4 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -9,6 +9,7 @@ import octoprint.plugin from octoprint.server import user_permission from octoprint.access import USER_GROUP from octoprint.access.permissions import Permissions +from octoprint.events import Events import flask from flask_babel import gettext @@ -36,17 +37,28 @@ class Prompt(object): class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, + octoprint.plugin.EventHandlerPlugin, octoprint.plugin.SettingsPlugin, octoprint.plugin.SimpleApiPlugin, octoprint.plugin.TemplatePlugin): + COMMAND = "M876" + CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT" + # noinspection PyMissingConstructor def __init__(self): self._prompt = None - self._selection_command = None + self._enable = "detected" + self._command = None + self._enable_emergency_sending = False + self._enable_signal_support = False + self._cap_prompt_support = False def initialize(self): - self._selection_command = self._settings.get([b"selection_command"]) + self._enable = self._settings.get(["enable"]) + self._command = self._settings.get(["command"]) + self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"]) + self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"]) # Additional permissions hook @@ -62,16 +74,31 @@ 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"]) + + #~ EventHandlerPlugin + + def on_event(self, event, payload): + if event == Events.CONNECTED and self._enable == "always" and self._enable_signal_support: + self._printer.commands(["{command} P1".format(command=self._command)]) + elif event == Events.DISCONNECTED: + self._close_prompt() #~ SettingsPlugin def get_settings_defaults(self): - return dict(selection_command=None) + return dict(enable="detected", + command=self.COMMAND, + enable_emergency_sending=True, + enable_signal_support=True) def on_settings_save(self, data): octoprint.plugin.SettingsPlugin.on_settings_save(self, data) - self._selection_command = self._settings.get([b"selection_command"]) + self._enable = self._settings.get(["enable"]) + self._command = self._settings.get(["command"]) + self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"]) + self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"]) #~ SimpleApiPlugin @@ -108,73 +135,108 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, #~ action command handler def action_command_handler(self, comm, line, action, *args, **kwargs): - if not action.startswith(b"prompt_"): - return - - if self._selection_command is None: - self._logger.info("Got a prompt command from the printer but no selection command is defined") + if not action.startswith("prompt_"): return parts = action.split(None, 1) if len(parts) == 1: action = parts[0] - parameter = b"" + parameter = "" else: action, parameter = parts - if action == b"prompt_begin": + if action == "prompt_begin": if self._prompt is not None and self._prompt.active: - self._logger.warn("Prompt is already defined") + self._logger.warning("Prompt is already defined") return self._prompt = Prompt(parameter.strip()) - elif action == b"prompt_choice" or action == b"prompt_button": + elif action == "prompt_choice" or action == "prompt_button": if self._prompt is None: return if self._prompt.active: - self._logger.warn("Prompt is already active") + self._logger.warning("Prompt is already active") return self._prompt.add_choice(parameter.strip()) - elif action == b"prompt_show": + elif action == "prompt_show": if self._prompt is None: return if self._prompt.active: - self._logger.warn("Prompt is already active") + self._logger.warning("Prompt is already active") return self._show_prompt() - elif action == b"prompt_end": + elif action == "prompt_end": if self._prompt is None: return self._close_prompt() self._prompt = None + #~ queuing handling + + def gcode_queuing_handler(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs): + if gcode != self._command: + return + + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support) or not self._enable_emergency_sending: + return + + if not "S" in cmd: + # we only force-send M876 Sx + return + + # noinspection PyProtectedMember + return comm_instance._emergency_force_send(cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode) + + #~ capability reporting + + def firmware_capability_handler(self, comm_instance, capability, enabled, already_defined, *args, **kwargs): + if capability == self.CAP_PROMPT_SUPPORT and enabled: + self._cap_prompt_support = True + if self._enable == "detected" and self._enable_signal_support: + self._printer.commands(["{command} P1".format(command=self._command)]) + #~ prompt handling def _show_prompt(self): + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): + return + self._prompt.activate() self._plugin_manager.send_plugin_message(self._identifier, dict(action="show", text=self._prompt.text, choices=self._prompt.choices)) def _close_prompt(self): + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): + return + self._prompt = None self._plugin_manager.send_plugin_message(self._identifier, dict(action="close")) def _answer_prompt(self, choice): + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): + return + self._close_prompt() - self._printer.commands([self._selection_command.format(choice=choice)]) + if "{choice}" in self._command: + self._printer.commands([self._command.format(choice=choice)]) + else: + self._printer.commands(["{command} S{choice}".format(command=self._command, + choice=choice)]) __plugin_name__ = "Action Command Prompt Support" __plugin_description__ = "Allows your printer to trigger prompts via action commands on the connection" __plugin_author__ = "Gina Häußge" __plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger" - "confirmation or selection prompts in OctoPrint") + " confirmation or selection prompts in OctoPrint") __plugin_license__ = "AGPLv3" __plugin_implementation__ = ActionCommandPromptPlugin() __plugin_hooks__ = { - b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, - b"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions + "octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, + "octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler, + "octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions } diff --git a/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js b/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js new file mode 100644 index 000000000..9ba9b4a14 --- /dev/null +++ b/src/octoprint/plugins/action_command_prompt/static/clientjs/action_command_prompt.js @@ -0,0 +1,25 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintActionCommandPromptClient = function(base) { + this.base = base; + }; + + OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) { + return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts); + }; + + OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) { + var data = { + choice: choice + }; + return this.base.simpleApiCommand("action_command_prompt", "select", data, opts); + }; + + OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient); + return OctoPrintActionCommandPromptClient; +}); diff --git a/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js index e5f8c1244..c35faf7e6 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; @@ -31,7 +5,17 @@ $(function() { self.loginState = parameters[0]; self.access = parameters[1]; - self._modal = undefined; + self.modal = ko.observable(undefined); + + self.text = ko.observable(); + self.buttons = ko.observableArray([]); + + self.active = ko.pureComputed(function() { + return self.text() !== undefined; + }); + self.visible = ko.pureComputed(function() { + return self.modal() !== undefined; + }); self.requestData = function() { if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return; @@ -42,26 +26,35 @@ $(function() { self.fromResponse = function(data) { if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) { - self._showPrompt(data.text, data.choices); + self.text(data.text); + self.buttons(data.choices); + self.showPrompt(); + } else { + self.text(undefined); + self.buttons([]); } }; - self._showPrompt = function(text, buttons) { + self.showPrompt = function() { + var text = self.text(); + var buttons = self.buttons(); + var opts = { title: gettext("Message from your printer"), message: text, selections: buttons, + maycancel: true, // see #3171 onselect: function(index) { if (index > -1) { self._select(index); } }, onclose: function() { - self._modal = undefined; + self.modal(undefined); } }; - self._modal = showSelectionDialog(opts) + self.modal(showSelectionDialog(opts)); }; self._select = function(index) { @@ -69,8 +62,9 @@ $(function() { }; self._closePrompt = function() { - if (self._modal) { - self._modal.modal("hide"); + var modal = self.modal(); + if (modal) { + modal.modal("hide"); } }; @@ -86,10 +80,14 @@ $(function() { switch (data.action) { case "show": { - self._showPrompt(data.text, data.choices); + self.text(data.text); + self.buttons(data.choices); + self.showPrompt(); break; } case "close": { + self.text(undefined); + self.buttons([]); self._closePrompt(); break; } @@ -100,6 +98,7 @@ $(function() { OCTOPRINT_VIEWMODELS.push({ construct: ActionCommandPromptViewModel, - dependencies: ["loginStateViewModel", "accessViewModel"] + dependencies: ["loginStateViewModel", "accessViewModel"], + elements: ["#navbar_plugin_action_command_prompt"] }); }); diff --git a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 new file mode 100644 index 000000000..31e2a266e --- /dev/null +++ b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 @@ -0,0 +1,3 @@ + diff --git a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 index a30e7f9b8..df45ff760 100644 --- a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 +++ b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 @@ -2,10 +2,43 @@
- +
- -
{{ _('Use this to define the command to tell the printer about the selection. OctoPrint will replace {choice} with the index of the selected choice. E.g. M876 S{choice} will become M123 S1') }}
+ + + +
+
+
+ +
+
+ +
+ +
{{ _('Use this to define the dialog command. Default is M876. You normally should not have to change this.') }}
+
+
+
+
+ +
+
+
+
+ +
+
diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index a4f2815b2..ad13b95be 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -9,20 +9,23 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms import octoprint.plugin import calendar -import codecs +import io import os import re import time import threading +import sys +PY2 = sys.version_info[0] < 3 import feedparser import flask from collections import OrderedDict +from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions -from octoprint.server.util.flask import require_firstrun, with_revalidation_checking, check_etag -from octoprint.util import utmify +from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag +from octoprint.util import utmify, count, monotonic_time from flask_babel import gettext from octoprint import __version__ as OCTOPRINT_VERSION @@ -50,11 +53,13 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, dict(key="READ", name="Read announcements", description=gettext("Allows to read announcements"), + default_groups=[ADMIN_GROUP], roles=["read"]), dict(key="MANAGE", name="Manage announcement subscriptions", description=gettext("Allows to manage announcement subscriptions. Includes \"Read announcements\" " "permission"), + default_groups=[ADMIN_GROUP], roles=["manage"], permissions=["PLUGIN_ANNOUNCEMENTS_READ"]) ] @@ -104,7 +109,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, ttl=6*60, display_limit=3, summary_limit=300) - settings["enabled_channels"] = settings["channels"].keys() + settings["enabled_channels"] = list(settings["channels"].keys()) return settings def get_settings_version(self): @@ -150,7 +155,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, # Blueprint Plugin @octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403) def get_channel_data(self): from octoprint.settings import valid_boolean_trues @@ -170,7 +175,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, for key, data in channel_configs.items(): read_until = channel_configs[key].get("read_until", None) entries = sorted(self._to_internal_feed(channel_data.get(key, []), read_until=read_until), key=lambda e: e["published"], reverse=True) - unread = len(list(filter(lambda e: not e["read"], entries))) + unread = count(filter(lambda e: not e["read"], entries)) if read_until is None and entries: last = entries[0]["published"] @@ -191,14 +196,16 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, def etag(): import hashlib hash = hashlib.sha1() - hash.update(repr(sorted(enabled))) - hash.update(repr(sorted(forced))) - hash.update(OCTOPRINT_VERSION) + def hash_update(value): + hash.update(value.encode("utf-8")) + hash_update(repr(sorted(enabled))) + hash_update(repr(sorted(forced))) + hash_update(OCTOPRINT_VERSION) for channel in sorted(channel_configs.keys()): - hash.update(repr(channel_configs[channel])) + hash_update(repr(channel_configs[channel])) channel_data = self._get_channel_data_from_cache(channel, channel_configs[channel]) - hash.update(repr(channel_data)) + hash_update(repr(channel_data)) return hash.hexdigest() @@ -211,7 +218,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, unless=lambda: force)(view)() @octoprint.plugin.BlueprintPlugin.route("/channels/", methods=["POST"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403) def channel_command(self, channel): from octoprint.server.util.flask import get_json_command_from_request @@ -358,7 +365,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, now = time.time() if os.stat(channel_path).st_mtime + ttl > now: d = feedparser.parse(channel_path) - self._logger.debug(u"Loaded channel {} from cache at {}".format(key, channel_path)) + self._logger.debug("Loaded channel {} from cache at {}".format(key, channel_path)) return d return None @@ -370,18 +377,18 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, url = config["url"] try: - start = time.time() + start = monotonic_time() r = requests.get(url, timeout=30) r.raise_for_status() - self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start)) - except Exception as e: + self._logger.info("Loaded channel {} from {} in {:.2}s".format(key, config["url"], monotonic_time() - start)) + except Exception: self._logger.exception( - u"Could not fetch channel {} from {}: {}".format(key, config["url"], str(e))) + "Could not fetch channel {} from {}".format(key, config["url"])) return None response = r.text channel_path = self._get_channel_cache_path(key) - with codecs.open(channel_path, mode="w", encoding="utf-8") as f: + with io.open(channel_path, mode="wt", encoding="utf-8") as f: f.write(response) return feedparser.parse(response) @@ -391,15 +398,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, result = [] if "entries" in feed: for entry in feed["entries"]: - internal_entry = self._to_internal_entry(entry, read_until=read_until) - if internal_entry: - result.append(internal_entry) + try: + internal_entry = self._to_internal_entry(entry, read_until=read_until) + if internal_entry: + result.append(internal_entry) + except Exception: + self._logger.exception("Error while converting entry from feed, skipping it") return result def _to_internal_entry(self, entry, read_until=None): """Convert feed entries to internal data structure.""" - published = calendar.timegm(entry["published_parsed"]) + timestamp = entry.get("published_parsed", None) + if timestamp is None: + timestamp = entry.get("updated_parsed", None) + if timestamp is None: + return None + + published = calendar.timegm(timestamp) read = True if read_until is not None: @@ -423,22 +439,22 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, _image_tag_re = re.compile(r'') def _strip_images(text): """ - >>> _strip_images(u"I'm a link and this is an image: foo") - u"I'm a link and this is an image: " - >>> _strip_images(u"One and two and three and four \\"four\\"") - u'One and two and three and four ' - >>> _strip_images(u"No images here") - u'No images here' + >>> _strip_images("I'm a link and this is an image: foo") # doctest: +ALLOW_UNICODE + "I'm a link and this is an image: " + >>> _strip_images("One and two and three and four \\"four\\"") # doctest: +ALLOW_UNICODE + 'One and two and three and four ' + >>> _strip_images("No images here") # doctest: +ALLOW_UNICODE + 'No images here' """ return _image_tag_re.sub('', text) def _replace_images(text, callback): """ >>> callback = lambda img: "foobar" - >>> _replace_images(u"I'm a link and this is an image: foo", callback) - u"I'm a link and this is an image: foobar" - >>> _replace_images(u"One and two and three and four \\"four\\"", callback) - u'One foobar and two foobar and three foobar and four foobar' + >>> _replace_images("I'm a link and this is an image: foo", callback) # doctest: +ALLOW_UNICODE + "I'm a link and this is an image: foobar" + >>> _replace_images("One and two and three and four \\"four\\"", callback) # doctest: +ALLOW_UNICODE + 'One foobar and two foobar and three foobar and four foobar' """ result = text for match in _image_tag_re.finditer(text): @@ -450,14 +466,14 @@ def _replace_images(text, callback): _image_src_re = re.compile(r'src=(?P[\'"]*)(?P.*?)(?P=quote)(?=\s+|>)') def _lazy_images(text, placeholder=None): """ - >>> _lazy_images(u"I'm a link and this is an image: foo") - u'I\\'m a link and this is an image: \\'foo\\'' - >>> _lazy_images(u"I'm a link and this is an image: foo", placeholder="ph.png") - u'I\\'m a link and this is an image: \\'foo\\'' - >>> _lazy_images(u"One and two and three and four \\"four\\"", placeholder="ph.png") - u'One and two and three and four four' - >>> _lazy_images(u"No images here") - u'No images here' + >>> _lazy_images("I'm a link and this is an image: foo") # doctest: +ALLOW_UNICODE + 'I\\'m a link and this is an image: \\'foo\\'' + >>> _lazy_images("I'm a link and this is an image: foo", placeholder="ph.png") # doctest: +ALLOW_UNICODE + 'I\\'m a link and this is an image: \\'foo\\'' + >>> _lazy_images("One and two and three and four \\"four\\"", placeholder="ph.png") # doctest: +ALLOW_UNICODE + 'One and two and three and four four' + >>> _lazy_images("No images here") # doctest: +ALLOW_UNICODE + 'No images here' """ if placeholder is None: # 1px transparent gif @@ -476,10 +492,10 @@ def _lazy_images(text, placeholder=None): def _strip_tags(text): """ - >>> _strip_tags(u"Hello world<img src='foo.jpg'>") - u"Hello world<img src='foo.jpg'>" - >>> _strip_tags(u"> > Foo") - u'> > Foo' + >>> _strip_tags("Hello world<img src='foo.jpg'>") # doctest: +ALLOW_UNICODE + "Hello world<img src='foo.jpg'>" + >>> _strip_tags("> > Foo") # doctest: +ALLOW_UNICODE + '> > Foo' """ try: # noinspection PyCompatibility @@ -490,8 +506,8 @@ def _strip_tags(text): class TagStripper(HTMLParser): - def __init__(self): - HTMLParser.__init__(self) + def __init__(self, **kw): + HTMLParser.__init__(self, **kw) self._fed = [] def handle_data(self, data): @@ -506,7 +522,7 @@ def _strip_tags(text): def get_data(self): return "".join(self._fed) - tag_stripper = TagStripper() + tag_stripper = TagStripper() if PY2 else TagStripper(convert_charrefs=False) tag_stripper.feed(text) return tag_stripper.get_data() diff --git a/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 b/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 index 933cc5521..7f936f0da 100644 --- a/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 +++ b/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 @@ -1,3 +1,3 @@ - + diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py new file mode 100644 index 000000000..9bb3c70df --- /dev/null +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -0,0 +1,445 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, unicode_literals + +import flask +import threading +import os +import yaml +import io +import time +from binascii import hexlify +from collections import defaultdict +from flask_babel import gettext + +import octoprint.plugin +from octoprint.settings import valid_boolean_trues +from octoprint.server.util.flask import restricted_access, no_firstrun_access +from octoprint.server import NO_CONTENT, current_user, admin_permission +from octoprint.util import atomic_write, monotonic_time, ResettableTimer + +from octoprint.access import ADMIN_GROUP +from octoprint.access.permissions import Permissions + + +CUTOFF_TIME = 10 * 60 # 10min +POLL_TIMEOUT = 5 # 5 seconds + +class AppAlreadyExists(Exception): + pass + + +class PendingDecision(object): + def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None): + self.app_id = app_id + self.app_token = app_token + self.user_id = user_id + self.user_token = user_token + self.created = monotonic_time() + + if callable(timeout_callback): + self.poll_timeout = ResettableTimer(POLL_TIMEOUT, timeout_callback, [user_token]) + self.poll_timeout.start() + + def external(self): + return dict(app_id=self.app_id, + user_id=self.user_id, + user_token=self.user_token) + + def __repr__(self): + return u"PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(self.app_id, + self.app_token, + self.user_id, + 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) + + def __repr__(self): + return u"ReadyDecision({!r}, {!r}, {!r})".format(self.app_id, + self.app_token, + self.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) + + def __repr__(self): + return u"ActiveKey({!r}, {!r}, {!r})".format(self.app_id, + self.api_key, + self.user_id) + + +class AppKeysPlugin(octoprint.plugin.AssetPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin): + + def __init__(self): + self._pending_decisions = [] + self._pending_lock = threading.RLock() + + self._ready_decisions = [] + self._ready_lock = threading.RLock() + + self._keys = defaultdict(list) + self._keys_lock = threading.RLock() + + self._key_path = None + + def initialize(self): + self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml") + self._load_keys() + + # Additional permissions hook + + def get_additional_permissions(self): + return [ + dict(key="ADMIN", + name="Admin access", + description=gettext("Allows administrating all application keys"), + roles=["admin"], + dangerous=True, + default_groups=[ADMIN_GROUP]) + ] + + ##~~ TemplatePlugin + + def get_template_configs(self): + return [dict(type="usersettings", name=gettext("Application Keys")), + dict(type="settings", name=gettext("Application Keys"))] + + ##~~ AssetPlugin + + def get_assets(self): + return dict(js=["js/appkeys.js"], + clientjs=["clientjs/appkeys.js"], + less=["less/appkeys.less"], + css=["css/appkeys.css"]) + + ##~~ BlueprintPlugin mixin + + @octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"]) + @no_firstrun_access + def handle_probe(self): + return NO_CONTENT + + @octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"]) + @no_firstrun_access + def handle_request(self): + data = flask.request.json + if data is None: + return flask.make_response("Missing key request", 400) + + 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 and data["user"]: + user_id = data["user"] + + app_token, user_token = self._add_pending_decision(app_name, user_id=user_id) + + self._plugin_manager.send_plugin_message(self._identifier, dict(type="request_access", + app_name=app_name, + user_token=user_token, + user_id=user_id)) + response = flask.jsonify(app_token=app_token) + response.status_code = 201 + response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True) + return response + + @octoprint.plugin.BlueprintPlugin.route("/request/") + @no_firstrun_access + def handle_decision_poll(self, app_token): + result = self._get_pending_by_app_token(app_token) + if result: + for pending_decision in result: + pending_decision.poll_timeout.reset() + + response = flask.jsonify(message="Awaiting decision") + response.status_code = 202 + return response + + result = self._get_decision(app_token) + if result: + return flask.jsonify(api_key=result) + + return flask.abort(404) + + @octoprint.plugin.BlueprintPlugin.route("/decision/", methods=["POST"]) + @restricted_access + def handle_decision(self, user_token): + data = flask.request.json + if not "decision" in data: + return flask.make_response("No decision provided", 400) + decision = data["decision"] in valid_boolean_trues + user_id = current_user.get_name() + + result = self._set_decision(user_token, decision, user_id) + if not result: + return flask.abort(404) + + # Close access_request dialog for this request on all open OctoPrint connections + self._plugin_manager.send_plugin_message(self._identifier, dict( + type="end_request", + user_token=user_token + )) + + return NO_CONTENT + + def is_blueprint_protected(self): + return False # No API key required to request API access + + ##~~ SimpleApiPlugin mixin + + def get_api_commands(self): + return dict(generate=["app"], + revoke=["key"]) + + def on_api_get(self, request): + user_id = current_user.get_name() + if not user_id: + return flask.abort(403) + + if request.values.get("all") in valid_boolean_trues and Permissions.PLUGIN_APPKEYS_ADMIN.can(): + keys = self._all_api_keys() + else: + keys = self._api_keys_for_user(user_id) + + return flask.jsonify(keys=list(map(lambda x: x.external(), keys)), + pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id))) + + def on_api_command(self, command, data): + user_id = current_user.get_name() + if not user_id: + return flask.abort(403) + + if command == "revoke": + api_key = data.get("key") + if not api_key: + return flask.abort(400) + + if not admin_permission.can(): + user_for_key = self._user_for_api_key(api_key) + if user_for_key is None or user_for_key.user_id != user_id: + return flask.abort(403) + + self._delete_api_key(api_key) + + elif command == "generate": + # manual generateKey + app_name = data.get("app") + if not app_name: + return flask.abort(400) + + self._add_api_key(user_id, app_name.strip()) + + return NO_CONTENT + + ##~~ key validator hook + + def validate_api_key(self, api_key, *args, **kwargs): + return self._user_for_api_key(api_key) + + ##~~ Helpers + + def _add_pending_decision(self, app_name, user_id=None): + app_token = self._generate_key() + user_token = self._generate_key() + + with self._pending_lock: + self._remove_stale_pending() + self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token, + timeout_callback=self._expire_pending)) + + return app_token, user_token + + def _get_pending_by_app_token(self, app_token): + result = [] + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.app_token == app_token: + result.append(data) + return result + + def _get_pending_by_user_id(self, user_id): + result = [] + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.user_id == user_id or data.user_id is None: + result.append(data) + return result + + def _expire_pending(self, user_token): + with self._pending_lock: + len_before = len(self._pending_decisions) + self._pending_decisions = list(filter(lambda x: x.user_token != user_token, + self._pending_decisions)) + len_after = len(self._pending_decisions) + + if len_after < len_before: + self._plugin_manager.send_plugin_message(self._identifier, dict( + type="end_request", + user_token=user_token + )) + + def _remove_stale_pending(self): + with self._pending_lock: + cutoff = monotonic_time() - CUTOFF_TIME + len_before = len(self._pending_decisions) + self._pending_decisions = list(filter(lambda x: x.created >= cutoff, + self._pending_decisions)) + len_after = len(self._pending_decisions) + if len_after < len_before: + self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after)) + + def _set_decision(self, user_token, decision, user_id): + with self._pending_lock: + self._remove_stale_pending() + for data in self._pending_decisions: + if data.user_token == user_token and (data.user_id == user_id or data.user_id is None): + pending = data + break + else: + return False # not found + + if decision: + with self._ready_lock: + self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id)) + + with self._pending_lock: + self._pending_decisions = list(filter(lambda x: x.user_token != user_token, + self._pending_decisions)) + + return True + + def _get_decision(self, app_token): + self._remove_stale_pending() + + with self._ready_lock: + for data in self._ready_decisions: + if data.app_token == app_token: + decision = data + break + else: + return False # not found + + api_key = self._add_api_key(decision.user_id, decision.app_id) + + with self._ready_lock: + self._ready_decisions = list(filter(lambda x: x.app_token != app_token, + self._ready_decisions)) + + return api_key + + def _add_api_key(self, user_id, app_name): + with self._keys_lock: + for key in self._keys[user_id]: + if key.app_id.lower() == app_name.lower(): + return key.api_key + + key = ActiveKey(app_name, self._generate_key(), user_id) + self._keys[user_id].append(key) + self._save_keys() + return key.api_key + + def _delete_api_key(self, api_key): + with self._keys_lock: + for user_id, data in self._keys.items(): + self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data)) + self._save_keys() + + def _user_for_api_key(self, api_key): + with self._keys_lock: + for user_id, data in self._keys.items(): + if any(filter(lambda x: x.api_key == api_key, data)): + if self._user_manager.enabled: + return self._user_manager.findUser(userid=user_id) + elif user_id == "_admin" or user_id == "dummy": + # dummy = backwards compatible + return self._user_manager.anonymous_user_factory() + return None + + def _api_keys_for_user(self, user_id): + with self._keys_lock: + return self._keys[user_id] + + def _all_api_keys(self): + with self._keys_lock: + result = [] + for user_id, keys in self._keys.items(): + result += keys + return result + + def _generate_key(self): + return hexlify(os.urandom(16)) + + def _load_keys(self): + with self._keys_lock: + if not os.path.exists(self._key_path): + return + + try: + with io.open(self._key_path, 'rt', encoding="utf-8", errors="strict") as f: + persisted = yaml.safe_load(f) + except Exception: + self._logger.exception("Could not load application keys from {}".format(self._key_path)) + return + + if not isinstance(persisted, dict): + return + + keys = defaultdict(list) + for user_id, persisted_keys in persisted.items(): + keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys] + self._keys = keys + + def _save_keys(self): + with self._keys_lock: + to_persist = dict() + for user_id, keys in self._keys.items(): + to_persist[user_id] = [x.internal() for x in keys] + + try: + with atomic_write(self._key_path, mode='wt') as f: + yaml.safe_dump(to_persist, f, allow_unicode=True) + except Exception: + self._logger.exception("Could not write application keys to {}".format(self._key_path)) + +__plugin_name__ = "Application Keys Plugin" +__plugin_description__ = "Implements a workflow for third party clients to obtain API keys" +__plugin_author__ = "Gina Häußge, Aldo Hoeben" +__plugin_disabling_discouraged__ = gettext("Without this plugin third party clients will no longer be able to " + "obtain an API key without you manually copy-pasting it.") +__plugin_implementation__ = AppKeysPlugin() +__plugin_hooks__ = { + "octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key, + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions +} diff --git a/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js new file mode 100644 index 000000000..9b29428aa --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/clientjs/appkeys.js @@ -0,0 +1,98 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintAppKeysClient = function(base) { + this.base = base; + }; + + OctoPrintAppKeysClient.prototype.getKeys = function(opts) { + return this.base.simpleApiGet("appkeys", opts); + }; + + OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) { + return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts); + }; + + OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) { + return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts); + }; + + OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) { + return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts); + }; + + OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) { + return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts); + }; + + OctoPrintAppKeysClient.prototype.probe = function(opts) { + return this.base.get(this.base.getBlueprintUrl("appkeys") + "probe", opts); + }; + + OctoPrintAppKeysClient.prototype.request = function(app, opts) { + return this.requestForUser(app, undefined, opts); + }; + + OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) { + return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts); + }; + + OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) { + return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts); + }; + + OctoPrintAppKeysClient.prototype.authenticate = function(app, user) { + var deferred = $.Deferred(); + var client = this; + + client.probe() + .done(function() { + client.requestForUser(app, user) + .done(function(response) { + var token = response.app_token; + if (!token) { + // no token received, something went wrong + deferred.reject(); + return; + } + + var interval = 1000; + var poll = function() { + client.checkDecision(token) + .done(function(response) { + if (response.api_key) { + // got a decision, resolve the promise + deferred.resolve(response.api_key); + } else { + // no decision yet, poll a bit more + deferred.notify(); + window.setTimeout(poll, interval); + } + }) + .fail(function() { + // something went wrong + deferred.reject(); + }); + }; + window.setTimeout(poll, interval); + }) + .fail(function() { + // something went wrong + deferred.reject(); + }); + }) + .fail(function() { + // workflow unsupported + deferred.reject(); + }); + + return deferred.promise(); + }; + + OctoPrintClient.registerPluginComponent("appkeys", OctoPrintAppKeysClient); + return OctoPrintAppKeysClient; +}); diff --git a/src/octoprint/plugins/appkeys/static/css/appkeys.css b/src/octoprint/plugins/appkeys/static/css/appkeys.css new file mode 100644 index 000000000..6240d21d7 --- /dev/null +++ b/src/octoprint/plugins/appkeys/static/css/appkeys.css @@ -0,0 +1 @@ +#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a{color:#000}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox],#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox]{margin-top:0} \ No newline at end of file diff --git a/src/octoprint/plugins/appkeys/static/js/appkeys.js b/src/octoprint/plugins/appkeys/static/js/appkeys.js new file mode 100644 index 000000000..bb5fdc822 --- /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: _.escape(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: _.escape(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: _.escape(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: _.escape(key)}), true); + }) + .fail(function(jqXHR) { + var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: _.escape(key)}); + var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: _.escape(key), error: _.escape(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..6da481c60 --- /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..1bfeaf07f --- /dev/null +++ b/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 @@ -0,0 +1,49 @@ +{{ _('Registered application keys') }} + +
+

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

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

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

{{ _('Existing backups') }}

+ +
+

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

+
+
+

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

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

{{ _('Create backup') }}

+ +

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

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

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

+ +

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

+ +
+
+ +
+
+ + {{ _('Browse...') }} + + + +
+
+
+ +
+
+ +
+
+
+
+ +
+ {{ _('Please note that the operating system that this OctoPrint server is running on does not support automatically restoring backups. You will have to restore your backups manually for now.', url='https://faq.octoprint.org/manual-restore') }} +
+ + diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index 2b817d541..64047f5ff 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/src/octoprint/plugins/corewizard/static/js/corewizard.js b/src/octoprint/plugins/corewizard/static/js/corewizard.js index 1c8f41b7d..5f3dfa7d0 100644 --- a/src/octoprint/plugins/corewizard/static/js/corewizard.js +++ b/src/octoprint/plugins/corewizard/static/js/corewizard.js @@ -170,10 +170,6 @@ $(function() { return false; }; - self.onWizardPreventSettingsRefreshDialog = function() { - return self.active; - }; - self.onWizardDetails = function(response) { self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.onlinecheck && response.corewizard.details.onlinecheck.required; }; @@ -252,10 +248,6 @@ $(function() { return false; }; - self.onWizardPreventSettingsRefreshDialog = function() { - return self.active; - }; - self.onWizardDetails = function(response) { self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.pluginblacklist && response.corewizard.details.pluginblacklist.required; }; diff --git a/src/octoprint/plugins/corewizard/subwizards.py b/src/octoprint/plugins/corewizard/subwizards.py index 85479d039..0fee431c7 100644 --- a/src/octoprint/plugins/corewizard/subwizards.py +++ b/src/octoprint/plugins/corewizard/subwizards.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -10,7 +10,7 @@ import sys import inspect from flask_babel import gettext from octoprint.access import ADMIN_GROUP, USER_GROUP - +from octoprint.util import to_native_str # noinspection PyUnresolvedReferences,PyMethodMayBeStatic class ServerCommandsSubwizard(object): @@ -56,7 +56,7 @@ class AclSubwizard(object): return True def _is_acl_wizard_required(self): - return self._user_manager.enabled and not self._user_manager.hasBeenCustomized() + return self._user_manager.enabled and not self._user_manager.has_been_customized() def _get_acl_wizard_details(self): return dict(required=self._is_acl_wizard_required()) @@ -72,7 +72,7 @@ class AclSubwizard(object): from flask import request, abort from octoprint.server.api import valid_boolean_trues, NO_CONTENT - if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.hasBeenCustomized(): + if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.has_been_customized(): abort(404) data = request.get_json() @@ -80,20 +80,16 @@ class AclSubwizard(object): data = request.values if "ac" in data and data["ac"] in valid_boolean_trues and \ - "user" in data.keys() and "pass1" in data.keys() and \ - "pass2" in data.keys() and data["pass1"] == data["pass2"]: + "user" in data and "pass1" in data and \ + "pass2" in data and data["pass1"] == data["pass2"]: # configure access control self._settings.global_set_boolean(["accessControl", "enabled"], True) self._user_manager.enable() self._user_manager.add_user(data["user"], data["pass1"], True, [], [USER_GROUP, ADMIN_GROUP], overwrite=True) - elif "ac" in data.keys() and not data["ac"] in valid_boolean_trues: + elif "ac" in data and not data["ac"] in valid_boolean_trues: # disable access control self._settings.global_set_boolean(["accessControl", "enabled"], False) - - octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser - octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader) - self._user_manager.disable() self._settings.save() return NO_CONTENT @@ -150,7 +146,7 @@ class PrinterProfileSubwizard(object): return gettext("Default Printer Profile") -Subwizards = type("Subwizwards", +Subwizards = type(to_native_str("Subwizards"), tuple(cls for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass) if clsname.endswith("Subwizard")), dict()) diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_acl_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_acl_wizard.jinja2 index 58cd4bfa7..823e65212 100644 --- a/src/octoprint/plugins/corewizard/templates/corewizard_acl_wizard.jinja2 +++ b/src/octoprint/plugins/corewizard/templates/corewizard_acl_wizard.jinja2 @@ -1,14 +1,22 @@

{{ _('Access Control') }}

-{% trans %}

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

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

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

+

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

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

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

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

{% endtrans %}
diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 index fa4522cd0..98a4ea007 100644 --- a/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 +++ b/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 @@ -29,7 +29,7 @@

{% trans %} Finally, please decide on whether to enable or disable the connectivity check. You may change the configuration at - any time to a later date through Settings > Server right from within OctoPrint. + any time through Settings > Server right from within OctoPrint. {% endtrans %}

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

{{ _('General') }}

- -

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

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

{{ _('Profiles') }}

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

{{ _('Configure CuraEngine') }}

-

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

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

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

-

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

- -
- {% include "snippets/settings/cura/profiles.jinja2" %} -
- - - -
- {% trans %} - Don't know where to get a profile? In order to export - a slicing profile from the Cura desktop UI up to and including version 15.04.06 (not versions - 2.1 and later which are actually newer than 15.04), open it, set up your profile, then click - on "File" and there on "Save Profile". You can import the .ini file this creates - via the "Import Profile" button. - {% endtrans %} -
-
diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 deleted file mode 100644 index 690f1490d..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 +++ /dev/null @@ -1,7 +0,0 @@ -
-
- -
-
diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 deleted file mode 100644 index b2e6a522d..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 +++ /dev/null @@ -1,10 +0,0 @@ -
- -
-
- - -
- -
-
diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 deleted file mode 100644 index ddf48eb2b..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 +++ /dev/null @@ -1,64 +0,0 @@ - diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 deleted file mode 100644 index f5d85ea3e..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 +++ /dev/null @@ -1,34 +0,0 @@ -
- - - - - - - - - - - - - - - - -
{{ _('Identifier') }}{{ _('Name') }}{{ _('Actions') }}
-  |  -
- -
diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index 031ef7d48..e8d153f8e 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -20,8 +20,9 @@ import octoprint.plugin import octoprint.util try: + # TODO: looks like pybonjour is py2 only - find alternatives or port? import pybonjour -except: +except ImportError: pybonjour = False @@ -194,8 +195,20 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, params["txtRecord"] = pybonjour.TXTRecord(txt_record) key = (reg_type, port) - self._sd_refs[key] = pybonjour.DNSServiceRegister(**params) - self._logger.info(u"Registered {name} for {reg_type}".format(**locals())) + + counter = 1 + while True: + try: + self._sd_refs[key] = pybonjour.DNSServiceRegister(**params) + self._logger.info("Registered '{name}' for {regtype}".format(**params)) + return True + except pybonjour.BonjourError as be: + if be.errorCode == pybonjour.kDNSServiceErr_NameConflict: + # Name already registered by different service, let's try a counter postfix. See #2852 + counter += 1 + params["name"] = "{} ({})".format(name, counter) + else: + raise def zeroconf_unregister(self, reg_type, port=None): """ @@ -220,7 +233,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, try: sd_ref.close() self._logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port)) - except: + except Exception: self._logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port)) def zeroconf_browse(self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5): @@ -366,7 +379,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, def browse_callback(results): for result in results: - print "Location: {}".format(result) + print("Location: {}".format(result)) :param query: the SSDP query to send, e.g. "upnp:rootdevice" to search for all devices :param block: whether to block, defaults to True @@ -378,10 +391,16 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, """ import threading - - import httplib import io - class Response(httplib.HTTPResponse): + + try: + # noinspection PyCompatibility + from http.client import HTTPResponse # py3 + except ImportError: + # noinspection PyCompatibility + from httplib import HTTPResponse # py2 + + class Response(HTTPResponse): def __init__(self, response_text): self.fp = io.BytesIO(response_text) self.debuglevel = 0 @@ -419,7 +438,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, mcast_addr=self.__class__.ssdp_multicast_addr, mcast_port=self.__class__.ssdp_multicast_port) for _ in range(2): - sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port)) + sock.sendto(message.encode("utf-8"), (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port)) try: data = sock.recv(1024) @@ -429,7 +448,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, response = Response(data) result.append(response.getheader("Location")) - except: + except Exception: pass if callback: @@ -550,9 +569,8 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, """ import socket - import time - if alive and self._ssdp_last_notify + self._ssdp_notify_timeout > time.time(): + if alive and self._ssdp_last_notify + self._ssdp_notify_timeout > octoprint.util.monotonic_time(): # we just sent an alive, no need to send another one now return @@ -587,11 +605,11 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, mcast_port=self.__class__.ssdp_multicast_port) for _ in range(2): # send twice, stuff might get lost, it's only UDP - sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port)) - except: + sock.sendto(message.encode("utf-8"), (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port)) + except Exception: pass - self._ssdp_last_notify = time.time() + self._ssdp_last_notify = octoprint.util.monotonic_time() def _ssdp_monitor(self, timeout=5): """ @@ -641,22 +659,23 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.__class__.ssdp_multicast_addr) + socket.inet_aton('0.0.0.0')) - self._logger.info(u"Registered {} for SSDP".format(self.get_instance_name())) + self._logger.info("Registered {} for SSDP".format(self.get_instance_name())) self._ssdp_notify(alive=True) try: - while (self._ssdp_monitor_active): + while self._ssdp_monitor_active: try: data, address = sock.recvfrom(4096) request = Request(data) if not request.error_code and request.command == "M-SEARCH" and request.path == "*" and (request.headers["ST"] == "upnp:rootdevice" or request.headers["ST"] == "ssdp:all") and request.headers["MAN"] == '"ssdp:discover"': interface_address = octoprint.util.address_for_client(*address) if not interface_address: - self._logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address)) + self._logger.warning("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address)) continue - message = location_message.format(uuid=self.get_uuid(), location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port)) - sock.sendto(message, address) + message = location_message.format(uuid=self.get_uuid(), + location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port)) + sock.sendto(message.encode("utf-8"), address) self._logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address)) except socket.timeout: pass @@ -665,7 +684,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, finally: try: sock.close() - except: + except Exception: pass ##~~ helpers @@ -682,10 +701,10 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, def get_instance_name(self): name = self._settings.global_get(["appearance", "name"]) if name: - return u"OctoPrint instance \"{}\"".format(name) + return "OctoPrint instance \"{}\"".format(name) else: import socket - return u"OctoPrint instance on {}".format(socket.gethostname()) + return "OctoPrint instance on {}".format(socket.gethostname()) __plugin_name__ = "Discovery" diff --git a/src/octoprint/plugins/errortracking/__init__.py b/src/octoprint/plugins/errortracking/__init__.py new file mode 100644 index 000000000..816c49eee --- /dev/null +++ b/src/octoprint/plugins/errortracking/__init__.py @@ -0,0 +1,212 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import octoprint.plugin +import logging + +from octoprint.util import get_fully_qualified_classname as fqcn +from octoprint.util.version import get_octoprint_version_string, is_released_octoprint_version + +from flask import jsonify +from flask_babel import gettext + +SENTRY_URL_SERVER = "https://6c066dfe16c244d38fca46dbc05e1028@sentry.io/1373987" +SENTRY_URL_COREUI = "https://fb45e3d5210b43bfaccd5f3c45c2b28d@sentry.io/1374096" + +SETTINGS_DEFAULTS = dict(enabled=False, + enabled_unreleased=False, + unique_id=None, + url_server=SENTRY_URL_SERVER, + url_coreui=SENTRY_URL_COREUI) + +import serial +import requests.exceptions +import errno +import octoprint.util.avr_isp.ispBase +import tornado.websocket + +IGNORED_EXCEPTIONS = [ + # serial exceptions in octoprint.util.comm + (serial.SerialException, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"), + + # isp errors during port auto detection in octoprint.util.comm + (octoprint.util.avr_isp.ispBase.IspError, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"), + + # IOErrors of any kind due to a full file system + (IOError, lambda exc, logger, plugin, cb: getattr(exc, "errno") and exc.errno in (getattr(errno, "ENOSPC"),)), + + # RequestExceptions of any kind + requests.exceptions.RequestException, + + # Tornado WebSocketErrors of any kind + tornado.websocket.WebSocketError, + + # Anything triggered by or in third party plugin Astroprint + (Exception, lambda exc, logger, plugin, cb: logger.startswith("octoprint.plugins.astroprint") + or plugin == "astroprint" + or cb.startswith("octoprint_astroprint.")) +] + +try: + # noinspection PyUnresolvedReferences + from octoprint.plugins.backup import InsufficientSpace + + # if the backup plugin is enabled, ignore InsufficientSpace errors from it as well + IGNORED_EXCEPTIONS.append(InsufficientSpace) + + del InsufficientSpace +except ImportError: + pass + + +class ErrorTrackingPlugin(octoprint.plugin.SettingsPlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.SimpleApiPlugin): + + def get_template_configs(self): + return [ + dict(type="settings", + name=gettext("Error Tracking"), + template="errortracking_settings.jinja2", + custom_bindings=False), + dict(type="generic", template="errortracking_javascripts.jinja2") + ] + + def get_template_vars(self): + enabled = self._settings.get_boolean(["enabled"]) + enabled_unreleased = self._settings.get_boolean(["enabled_unreleased"]) + + return dict(enabled=_is_enabled(enabled, enabled_unreleased), + unique_id=self._settings.get(["unique_id"]), + url_coreui=self._settings.get(["url_coreui"])) + + def get_assets(self): + return dict(js=["js/sentry.min.js", "js/errortracking.js"]) + + def get_settings_defaults(self): + return SETTINGS_DEFAULTS + + def on_settings_save(self, data): + old_enabled = _is_enabled(self._settings.get_boolean(["enabled"]), + self._settings.get_boolean(["enabled_unreleased"])) + + octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + + enabled = _is_enabled(self._settings.get_boolean(["enabled"]), + self._settings.get_boolean(["enabled_unreleased"])) + + if old_enabled != enabled: + _enable_errortracking() + + def on_api_get(self, request): + return jsonify(**self.get_template_vars()) + + +_enabled = False +def _enable_errortracking(): + # this is a bit hackish, but we want to enable error tracking as early in the platform lifecycle as possible + # and hence can't wait until our implementation is initialized and injected with settings + + from octoprint.settings import settings + global _enabled + + if _enabled: + return + + version = get_octoprint_version_string() + + s = settings() + plugin_defaults = dict(plugins=dict(errortracking=SETTINGS_DEFAULTS)) + + enabled = s.getBoolean(["plugins", "errortracking", "enabled"], defaults=plugin_defaults) + enabled_unreleased = s.getBoolean(["plugins", "errortracking", "enabled_unreleased"], defaults=plugin_defaults) + url_server = s.get(["plugins", "errortracking", "url_server"], defaults=plugin_defaults) + unique_id = s.get(["plugins", "errortracking", "unique_id"], defaults=plugin_defaults) + if unique_id is None: + import uuid + unique_id = str(uuid.uuid4()) + s.set(["plugins", "errortracking", "unique_id"], unique_id, defaults=plugin_defaults) + s.save() + + if _is_enabled(enabled, enabled_unreleased): + import sentry_sdk + from octoprint.plugin import plugin_manager + + def _before_send(event, hint): + if not "exc_info" in hint: + # we only want exceptions + return None + + handled = True + logger = event.get("logger", "") + plugin = event.get("extra", dict()).get("plugin", None) + callback = event.get("extra", dict()).get("callback", None) + + for ignore in IGNORED_EXCEPTIONS: + if isinstance(ignore, tuple): + ignored_exc, matcher = ignore + else: + ignored_exc = ignore + matcher = lambda *args: True + + exc = hint["exc_info"][1] + if isinstance(exc, ignored_exc) and matcher(exc, logger, plugin, callback): + # exception ignored for logger, plugin and/or callback + return None + + elif isinstance(ignore, type): + if isinstance(hint["exc_info"][1], ignore): + # exception ignored + return None + + if event.get("exception") and event["exception"].get("values"): + handled = not any(map(lambda x: x.get("mechanism") and x["mechanism"].get("handled", True) == False, + event["exception"]["values"])) + + if handled: + # error is handled, restrict further based on logger + if logger != "" and not (logger.startswith("octoprint.") or logger.startswith("tornado.")): + # we only want errors logged by loggers octoprint.* or tornado.* + return None + + if logger.startswith("octoprint.plugins."): + plugin_id = logger.split(".")[2] + plugin_info = plugin_manager().get_plugin_info(plugin_id) + if plugin_info is None or not plugin_info.bundled: + # we only want our active bundled plugins + return None + + if plugin is not None: + plugin_info = plugin_manager().get_plugin_info(plugin) + if plugin_info is None or not plugin_info.bundled: + # we only want our active bundled plugins + return None + + return event + + sentry_sdk.init(url_server, + release=version, + before_send=_before_send) + + with sentry_sdk.configure_scope() as scope: + scope.user = dict(id=unique_id) + + logging.getLogger("octoprint.plugins.errortracking").info("Initialized error tracking") + _enabled = True + + +def _is_enabled(enabled, enabled_unreleased): + return enabled and (enabled_unreleased or is_released_octoprint_version()) + + +def __plugin_enable__(): + _enable_errortracking() + + +__plugin_name__ = "Error Tracking" +__plugin_author__ = "Gina Häußge" +__plugin_implementation__ = ErrorTrackingPlugin() diff --git a/src/octoprint/plugins/errortracking/static/js/errortracking.js b/src/octoprint/plugins/errortracking/static/js/errortracking.js new file mode 100644 index 000000000..32ed05e0b --- /dev/null +++ b/src/octoprint/plugins/errortracking/static/js/errortracking.js @@ -0,0 +1,103 @@ +$(function() { + function ErrorTrackingViewModel(parameters) { + var self = this; + + self.settings = parameters[0]; + self.loginState = parameters[1]; + + var notification = undefined; + var performCheck = function() { + if (!self.loginState.isAdmin()) return; + + // already enabled? + if (self.settings.settings.plugins.errortracking.enabled()) return; + + // RC release channel? + var releaseChannel = self.settings.settings.plugins.softwareupdate.octoprint_release_channel(); + if (releaseChannel === "rc/maintenance" || releaseChannel === "rc/devel") { + if (notification !== undefined) return; + + // ignored? + try { + var ignoredString = localStorage["plugin.errortracking.notification_ignored"]; + var ignored = false; + + if (ignoredString) { + ignored = JSON.parse(ignoredString); + } + + if (ignored) return; + } catch (ex) { + log.error("Error while reading plugin.errortracking.notification_ignored from local storage"); + } + + // show notification + notification = new PNotify({ + title: gettext("Enable error reporting?"), + text: gettext("

It looks like you are tracking an OctoPrint RC release channel. It " + + "would be great if you would enable error reporting so that any kind of errors that occur " + + "with an RC can be looked into more easily. Thank you!

" + + "

You can find more information on error reporting " + + "under Settings > Error Tracking

"), + hide: false, + confirm: { + confirm: true, + buttons: [{ + text: gettext("Ignore"), + click: function() { + notification.remove(); + notification = undefined; + new PNotify({ + text: gettext("You can still enable error tracking via \"Settings\" > \"Error Tracking\"") + }); + + if (Modernizr.localstorage) { + localStorage["plugin.errortracking.notification_ignored"] = JSON.stringify(true); + } + } + }, { + text: gettext("Enable"), + addClass: "btn-primary", + click: function() { + self.settings.saveData({ + plugins: { + errortracking: { + enabled: true + } + } + }).done(function() { + notification.remove(); + notification = undefined; + location.reload(true); + }); + } + }] + }, + buttons: { + closer: false, + sticker: false + } + }); + + // not an RC release channel, close notification + } else if (notification !== undefined) { + notification.remove(); + notification = undefined; + } + }; + + var subbed = false; + self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function() { + performCheck(); + if (self.settings && self.settings.settings && self.settings.settings.plugins && self.settings.settings.plugins.softwareupdate && !subbed) { + subbed = true; + self.settings.settings.plugins.softwareupdate.octoprint_release_channel.subscribe(performCheck); + } + }; + } + + OCTOPRINT_VIEWMODELS.push({ + construct: ErrorTrackingViewModel, + dependencies: ["settingsViewModel", "loginStateViewModel"] + }); +}); diff --git a/src/octoprint/plugins/errortracking/static/js/sentry.min.js b/src/octoprint/plugins/errortracking/static/js/sentry.min.js new file mode 100644 index 000000000..83bb176de --- /dev/null +++ b/src/octoprint/plugins/errortracking/static/js/sentry.min.js @@ -0,0 +1,2 @@ +/*! @sentry/browser 5.0.5 (913eafc4) | https://github.com/getsentry/sentry-javascript */ +var Sentry=function(n){"use strict";var t=function(n,r){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,t){n.__proto__=t}||function(n,t){for(var r in t)t.hasOwnProperty(r)&&(n[r]=t[r])})(n,r)};function r(n,r){function i(){this.constructor=n}t(n,r),n.prototype=null===r?Object.create(r):(i.prototype=r.prototype,new i)}var i,e,o,u=function(){return(u=Object.assign||function(n){for(var t,r=1,i=arguments.length;r0&&e[e.length-1])&&(6===o[0]||2===o[0])){u=0;continue}if(3===o[0]&&(!e||o[1]>e[0]&&o[1]0)&&!(i=o.next()).done;)u.push(i.value)}catch(n){e={error:n}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return u}function a(){for(var n=[],t=0;t=200&&t<300?n.Success:429===t?n.RateLimit:t>=400&&t<500?n.Invalid:t>=500?n.Failed:n.Unknown}}(n.Status||(n.Status={}));var b={};function w(){return"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:b}function g(){var n=w(),t=n.crypto||n.msCrypto;if(void 0!==t&&t.getRandomValues){var r=new Uint16Array(8);t.getRandomValues(r),r[3]=4095&r[3]|16384,r[4]=16383&r[4]|32768;var i=function(n){for(var t=n.toString(16);t.length<4;)t="0"+t;return t};return i(r[0])+i(r[1])+i(r[2])+i(r[3])+i(r[4])+i(r[5])+i(r[6])+i(r[7])}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(n){var t=16*Math.random()|0;return("x"===n?t:3&t|8).toString(16)})}function E(n){var t,r,i,e,o,u=[];if(!n||!n.tagName)return"";if(u.push(n.tagName.toLowerCase()),n.id&&u.push("#"+n.id),(t=n.className)&&d(t))for(r=t.split(/\s+/),o=0;o"}return n.event_id||""}function S(n){var t=w();if(!("console"in t))return n();var r=t.console,i={};["debug","info","warn","error","log"].forEach(function(n){n in t.console&&r[n].__sentry__&&(i[n]=r[n].__sentry_wrapped__,r[n]=r[n].__sentry_original__)});var e=n();return Object.keys(i).forEach(function(n){r[n]=i[n]}),e}function _(n,t,r,i){void 0===i&&(i={handled:!0,type:"generic"}),n.exception=n.exception||{},n.exception.values=n.exception.values||[],n.exception.values[0]=n.exception.values[0]||{},n.exception.values[0].value=n.exception.values[0].value||t||"",n.exception.values[0].type=n.exception.values[0].type||r||"Error",n.exception.values[0].mechanism=n.exception.values[0].mechanism||i}var O,k=function(){function n(){this.t="function"==typeof WeakSet,this.i=this.t?new WeakSet:[]}return n.prototype.memoize=function(n){if(this.t)return!!this.i.has(n)||(this.i.add(n),!1);for(var t=0;tr?D(n,t-1,r):i}function I(n,t){return"domain"===t&&"object"==typeof n&&n.o?"[Domain]":"domainEmitter"===t?"[DomainEmitter]":"undefined"!=typeof global&&n===global?"[Global]":"undefined"!=typeof window&&n===window?"[Window]":"undefined"!=typeof document&&n===document?"[Document]":"undefined"!=typeof Event&&n instanceof Event?Object.getPrototypeOf(n)?n.constructor.name:"Event":m(r=n)&&"nativeEvent"in r&&"preventDefault"in r&&"stopPropagation"in r?"[SyntheticEvent]":Number.isNaN(n)?"[NaN]":void 0===n?"[undefined]":"function"==typeof n?"[Function: "+(n.name||"")+"]":n;var r}function A(n,t,r,i){if(void 0===r&&(r=1/0),void 0===i&&(i=new k),0===r)return function(n){var t=Object.prototype.toString.call(n);if("string"==typeof n)return n;if("[object Object]"===t)return"[Object]";if("[object Array]"===t)return"[Array]";var r=I(n);return p(r)?r:t}(t);if(null!=t&&"function"==typeof t.toJSON)return t.toJSON();var e=I(t,n);if(p(e))return e;var o=h(t)?function(n){var t={message:n.message,name:n.name,stack:n.stack};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r]);return t}(t):t,u=Array.isArray(t)?[]:{};if(i.memoize(t))return"[Circular ~]";for(var c in o)Object.prototype.hasOwnProperty.call(o,c)&&(u[c]=A(c,o[c],r-1,i));return i.unmemoize(t),u}function C(n,t){try{return JSON.parse(JSON.stringify(n,function(n,r){return A(n,r,t)}))}catch(n){return"**non-serializable**"}}!function(n){n.PENDING="PENDING",n.RESOLVED="RESOLVED",n.REJECTED="REJECTED"}(O||(O={}));var M=function(){function n(n){var t=this;this.u=O.PENDING,this.s=[],this.h=function(n){t.v(n,O.RESOLVED)},this.l=function(n){t.v(n,O.REJECTED)},this.v=function(n,r){t.u===O.PENDING&&(y(n)?n.then(t.h,t.l):(t.p=n,t.u=r,t.m()))},this.m=function(){t.u!==O.PENDING&&(t.u===O.REJECTED?t.s.forEach(function(n){return n.onFail&&n.onFail(t.p)}):t.s.forEach(function(n){return n.onSuccess&&n.onSuccess(t.p)}),t.s=[])},this.g=function(n){t.s=t.s.concat(n),t.m()};try{n(this.h,this.l)}catch(n){this.l(n)}}return n.prototype.then=function(t,r){var i=this;return new n(function(n,e){i.g({onFail:function(t){if(r)try{return void n(r(t))}catch(n){return void e(n)}else e(t)},onSuccess:function(r){if(t)try{return void n(t(r))}catch(n){return void e(n)}else n(r)}})})},n.prototype.catch=function(n){return this.then(function(n){return n},n)},n.prototype.toString=function(){return"[object SyncPromise]"},n.resolve=function(t){return new n(function(n){n(t)})},n.reject=function(t){return new n(function(n,r){r(t)})},n}(),N=function(){function n(){this.j=!1,this.S=[],this._=[],this.O=[],this.k={},this.T={},this.R={}}return n.prototype.addScopeListener=function(n){this.S.push(n)},n.prototype.addEventProcessor=function(n){return this._.push(n),this},n.prototype.D=function(){var n=this;this.j||(this.j=!0,setTimeout(function(){n.S.forEach(function(t){t(n)}),n.j=!1}))},n.prototype.I=function(n,t,r,i){var e=this;return void 0===i&&(i=0),new M(function(o,c){var s=n[i];if(null===t||"function"!=typeof s)o(t);else{var f=s(u({},t),r);y(f)?f.then(function(t){return e.I(n,t,r,i+1).then(o)}).catch(c):e.I(n,f,r,i+1).then(o).catch(c)}})},n.prototype.setUser=function(n){return this.k=C(n),this.D(),this},n.prototype.setTags=function(n){return this.T=u({},this.T,C(n)),this.D(),this},n.prototype.setTag=function(n,t){var r;return this.T=u({},this.T,((r={})[n]=C(t),r)),this.D(),this},n.prototype.setExtras=function(n){return this.R=u({},this.R,C(n)),this.D(),this},n.prototype.setExtra=function(n,t){var r;return this.R=u({},this.R,((r={})[n]=C(t),r)),this.D(),this},n.prototype.setFingerprint=function(n){return this.A=C(n),this.D(),this},n.prototype.setLevel=function(n){return this.C=C(n),this.D(),this},n.clone=function(t){var r=new n;return Object.assign(r,t,{S:[]}),t&&(r.O=a(t.O),r.T=u({},t.T),r.R=u({},t.R),r.k=t.k,r.C=t.C,r.A=t.A,r._=a(t._)),r},n.prototype.clear=function(){return this.O=[],this.T={},this.R={},this.k={},this.C=void 0,this.A=void 0,this.D(),this},n.prototype.addBreadcrumb=function(n,t){return this.O=void 0!==t&&t>=0?a(this.O,[C(n)]).slice(-t):a(this.O,[C(n)]),this.D(),this},n.prototype.clearBreadcrumbs=function(){return this.O=[],this.D(),this},n.prototype.M=function(n){n.fingerprint=n.fingerprint?Array.isArray(n.fingerprint)?n.fingerprint:[n.fingerprint]:[],this.A&&(n.fingerprint=n.fingerprint.concat(this.A)),n.fingerprint&&!n.fingerprint.length&&delete n.fingerprint},n.prototype.applyToEvent=function(n,t){return this.R&&Object.keys(this.R).length&&(n.extra=u({},this.R,n.extra)),this.T&&Object.keys(this.T).length&&(n.tags=u({},this.T,n.tags)),this.k&&Object.keys(this.k).length&&(n.user=u({},this.k,n.user)),this.C&&(n.level=this.C),this.M(n),(!n.breadcrumbs||0===n.breadcrumbs.length)&&this.O.length>0&&(n.breadcrumbs=this.O),this.I(a(F(),this._),n,t)},n}();function F(){var n=w();return n.__SENTRY__=n.__SENTRY__||{},n.__SENTRY__.globalEventProcessors=n.__SENTRY__.globalEventProcessors||[],n.__SENTRY__.globalEventProcessors}function U(n){F().push(n)}var L=w(),P="Sentry Logger ",$=function(){function n(){this.N=!1}return n.prototype.disable=function(){this.N=!1},n.prototype.enable=function(){this.N=!0},n.prototype.log=function(){for(var n=[],t=0;t0?n[n.length-1].scope:void 0,r=N.clone(t);return this.getStack().push({client:this.getClient(),scope:r}),r},n.prototype.popScope=function(){return void 0!==this.getStack().pop()},n.prototype.withScope=function(n){var t=this.pushScope();try{n(t)}finally{this.popScope()}},n.prototype.getClient=function(){return this.getStackTop().client},n.prototype.getScope=function(){return this.getStackTop().scope},n.prototype.getStack=function(){return this.U},n.prototype.getStackTop=function(){return this.U[this.U.length-1]},n.prototype.captureException=function(n,t){var r=this.P=g();return this.L("captureException",n,u({},t,{event_id:r})),r},n.prototype.captureMessage=function(n,t,r){var i=this.P=g();return this.L("captureMessage",n,t,u({},r,{event_id:i})),i},n.prototype.captureEvent=function(n,t){var r=this.P=g();return this.L("captureEvent",n,u({},t,{event_id:r})),r},n.prototype.lastEventId=function(){return this.P},n.prototype.addBreadcrumb=function(n,t){var r=this.getStackTop();if(r.scope&&r.client){var i=r.client.getOptions(),e=i.beforeBreadcrumb,o=i.maxBreadcrumbs,c=void 0===o?30:o;if(!(c<=0)){var s=(new Date).getTime()/1e3,f=u({timestamp:s},n),a=e?S(function(){return e(f,t)}):f;null!==a&&r.scope.addBreadcrumb(a,Math.min(c,100))}}},n.prototype.configureScope=function(n){var t=this.getStackTop();t.scope&&t.client&&n(t.scope)},n.prototype.run=function(n){var t=G(this);try{n(this)}finally{G(t)}},n.prototype.getIntegration=function(n){var t=this.getClient();if(!t)return null;try{return t.getIntegration(n)}catch(t){return q.warn("Cannot retrieve integration "+n.id+" from the current Hub"),null}},n}();function B(){var n=w();return n.__SENTRY__=n.__SENTRY__||{hub:void 0},n}function G(n){var t=B(),r=z(t);return V(t,n),r}function J(){var n,t,r=B();X(r)&&!z(r).isOlderThan(H)||V(r,new W);try{var i=(n=module,t="domain",n.require(t)).active;if(!i)return z(r);if(!X(i)||z(i).isOlderThan(H)){var e=z(r).getStackTop();V(i,new W(e.client,N.clone(e.scope)))}return z(i)}catch(n){return z(r)}}function X(n){return!!(n&&n.__SENTRY__&&n.__SENTRY__.hub)}function z(n){return n&&n.__SENTRY__&&n.__SENTRY__.hub?n.__SENTRY__.hub:(n.__SENTRY__=n.__SENTRY__||{},n.__SENTRY__.hub=new W,n.__SENTRY__.hub)}function V(n,t){return!!n&&(n.__SENTRY__=n.__SENTRY__||{},n.__SENTRY__.hub=t,!0)}function K(n){for(var t=[],r=1;r1&&(h=l.slice(0,-1).join("/"),v=l.pop()),Object.assign(this,{host:c,pass:u,path:h,projectId:v,port:a,protocol:i,user:e})},n.prototype.q=function(n){this.protocol=n.protocol,this.user=n.user,this.pass=n.pass||"",this.host=n.host,this.port=n.port||"",this.path=n.path||"",this.projectId=n.projectId},n.prototype.H=function(){var n=this;if(["protocol","user","host","projectId"].forEach(function(t){if(!n[t])throw new Q("Invalid Dsn")}),"http"!==this.protocol&&"https"!==this.protocol)throw new Q("Invalid Dsn");if(this.port&&Number.isNaN(parseInt(this.port,10)))throw new Q("Invalid Dsn")},n}(),tn=function(){function n(n){this.dsn=n,this.W=new nn(n)}return n.prototype.getDsn=function(){return this.W},n.prototype.getStoreEndpoint=function(){return""+this.B()+this.getStoreEndpointPath()},n.prototype.getStoreEndpointWithUrlEncodedAuth=function(){var n,t={sentry_key:this.W.user,sentry_version:"7"};return this.getStoreEndpoint()+"?"+(n=t,Object.keys(n).map(function(t){return encodeURIComponent(t)+"="+encodeURIComponent(n[t])}).join("&"))},n.prototype.B=function(){var n=this.W,t=n.protocol?n.protocol+":":"",r=n.port?":"+n.port:"";return t+"//"+n.host+r},n.prototype.getStoreEndpointPath=function(){var n=this.W;return(n.path?"/"+n.path:"")+"/api/"+n.projectId+"/store/"},n.prototype.getRequestHeaders=function(n,t){var r=this.W,i=["Sentry sentry_version=7"];return i.push("sentry_timestamp="+(new Date).getTime()),i.push("sentry_client="+n+"/"+t),i.push("sentry_key="+r.user),r.pass&&i.push("sentry_secret="+r.pass),{"Content-Type":"application/json","X-Sentry-Auth":i.join(", ")}},n.prototype.getReportDialogEndpoint=function(n){void 0===n&&(n={});var t=this.W,r=this.B()+(t.path?"/"+t.path:"")+"/api/embed/error-page/",i=[];for(var e in i.push("dsn="+t.toString()),n)if("user"===e){if(!n.user)continue;n.user.name&&i.push("name="+encodeURIComponent(n.user.name)),n.user.email&&i.push("email="+encodeURIComponent(n.user.email))}else i.push(encodeURIComponent(e)+"="+encodeURIComponent(n[e]));return i.length?r+"?"+i.join("&"):r},n}();function rn(n,t){return void 0===t&&(t=0),0===t?n:n.length<=t?n:n.substr(0,t)+"..."}function en(n,t){if(!Array.isArray(n))return"";for(var r=[],i=0;i=t)return rn(n[0],t);for(var r=n.length;r>0;r--){var i=n.slice(0,r).join(", ");if(!(i.length>t))return r===n.length?i:rn(i,t)}return""}var un=[];function cn(n){var t={};return function(n){var t=n.defaultIntegrations&&a(n.defaultIntegrations)||[],r=n.integrations,i=[];if(Array.isArray(r)){var e=r.map(function(n){return n.name}),o=[];t.forEach(function(n){-1===e.indexOf(n.name)&&-1===o.indexOf(n.name)&&(i.push(n),o.push(n.name))}),r.forEach(function(n){-1===o.indexOf(n.name)&&(i.push(n),o.push(n.name))})}else{if("function"!=typeof r)return a(t);i=r(t),i=Array.isArray(i)?i:[i]}return i}(n).forEach(function(n){t[n.name]=n,function(n){-1===un.indexOf(n.name)&&(n.setupOnce(U,J),un.push(n.name),q.log("Integration installed: "+n.name))}(n)}),t}var sn,fn=function(){function n(n,t){this.G=!1,this.J=new n(t),this.X=t,t.dsn&&(this.V=new nn(t.dsn)),this.K=cn(this.X)}return n.prototype.captureException=function(n,t,r){var i=this,e=t&&t.event_id;return this.G=!0,this.Z().eventFromException(n,t).then(function(n){return i.Y(n,t,r)}).then(function(n){e=n&&n.event_id,i.G=!1}).catch(function(n){q.log(n),i.G=!1}),e},n.prototype.captureMessage=function(n,t,r,i){var e=this,o=r&&r.event_id;return this.G=!0,(p(n)?this.Z().eventFromMessage(""+n,t,r):this.Z().eventFromException(n,r)).then(function(n){return e.Y(n,r,i)}).then(function(n){o=n&&n.event_id,e.G=!1}).catch(function(n){q.log(n),e.G=!1}),o},n.prototype.captureEvent=function(n,t,r){var i=this,e=t&&t.event_id;return this.G=!0,this.Y(n,t,r).then(function(n){e=n&&n.event_id,i.G=!1}).catch(function(n){q.log(n),i.G=!1}),e},n.prototype.getDsn=function(){return this.V},n.prototype.getOptions=function(){return this.X},n.prototype.flush=function(n){return c(this,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return[4,Promise.all([this.Z().getTransport().close(n),this.nn()])];case 1:return[2,t.sent().reduce(function(n,t){return n&&t})]}})})},n.prototype.close=function(n){return c(this,void 0,void 0,function(){var t=this;return s(this,function(r){return[2,this.flush(n).finally(function(){t.getOptions().enabled=!1})]})})},n.prototype.getIntegrations=function(){return this.K||{}},n.prototype.getIntegration=function(n){try{return this.K[n.id]||null}catch(t){return q.warn("Cannot retrieve integration "+n.id+" from the current Client"),null}},n.prototype.nn=function(n){return void 0===n&&(n=0),c(this,void 0,void 0,function(){var t=this;return s(this,function(r){return[2,new Promise(function(r){t.G?n>=10?r(!1):setTimeout(function(){return c(t,void 0,void 0,function(){var t;return s(this,function(i){switch(i.label){case 0:return t=r,[4,this.nn(n+1)];case 1:return t.apply(void 0,[i.sent()]),[2]}})})},10):r(!0)})]})})},n.prototype.Z=function(){return this.J},n.prototype.tn=function(){return!1!==this.getOptions().enabled&&void 0!==this.V},n.prototype.rn=function(n,t,r){var i=this.getOptions(),e=i.environment,o=i.release,c=i.dist,s=i.maxValueLength,f=void 0===s?250:s,a=u({},n);void 0===a.environment&&void 0!==e&&(a.environment=e),void 0===a.release&&void 0!==o&&(a.release=o),void 0===a.dist&&void 0!==c&&(a.dist=c),a.message&&(a.message=rn(a.message,f));var h=a.exception&&a.exception.values&&a.exception.values[0];h&&h.value&&(h.value=rn(h.value,f));var v=a.request;v&&v.url&&(v.url=rn(v.url,f)),void 0===a.event_id&&(a.event_id=g()),this.in(a.sdk);var l=M.resolve(a);return t&&(l=t.applyToEvent(a,r)),l},n.prototype.in=function(n){var t=Object.keys(this.K);n&&t.length>0&&(n.integrations=t)},n.prototype.Y=function(n,t,r){var i=this,e=this.getOptions(),o=e.beforeSend,u=e.sampleRate;return this.tn()?"number"==typeof u&&Math.random()>u?M.reject("This event has been sampled, will not send event."):new M(function(e,u){i.rn(n,r,t).then(function(n){if(null!==n){var r=n;try{if(t&&t.data&&!0===t.data.__sentry__||!o)return i.Z().sendEvent(r),void e(r);var c=o(n,t);if(void 0===c)q.error("`beforeSend` method has to return `null` or a valid event.");else if(y(c))i.en(c,e,u);else{if(null===(r=c))return q.log("`beforeSend` returned `null`, will not send event."),void e(null);i.Z().sendEvent(r),e(r)}}catch(n){i.captureException(n,{data:{__sentry__:!0},originalException:n}),u("`beforeSend` throw an error, will not send event.")}}else u("An event processor returned null, will not send event.")})}):M.reject("SDK not enabled, will not send event.")},n.prototype.en=function(n,t,r){var i=this;n.then(function(n){null!==n?(i.Z().sendEvent(n),t(n)):r("`beforeSend` returned `null`, will not send event.")}).catch(function(n){r("beforeSend rejected with "+n)})},n}(),an=function(){function t(){}return t.prototype.sendEvent=function(t){return c(this,void 0,void 0,function(){return s(this,function(t){return[2,Promise.resolve({reason:"NoopTransport: Event has been skipped because no Dsn is configured.",status:n.Status.Skipped})]})})},t.prototype.close=function(n){return c(this,void 0,void 0,function(){return s(this,function(n){return[2,Promise.resolve(!0)]})})},t}(),hn=function(){function n(n){this.X=n,this.X.dsn||q.warn("No DSN provided, backend will not do anything."),this.on=this.un()}return n.prototype.un=function(){return new an},n.prototype.eventFromException=function(n,t){throw new Q("Backend has to implement `eventFromException` method")},n.prototype.eventFromMessage=function(n,t,r){throw new Q("Backend has to implement `eventFromMessage` method")},n.prototype.sendEvent=function(n){this.on.sendEvent(n).catch(function(n){q.error("Error while sending event: "+n)})},n.prototype.getTransport=function(){return this.on},n}();var vn=function(){function n(){this.name=n.id}return n.prototype.setupOnce=function(){sn=Function.prototype.toString,Function.prototype.toString=function(){for(var n=[],t=0;t|[a-z]:|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,o=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|moz-extension).*?:\/.*?|\[native code\]|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,u=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,c=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,s=/\((\S*)(?::(\d+))(?::(\d+))\)/,f=n.stack.split("\n"),a=[],h=/^(.*) is undefined$/.exec(n.message),v=0,l=f.length;v eval")>-1&&(t=c.exec(r[3]))?r[3]=t[1]:0!==v||r[5]||void 0===n.columnNumber||(a[0].column=n.columnNumber+1),i={url:r[3],func:r[1]||gn,args:r[2]?r[2].split(","):[],line:r[4]?+r[4]:null,column:r[5]?+r[5]:null}}!i.func&&i.line&&(i.func=gn),i.context=null,a.push(i)}return a.length?(a[0]&&a[0].line&&!a[0].column&&h&&(a[0].column=null),{mode:"stack",name:n.name,message:n.message,stack:a}):null}function t(n,t,r,i){var e={url:t,line:r};if(e.url&&e.line){if(n.incomplete=!1,e.func||(e.func=gn),e.context||(e.context=null),/ '([^']+)' /.exec(i)&&(e.column=null),n.stack.length>0&&n.stack[0].url===e.url){if(n.stack[0].line===e.line)return!1;if(!n.stack[0].line&&n.stack[0].func===e.func)return n.stack[0].line=e.line,n.stack[0].context=e.context,!1}return n.stack.unshift(e),n.partial=!0,!0}return n.incomplete=!0,!1}function r(n,e){for(var o,u,c=/function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,s=[],f={},a=!1,h=r.caller;h&&!a;h=h.caller)if(h!==i&&h!==wn.report){if(u={url:null,func:gn,args:[],line:null,column:null},h.name?u.func=h.name:(o=c.exec(h.toString()))&&(u.func=o[1]),void 0===u.func)try{u.func=o.input.substring(0,o.input.indexOf("{"))}catch(n){}f[""+h]?a=!0:f[""+h]=!0,s.push(u)}e&&s.splice(0,e);var v={mode:"callers",name:n.name,message:n.message,stack:s};return t(v,n.sourceURL||n.fileName,n.line||n.lineNumber,n.message||n.description),v}function i(t,i){var e=null;i=null==i?0:+i;try{if(e=function(n){var t=n.stacktrace;if(t){for(var r,i=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,e=/ line (\d+), column (\d+)\s*(?:in (?:]+)>|([^\)]+))\((.*)\))? in (.*):\s*$/i,o=t.split("\n"),u=[],c=0;c0&&r(!1)},n);Promise.all(t.yn).then(function(){clearTimeout(i),r(!0)}).catch(function(){r(!0)})})]})})},n}(),Nn=function(){function n(n){this.options=n,this.yn=new Mn(30),this.url=new tn(this.options.dsn).getStoreEndpointWithUrlEncodedAuth()}return n.prototype.sendEvent=function(n){return c(this,void 0,void 0,function(){return s(this,function(n){throw new Q("Transport Class has to implement `sendEvent` method")})})},n.prototype.close=function(n){return c(this,void 0,void 0,function(){return s(this,function(t){return[2,this.yn.drain(n)]})})},n}(),Fn=w(),Un=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return r(i,t),i.prototype.sendEvent=function(t){return c(this,void 0,void 0,function(){var r;return s(this,function(i){return r={body:JSON.stringify(t),method:"POST",referrerPolicy:yn()?"origin":""},[2,this.yn.add(Fn.fetch(this.url,r).then(function(t){return{status:n.Status.fromHttpCode(t.status)}}))]})})},i}(Nn),Ln=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return r(i,t),i.prototype.sendEvent=function(t){return c(this,void 0,void 0,function(){var r=this;return s(this,function(i){return[2,this.yn.add(new Promise(function(i,e){var o=new XMLHttpRequest;o.onreadystatechange=function(){4===o.readyState&&(200===o.status&&i({status:n.Status.fromHttpCode(o.status)}),e(o))},o.open("POST",r.url),o.send(JSON.stringify(t))}))]})})},i}(Nn),Pn=Object.freeze({BaseTransport:Nn,FetchTransport:Un,XHRTransport:Ln}),$n=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return r(i,t),i.prototype.un=function(){if(!this.X.dsn)return t.prototype.un.call(this);var n=this.X.transportOptions?this.X.transportOptions:{dsn:this.X.dsn};return this.X.transport?new this.X.transport(n):mn()?new Un(n):new Ln(n)},i.prototype.eventFromException=function(t,r){var i,e,o=this;if(v(t)&&t.error)return t=t.error,i=Dn(kn(t)),M.resolve(this.bn(i,r));if(l(t)||(e=t,"[object DOMException]"===Object.prototype.toString.call(e))){var u=t,c=u.name||(l(u)?"DOMError":"DOMException"),s=u.message?c+": "+u.message:c;return this.eventFromMessage(s,n.Severity.Error,r).then(function(n){return _(n,s),M.resolve(o.bn(n,r))})}if(h(t))return i=Dn(kn(t)),M.resolve(this.bn(i,r));if(m(t)&&r&&r.syntheticException)return _(i=function(n,t){var r=Object.keys(n).sort(),i={extra:{__serialized__:D(n)},message:"Non-Error exception captured with keys: "+on(r)};if(t){var e=In(kn(t).stack);i.stacktrace={frames:e}}return i}(t,r.syntheticException),"Custom Object",void 0,{handled:!0,synthetic:!0,type:"generic"}),i.level=n.Severity.Error,M.resolve(this.bn(i,r));var f=t;return this.eventFromMessage(f,void 0,r).then(function(t){return _(t,""+f,void 0,{handled:!0,synthetic:!0,type:"generic"}),t.level=n.Severity.Error,M.resolve(o.bn(t,r))})},i.prototype.bn=function(n,t){return u({},n,{event_id:t&&t.event_id})},i.prototype.eventFromMessage=function(t,r,i){void 0===r&&(r=n.Severity.Info);var e={event_id:i&&i.event_id,level:r,message:t};if(this.X.attachStacktrace&&i&&i.syntheticException){var o=In(kn(i.syntheticException).stack);e.stacktrace={frames:o}}return M.resolve(e)},i}(hn),qn="sentry.javascript.browser",Hn=function(n){function t(t){return void 0===t&&(t={}),n.call(this,$n,t)||this}return r(t,n),t.prototype.rn=function(t,r,i){return t.platform=t.platform||"javascript",t.sdk=u({},t.sdk,{name:qn,packages:a(t.sdk&&t.sdk.packages||[],[{name:"npm:@sentry/browser",version:"5.0.5"}]),version:"5.0.5"}),n.prototype.rn.call(this,t,r,i)},t.prototype.showReportDialog=function(n){void 0===n&&(n={});var t=w().document;if(t)if(this.tn()){var r=n.dsn||this.getDsn();if(n.eventId)if(r){var i=t.createElement("script");i.async=!0,i.src=new tn(r).getReportDialogEndpoint(n),(t.head||t.body).appendChild(i)}else q.error("Missing `Dsn` option in showReportDialog call");else q.error("Missing `eventId` option in showReportDialog call")}else q.error("Trying to call showReportDialog with Sentry Client is disabled")},t}(fn),Wn=1e3,Bn=0;function Gn(n,t,r){if(void 0===t&&(t={}),"function"!=typeof n)return n;try{if(n.__sentry__)return n;if(n.__sentry_wrapped__)return n.__sentry_wrapped__}catch(t){return n}var sentryWrapped=function(){r&&"function"==typeof r&&r.apply(this,arguments);var i=Array.prototype.slice.call(arguments);try{var e=i.map(function(n){return Gn(n,t)});return n.handleEvent?n.handleEvent.apply(this,e):n.apply(this,e)}catch(n){throw Bn+=1,setTimeout(function(){Bn-=1}),Z(function(r){r.addEventProcessor(function(n){var r=u({},n);return t.mechanism&&_(r,void 0,void 0,t.mechanism),r.extra=u({},r.extra,{arguments:C(i,3)}),r}),captureException(n)}),n}};try{for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(sentryWrapped[i]=n[i])}catch(n){}n.prototype=n.prototype||{},sentryWrapped.prototype=n.prototype,Object.defineProperty(n,"__sentry_wrapped__",{enumerable:!1,value:sentryWrapped}),Object.defineProperties(sentryWrapped,{__sentry__:{enumerable:!1,value:!0},__sentry_original__:{enumerable:!1,value:n}});try{Object.defineProperty(sentryWrapped,"name",{get:function(){return n.name}})}catch(n){}return sentryWrapped}function Jn(n){return function(t){if(An=void 0,Cn!==t){var r;Cn=t;try{r=function(n){for(var t,r=n,i=[],e=0,o=0,u=" > ".length;r&&e++<5&&!("html"===(t=E(r))||e>1&&o+i.length*u+t.length>=80);)i.push(t),o+=t.length,r=r.parentNode;return i.reverse().join(" > ")}(t.target)}catch(n){r=""}J().addBreadcrumb({category:"ui."+n,message:r},{event:t,name:n})}}}function Xn(){return function(n){var t;try{t=n.target}catch(n){return}var r=t&&t.tagName;r&&("INPUT"===r||"TEXTAREA"===r||t.isContentEditable)&&(An||Jn("input")(n),clearTimeout(An),An=setTimeout(function(){An=void 0},Wn))}}var zn=function(){function n(t){this.name=n.id,this.X=u({onerror:!0,onunhandledrejection:!0},t)}return n.prototype.setupOnce=function(){Error.stackTraceLimit=50,Sn(function(t,r,i){if(!(Bn>0)){var e=J().getIntegration(n);e&&J().captureEvent(e.wn(t),{data:{stack:t},originalException:i})}}),this.X.onerror&&(q.log("Global Handler attached: onerror"),_n()),this.X.onunhandledrejection&&(q.log("Global Handler attached: onunhandledrejection"),On())},n.prototype.wn=function(n){var t=Dn(n),r={mode:n.mode};n.message&&(r.message=n.message),n.name&&(r.name=n.name);var i=J().getClient(),e=i&&i.getOptions().maxValueLength||250;return _(t,n.original?rn(JSON.stringify(C(n.original)),e):"","onunhandledrejection"===n.mechanism?"UnhandledRejection":"Error",{data:r,handled:!1,type:n.mechanism}),t},n.id="GlobalHandlers",n}(),Vn=function(){function n(){this.gn=0,this.name=n.id}return n.prototype.En=function(n){return function(){for(var t=[],r=0;r"}catch(n){return""}}var Zn,Qn=w(),Yn=function(){function t(n){this.name=t.id,this.X=u({console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0},n)}return t.prototype.Sn=function(){"console"in Qn&&["debug","info","warn","error","log"].forEach(function(r){r in Qn.console&&T(Qn.console,r,function(i){return function(){for(var e=[],o=0;o2?t[2]:void 0;return i&&u(Zn,String(i)),n.apply(this,t)}}},t.prototype.Tn=function(){if("XMLHttpRequest"in Qn){var n=XMLHttpRequest.prototype;T(n,"open",function(n){return function(){for(var t=[],r=0;r"},handled:!0,type:"instrument"}})})}(n,e)}),"onreadystatechange"in e&&"function"==typeof e.onreadystatechange?T(e,"onreadystatechange",function(n){return Gn(n,{mechanism:{data:{function:"onreadystatechange",handler:n&&n.name||""},handled:!0,type:"instrument"}},o)}):e.onreadystatechange=o,n.apply(this,r)}})}},t.addBreadcrumb=function(n,r){J().getIntegration(t)&&J().addBreadcrumb(n,r)},t.prototype.setupOnce=function(){this.X.console&&this.Sn(),this.X.dom&&this._n(),this.X.xhr&&this.Tn(),this.X.fetch&&this.On(),this.X.history&&this.kn()},t.id="Breadcrumbs",t}();function nt(t){try{var r=JSON.parse(t);Yn.addBreadcrumb({category:"sentry",event_id:r.event_id,level:r.level||n.Severity.fromString("error"),message:j(r)},{event:r})}catch(n){q.error("Error while adding sentry type breadcrumb")}}var tt="cause",rt=5,it=function(){function n(t){void 0===t&&(t={}),this.name=n.id,this.Rn=t.key||tt,this.mn=t.limit||rt}return n.prototype.setupOnce=function(){U(function(t,r){var i=J().getIntegration(n);return i?i.handler(t,r):t})},n.prototype.handler=function(n,t){if(!(n.exception&&n.exception.values&&t&&t.originalException instanceof Error))return n;var r=this.walkErrorTree(t.originalException,this.Rn);return n.exception.values=a(r,n.exception.values),n},n.prototype.walkErrorTree=function(n,t,r){if(void 0===r&&(r=[]),!(n[t]instanceof Error)||r.length+1>=this.mn)return r;var i=Rn(kn(n[t]));return this.walkErrorTree(n[t],t,a([i],r))},n.id="LinkedErrors",n}(),et=w(),ot=function(){function n(){this.name=n.id}return n.prototype.setupOnce=function(){U(function(t){if(J().getIntegration(n)){if(!et.navigator||!et.location)return t;var r=t.request||{};return r.url=r.url||et.location.href,r.headers=r.headers||{},r.headers["User-Agent"]=et.navigator.userAgent,u({},t,{request:r})}return t})},n.id="UserAgent",n}(),ut=Object.freeze({GlobalHandlers:zn,TryCatch:Vn,Breadcrumbs:Yn,LinkedErrors:it,UserAgent:ot}),ct=[new dn,new vn,new Vn,new Yn,new zn,new it,new ot];var st={},ft=w();ft.Sentry&&ft.Sentry.Integrations&&(st=ft.Sentry.Integrations);var at=u({},st,pn,ut);return n.Integrations=at,n.Transports=Pn,n.addGlobalEventProcessor=U,n.addBreadcrumb=function(n){K("addBreadcrumb",n)},n.captureException=captureException,n.captureEvent=function(n){return K("captureEvent",n)},n.captureMessage=function(n,t){var r;try{throw new Error(n)}catch(n){r=n}return K("captureMessage",n,t,{originalException:n,syntheticException:r})},n.configureScope=function(n){K("configureScope",n)},n.withScope=Z,n.getHubFromCarrier=z,n.getCurrentHub=J,n.Hub=W,n.Scope=N,n.BrowserClient=Hn,n.defaultIntegrations=ct,n.forceLoad=function(){},n.init=function(n){void 0===n&&(n={}),void 0===n.defaultIntegrations&&(n.defaultIntegrations=ct),function(n,t){!0===t.debug&&q.enable(),J().bindClient(new n(t))}(Hn,n)},n.lastEventId=function(){return J().lastEventId()},n.onLoad=function(n){n()},n.showReportDialog=function(n){void 0===n&&(n={}),n.eventId||(n.eventId=J().lastEventId());var t=J().getClient();t&&t.showReportDialog(n)},n.flush=function(n){return c(this,void 0,void 0,function(){var t;return s(this,function(r){return(t=J().getClient())?[2,t.flush(n)]:[2,Promise.reject(!1)]})})},n.close=function(n){return c(this,void 0,void 0,function(){var t;return s(this,function(r){return(t=J().getClient())?[2,t.close(n)]:[2,Promise.reject(!1)]})})},n.SDK_NAME=qn,n.SDK_VERSION="5.0.5",n}({}); diff --git a/src/octoprint/plugins/errortracking/templates/errortracking_javascripts.jinja2 b/src/octoprint/plugins/errortracking/templates/errortracking_javascripts.jinja2 new file mode 100644 index 000000000..d449fb7fd --- /dev/null +++ b/src/octoprint/plugins/errortracking/templates/errortracking_javascripts.jinja2 @@ -0,0 +1,32 @@ + diff --git a/src/octoprint/plugins/errortracking/templates/errortracking_settings.jinja2 b/src/octoprint/plugins/errortracking/templates/errortracking_settings.jinja2 new file mode 100644 index 000000000..56f86efee --- /dev/null +++ b/src/octoprint/plugins/errortracking/templates/errortracking_settings.jinja2 @@ -0,0 +1,42 @@ +

{{ _('Error Tracking') }}

+ +{% trans %} +

+ Error tracking will cause any logged exceptions in the server and the browser interface to be sent + to OctoPrint's Sentry instance. +

+

+ By enabling it you help to gather detailed information on the cause of bugs or other issues. This is especially valuable + on release candidates, which is why this plugin will also prompt you to enable error tracking if it detects that + you are subscribed to an RC release channel. +

+

+ Please enable this if you are running a release candidate, or are prompted to do so while debugging an issue that you reported. +

+{% endtrans %} + +
+
+
+ + {{ _('Please reload the page after enabling/disabling & saving') }} +
+
+
+ +
+ +
+
+
+ +{% trans %} +

+ The Error Tracking plugin is using a Sentry instance kindly provided by + sentry.io. For information on their service + please refer to their Security & Compliance documentation + and their Privacy Policy. +

+{% endtrans %} diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index 7ae1108e6..5a9b1e65d 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -8,7 +8,8 @@ import octoprint.plugin from octoprint.settings import settings from octoprint.server import NO_CONTENT -from octoprint.server.util.flask import redirect_to_tornado, require_firstrun +from octoprint.server.util.flask import redirect_to_tornado, no_firstrun_access +from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions from flask import request, jsonify, url_for, make_response @@ -18,6 +19,7 @@ from werkzeug.utils import secure_filename from werkzeug.exceptions import BadRequest import yaml +import io import os try: @@ -37,11 +39,12 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, dict(key="MANAGE", name="Logging management", description=gettext("Allows to download and delete log files and list and set log levels."), + default_groups=[ADMIN_GROUP], roles=["manage"]) ] @octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def get_all(self): files = self._getLogFiles() @@ -52,7 +55,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, setup=dict(loggers=loggers, levels=levels)) @octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def get_log_files(self): files = self._getLogFiles() @@ -60,13 +63,13 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, return jsonify(files=files, free=free, total=total) @octoprint.plugin.BlueprintPlugin.route("/logs/", methods=["GET"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def download_log(self, filename): return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename) @octoprint.plugin.BlueprintPlugin.route("/logs/", methods=["DELETE"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def delete_log(self, filename): secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename)) @@ -78,7 +81,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, return NO_CONTENT @octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def get_logging_setup(self): loggers = self._get_available_loggers() @@ -86,13 +89,13 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, return jsonify(loggers=loggers, levels=levels) @octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def get_logging_levels_api(self): return jsonify(self._get_logging_levels()) @octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def set_logging_levels_api(self): if not "application/json" in request.headers["Content-Type"]: @@ -145,7 +148,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, config_from_file = {} if os.path.exists(logging_file) and os.path.isfile(logging_file): import yaml - with open(logging_file, "r") as f: + with io.open(logging_file, 'rt', encoding='utf-8') as f: config_from_file = yaml.safe_load(f) return config_from_file @@ -164,23 +167,25 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, config = self._get_logging_config() # clear all configured logging levels - if config.has_key("loggers"): + if "loggers" in config: purge = [] - for component in config["loggers"]: + for component, data in config["loggers"].items(): if not self._is_managed_logger(component): continue try: - del config["loggers"][component]["level"] + del data["level"] self._logger.manager.loggerDict[component].setLevel(logging.INFO) - except: + except KeyError: pass - if len(config["loggers"][component]) == 0: + if len(data) == 0: purge.append(component) + for component in purge: + del config["loggers"][component] else: config["loggers"] = dict() # update all logging levels for logger, level in new_levels.items(): - if not config["loggers"].has_key(logger): + if logger not in config["loggers"]: config["loggers"][logger] = dict() config["loggers"][logger]["level"] = level @@ -188,7 +193,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, config["loggers"] = {k: v for k, v in config["loggers"].items() if len(v)} # save - with octoprint.util.atomic_write(self._get_logging_file(), "wb", max_permissions=0o666) as f: + with octoprint.util.atomic_write(self._get_logging_file(), mode='wt', max_permissions=0o666) as f: yaml.safe_dump(config, f, default_flow_style=False, indent=2, allow_unicode=True) # set runtime logging levels now @@ -208,6 +213,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, def get_assets(self): return dict(js=["js/logging.js"], + clientjs=["clientjs/logging.js"], less=["less/logging.less"], css=["css/logging.css"]) diff --git a/src/octoprint/plugins/logging/static/clientjs/logging.js b/src/octoprint/plugins/logging/static/clientjs/logging.js new file mode 100644 index 000000000..23b90f85d --- /dev/null +++ b/src/octoprint/plugins/logging/static/clientjs/logging.js @@ -0,0 +1,68 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + + var OctoPrintLoggingClient = function(base) { + this.base = base; + + this.baseUrl = this.base.getBlueprintUrl("logging"); + this.logsUrl = this.baseUrl + "logs"; + this.setupUrl = this.baseUrl + "setup"; + }; + + OctoPrintLoggingClient.prototype.get = function(opts) { + return this.base.get(this.baseUrl, opts); + }; + + OctoPrintLoggingClient.prototype.listLogs = function(opts) { + return this.base.get(this.logsUrl, opts); + }; + + OctoPrintLoggingClient.prototype.deleteLog = function(file, opts) { + var fileUrl = this.logsUrl + "/" + file; + return this.base.delete(fileUrl, opts); + }; + + OctoPrintLoggingClient.prototype.downloadLog = function(file, opts) { + var fileUrl = this.logsUrl + "/" + file; + return this.base.download(fileUrl, opts); + }; + + OctoPrintLoggingClient.prototype.updateLevels = function(config, opts) { + return this.base.putJson(this.setupUrl + "/levels", config, opts); + }; + + //~~ wrapper for backwards compatibility + + var DeprecatedOctoPrintLogsClient = function(base) { + this.base = base; + this.wrapped = this.base.plugins.logging; + }; + + DeprecatedOctoPrintLogsClient.prototype.list = function(opts) { + log.warn("OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead"); + return this.wrapped.listLogs(opts); + }; + + DeprecatedOctoPrintLogsClient.prototype.delete = function(file, opts) { + log.warn("OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead"); + return this.wrapped.deleteLog(file, opts); + }; + + DeprecatedOctoPrintLogsClient.prototype.download = function(file, opts) { + log.warn("OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead"); + return this.wrapped.downloadLog(file, opts); + }; + + // register plugin component + OctoPrintClient.registerPluginComponent("logging", OctoPrintLoggingClient); + + // also register deprecated client under old endpoint + OctoPrintClient.registerComponent("logs", DeprecatedOctoPrintLogsClient); + + return OctoPrintLoggingClient; +}); diff --git a/src/octoprint/plugins/logging/static/css/logging.css b/src/octoprint/plugins/logging/static/css/logging.css index 31603a340..ac69c3e52 100644 --- a/src/octoprint/plugins/logging/static/css/logging.css +++ b/src/octoprint/plugins/logging/static/css/logging.css @@ -1 +1 @@ -table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default} \ No newline at end of file +table td.settings_logs_checkbox,table th.settings_logs_checkbox{text-align:center;width:10px}table td.settings_logs_checkbox input[type=checkbox],table th.settings_logs_checkbox input[type=checkbox]{margin-top:0}table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default} \ No newline at end of file diff --git a/src/octoprint/plugins/logging/static/js/logging.js b/src/octoprint/plugins/logging/static/js/logging.js index c4131debb..7a7978ac7 100644 --- a/src/octoprint/plugins/logging/static/js/logging.js +++ b/src/octoprint/plugins/logging/static/js/logging.js @@ -1,72 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - - var OctoPrintLoggingClient = function(base) { - this.base = base; - - this.baseUrl = this.base.getBlueprintUrl("logging"); - this.logsUrl = this.baseUrl + "logs"; - this.setupUrl = this.baseUrl + "setup"; - }; - - OctoPrintLoggingClient.prototype.get = function(opts) { - return this.base.get(this.baseUrl, opts); - }; - - OctoPrintLoggingClient.prototype.listLogs = function(opts) { - return this.base.get(this.logsUrl, opts); - }; - - OctoPrintLoggingClient.prototype.deleteLog = function(file, opts) { - var fileUrl = this.logsUrl + "/" + file; - return this.base.delete(fileUrl, opts); - }; - - OctoPrintLoggingClient.prototype.downloadLog = function(file, opts) { - var fileUrl = this.logsUrl + "/" + file; - return this.base.download(fileUrl, opts); - }; - - OctoPrintLoggingClient.prototype.updateLevels = function(config, opts) { - return this.base.putJson(this.setupUrl + "/levels", config, opts); - }; - - //~~ wrapper for backwards compatibility - - var DeprecatedOctoPrintLogsClient = function(base) { - this.base = base; - this.wrapped = this.base.plugins.logging; - }; - - DeprecatedOctoPrintLogsClient.prototype.list = function(opts) { - log.warn("OctoPrintClient.logs.list has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.listLogs instead"); - return this.wrapped.listLogs(opts); - }; - - DeprecatedOctoPrintLogsClient.prototype.delete = function(file, opts) { - log.warn("OctoPrintClient.logs.delete has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.deleteLog instead"); - return this.wrapped.deleteLog(file, opts); - }; - - DeprecatedOctoPrintLogsClient.prototype.download = function(file, opts) { - log.warn("OctoPrintClient.logs.download has been deprecated as of OctoPrint 1.3.7, use OctoPrintClient.plugins.logging.downloadLog instead"); - return this.wrapped.downloadLog(file, opts); - }; - - // register plugin component - OctoPrintClient.registerPluginComponent("logging", OctoPrintLoggingClient); - - // also register deprecated client under old endpoint - OctoPrintClient.registerComponent("logs", DeprecatedOctoPrintLogsClient); - - return OctoPrintLoggingClient; -}); - $(function() { function LoggingViewModel(parameters) { var self = this; @@ -78,6 +9,8 @@ $(function() { self.configuredLoggers = ko.observableArray(); self.configuredLoggersChanged = false; + self.markedForDeletion = ko.observableArray([]); + self.availableLoggersSorted = ko.computed(function() { return _.sortBy(self.availableLoggers()); }); @@ -183,8 +116,37 @@ $(function() { }; self.removeFile = function(filename) { - OctoPrint.plugins.logging.deleteLog(filename) - .done(self.requestData); + var perform = function() { + OctoPrint.plugins.logging.deleteLog(filename) + .done(self.requestData); + }; + + showConfirmationDialog(_.sprintf(gettext("You are about to delete log file \"%(name)s\"."), {name: _.escape(filename)}), + perform); + }; + + self.markFilesOnPage = function() { + self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.listHelper.paginatedItems(), "name")))); + }; + + self.markAllFiles = function() { + self.markedForDeletion(_.map(self.listHelper.allItems, "name")); + }; + + self.clearMarkedFiles = function() { + self.markedForDeletion.removeAll(); + }; + + self.removeMarkedFiles = function() { + var perform = function() { + self._bulkRemove(self.markedForDeletion(), "files") + .done(function() { + self.markedForDeletion.removeAll(); + }); + }; + + showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d log files."), {count: self.markedForDeletion().length}), + perform); }; self.onSettingsShown = function() { @@ -203,6 +165,47 @@ $(function() { console.log("ConfiguredLoggers has not changed. Not saving."); } }; + + self._bulkRemove = function(files) { + var title = gettext("Deleting log files"); + var message = _.sprintf(gettext("Deleting %(count)d log files..."), {count: files.length}); + var handler = function(filename) { + return OctoPrint.plugins.logging.deleteLog(filename) + .done(function() { + deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: _.escape(filename)}), true); + }) + .fail(function(jqXHR) { + var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: _.escape(filename)}); + var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: _.escape(filename), error: _.escape(jqXHR.responseText)}); + deferred.notify(short, long, false); + }); + }; + + var deferred = $.Deferred(); + + var promise = deferred.promise(); + + var options = { + title: title, + message: message, + max: files.length, + output: true + }; + showProgressModal(options, promise); + + var requests = []; + _.each(files, function(filename) { + var request = handler(filename); + requests.push(request) + }); + $.when.apply($, _.map(requests, wrapPromiseWithAlways)) + .done(function() { + deferred.resolve(); + self.requestData(); + }); + + return promise; + }; } OCTOPRINT_VIEWMODELS.push({ diff --git a/src/octoprint/plugins/logging/static/less/logging.less b/src/octoprint/plugins/logging/static/less/logging.less index dfcb1c1f7..ac8b34dac 100644 --- a/src/octoprint/plugins/logging/static/less/logging.less +++ b/src/octoprint/plugins/logging/static/less/logging.less @@ -1,5 +1,14 @@ table { th, td { + &.settings_logs_checkbox { + text-align: center; + width: 10px; + + input[type="checkbox"] { + margin-top: 0; + } + } + &.settings_logs_name { text-overflow: ellipsis; text-align: left; diff --git a/src/octoprint/plugins/logging/templates/logging_settings.jinja2 b/src/octoprint/plugins/logging/templates/logging_settings.jinja2 index 7a082ec6b..56353a20c 100644 --- a/src/octoprint/plugins/logging/templates/logging_settings.jinja2 +++ b/src/octoprint/plugins/logging/templates/logging_settings.jinja2 @@ -1,13 +1,31 @@

{{ _('Logs') }}

+ + @@ -16,6 +34,7 @@ + @@ -65,7 +84,7 @@
- +
@@ -84,7 +103,7 @@
- +
diff --git a/src/octoprint/plugins/pi_support/__init__.py b/src/octoprint/plugins/pi_support/__init__.py index e0bd9ac10..4a2820cba 100644 --- a/src/octoprint/plugins/pi_support/__init__.py +++ b/src/octoprint/plugins/pi_support/__init__.py @@ -1,10 +1,11 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import flask +import io import os import sarge @@ -12,19 +13,29 @@ from flask_babel import gettext from octoprint.util import RepeatedTimer import octoprint.plugin +import octoprint.events _PROC_DT_MODEL_PATH = "/proc/device-tree/model" _OCTOPI_VERSION_PATH = "/etc/octopi_version" _VCGENCMD_THROTTLE = "/usr/bin/vcgencmd get_throttled" -### uncomment for local debugging -#import sys -#base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes")) -#_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt") -#_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt") -#_VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py")) -#import itertools -#_VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70000")) +_CHECK_INTERVAL_OK = 300 +_CHECK_INTERVAL_THROTTLED = 30 + +__LOCAL_DEBUG = False + +if __LOCAL_DEBUG: + ### mocks & settings for local debugging + import sys + base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes")) + _PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt") + _OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt") + _VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py")) + import itertools + _VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70005")) + + _CHECK_INTERVAL_OK = 10 + _CHECK_INTERVAL_THROTTLED = 5 # see https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=147781&start=50#p972790 @@ -35,10 +46,9 @@ _FLAG_PAST_UNDERVOLTAGE = 1 << 16 _FLAG_PAST_FREQ_CAPPED = 1 << 17 _FLAG_PAST_THROTTLED = 1 << 18 - class ThrottleState(object): @classmethod - def from_value(cls, value): + def from_value(cls, value=0): if value == 0: return ThrottleState() @@ -47,10 +57,12 @@ class ThrottleState(object): throttled=_FLAG_THROTTLED & value == _FLAG_THROTTLED, past_undervoltage=_FLAG_PAST_UNDERVOLTAGE & value == _FLAG_PAST_UNDERVOLTAGE, past_freq_capped=_FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED, - past_throttled=_FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED) + past_throttled=_FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED, + raw_value=value) return ThrottleState(**kwargs) def __init__(self, **kwargs): + self._raw_value = kwargs.get('raw_value', -1) self._undervoltage = False self._freq_capped = False self._throttled = False @@ -111,7 +123,8 @@ class ThrottleState(object): and self._past_throttled == other._past_throttled def as_dict(self): - return dict(current_undervoltage=self.current_undervoltage, + return dict(raw_value=self._raw_value, + current_undervoltage=self.current_undervoltage, past_undervoltage=self.past_undervoltage, current_overheat=self.current_overheat, past_overheat=self.past_overheat, @@ -124,15 +137,18 @@ def get_proc_dt_model(): global _proc_dt_model if _proc_dt_model is None: - with open(_PROC_DT_MODEL_PATH, "r") as f: + with io.open(_PROC_DT_MODEL_PATH, 'rt', encoding='utf-8') as f: _proc_dt_model = f.readline().strip(" \t\r\n\0") return _proc_dt_model def get_vcgencmd_throttled_state(command): - output = sarge.get_stdout(command) - #output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # for local debugging + if __LOCAL_DEBUG: + output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # mock for local debugging + else: + output = sarge.get_stdout(command) + if not "throttled=0x" in output: raise ValueError("cannot parse \"{}\" output: {}".format(command, output)) @@ -150,7 +166,7 @@ def get_octopi_version(): global _octopi_version if _octopi_version is None: - with open(_OCTOPI_VERSION_PATH, "r") as f: + with io.open(_OCTOPI_VERSION_PATH, 'rt', encoding='utf-8') as f: _octopi_version = f.readline().strip(" \t\r\n\0") return _octopi_version @@ -193,6 +209,7 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin, def get_assets(self): return dict( js=["js/pi_support.js"], + clientjs=["clientjs/pi_support.js"], css=["css/pi_support.css"] ) @@ -232,23 +249,31 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin, def _check_throttled_state_interval(self): if self._throttle_state.current_issue: - # check state every 30s if something's currently amiss - return 30 + return _CHECK_INTERVAL_THROTTLED else: - # check state every 5min if nothing's currently amiss - return 300 + return _CHECK_INTERVAL_OK def _check_throttled_state_condition(self): return self._throttle_functional + def get_throttle_state(self, run_now=False): + """Exposed as public helper.""" + if run_now: + self._check_throttled_state() + + if not self._throttle_functional: + return False + + return self._throttle_state.as_dict() + def _check_throttled_state(self): command = self._settings.get(["vcgencmd_throttle_check_command"]) self._logger.debug("Retrieving throttle state via \"{}\"".format(command)) try: state = get_vcgencmd_throttled_state(command) - except: - self._logger.exception("Got an error while trying to fetch the current throttle state via \"{}\"".format(command)) + except ValueError: + self._logger.warning("Fetching the current throttle state via \"{}\" doesn't work".format(command)) self._throttle_functional = False return @@ -273,17 +298,24 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin, message += "\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's " \ "CPU and GPU." - self._logger.warn(message) + self._logger.warning(message) self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state", state=self._throttle_state.as_dict())) + # noinspection PyUnresolvedReferences + self._event_bus.fire(octoprint.events.Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE, self._throttle_state.as_dict()) + + +def register_custom_events(*args, **kwargs): + return ["throttle_state",] + __plugin_name__ = "Pi Support Plugin" __plugin_author__ = "Gina Häußge" __plugin_description__ = "Provides additional information about your Pi in the UI." __plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to " - "provide additional information about your Pi," + "provide additional information about your Pi, " "which will make it more tricky to help you if you need support.") __plugin_license__ = "AGPLv3" @@ -292,11 +324,20 @@ def __plugin_check__(): proc_dt_model = get_proc_dt_model() if proc_dt_model is None: return False - except: + except Exception: return False return "raspberry pi" in proc_dt_model.lower() def __plugin_load__(): + plugin = PiSupportPlugin() global __plugin_implementation__ - __plugin_implementation__ = PiSupportPlugin() + __plugin_implementation__ = plugin + + global __plugin_hooks__ + __plugin_hooks__ = { + "octoprint.events.register_custom_events": register_custom_events + } + + global __plugin_helpers__ + __plugin_helpers__ = dict(get_throttled=plugin.get_throttle_state) diff --git a/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js b/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js new file mode 100644 index 000000000..7c216aa0f --- /dev/null +++ b/src/octoprint/plugins/pi_support/static/clientjs/pi_support.js @@ -0,0 +1,19 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintPiSupportClient = function(base) { + this.base = base; + }; + + OctoPrintPiSupportClient.prototype.get = function(opts) { + return this.base.get(this.base.getSimpleApiUrl("pi_support")); + }; + + OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient); + return OctoPrintPiSupportClient; +}); + diff --git a/src/octoprint/plugins/pi_support/static/js/pi_support.js b/src/octoprint/plugins/pi_support/static/js/pi_support.js index ced2a55e4..e4b08b8e5 100644 --- a/src/octoprint/plugins/pi_support/static/js/pi_support.js +++ b/src/octoprint/plugins/pi_support/static/js/pi_support.js @@ -1,22 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintPiSupportClient = function(base) { - this.base = base; - }; - - OctoPrintPiSupportClient.prototype.get = function(opts) { - return this.base.get(this.base.getSimpleApiUrl("pi_support")); - }; - - OctoPrintClient.registerPluginComponent("pi_support", OctoPrintPiSupportClient); - return OctoPrintPiSupportClient; -}); - $(function() { function PiSupportViewModel(parameters) { @@ -46,7 +27,7 @@ $(function() { var octoPrintVersion = $(".footer span.version"); var octoPiVersion = $(" " + gettext("running on") + " " + gettext("OctoPi") - + " " + response.octopi_version + "") + + " " + response.octopi_version + ""); $(octoPiVersion).insertAfter(octoPrintVersion); }) }; @@ -60,11 +41,34 @@ $(function() { self.pastIssue(state.past_issue); }; - self.issuePopoverContent = function() { - return "

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

" - + "

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

" - + "

" + gettext("A blinking icon indicates an acute issue!") + "

" - }; + self.popoverContent = ko.pureComputed(function() { + var undervoltageParagraphClasses = "muted"; + var undervoltageSymbolClasses = ""; + + var overheatParagraphClasses = "muted"; + var overheatSymbolClasses = ""; + + if (self.currentUndervoltage()) { + undervoltageSymbolClasses = "text-error pi_support_state_pulsate"; + undervoltageParagraphClasses = ""; + } else if (self.pastUndervoltage()) { + undervoltageSymbolClasses = "text-error"; + undervoltageParagraphClasses = ""; + } + + if (self.currentOverheat()) { + overheatSymbolClasses = "text-error pi_support_state_pulsate"; + overheatParagraphClasses = ""; + } else if (self.pastOverheat()) { + overheatSymbolClasses = "text-error"; + overheatParagraphClasses = ""; + } + + return "

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

" + + "

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

" + + "

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

" + + "

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

"; + }); self.onStartup = function() { self.requestData(); diff --git a/src/octoprint/plugins/pi_support/templates/pi_support_navbar.jinja2 b/src/octoprint/plugins/pi_support/templates/pi_support_navbar.jinja2 index d74c76b54..c2c5f9401 100644 --- a/src/octoprint/plugins/pi_support/templates/pi_support_navbar.jinja2 +++ b/src/octoprint/plugins/pi_support/templates/pi_support_navbar.jinja2 @@ -1,4 +1,4 @@ - - - + + + diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 41cb6d004..534464d1e 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -1,5 +1,5 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -11,15 +11,19 @@ import octoprint.plugin import octoprint.plugin.core from octoprint.settings import valid_boolean_trues -from octoprint.server.util.flask import require_firstrun, with_revalidation_checking, check_etag +from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag +from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions +from octoprint.util import to_bytes from octoprint.util.pip import LocalPipCaller -from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible -from octoprint.util.platform import get_os +from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible, is_python_compatible +from octoprint.util.platform import get_os, is_os_compatible +from octoprint.events import Events from flask import jsonify, make_response from flask_babel import gettext +import io import logging import sarge import sys @@ -27,12 +31,52 @@ import requests import re import os import copy -import dateutil.parser import time import threading +from datetime import datetime + _DATA_FORMAT_VERSION = "v2" + +def map_repository_entry(entry): + if not isinstance(entry, dict): + return None + + result = copy.deepcopy(entry) + + if not "follow_dependency_links" in result: + result["follow_dependency_links"] = False + + result["is_compatible"] = dict( + octoprint=True, + os=True, + python=True + ) + + if "compatibility" in entry: + if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance( + entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]): + result["is_compatible"]["octoprint"] = is_octoprint_compatible(*entry["compatibility"]["octoprint"]) + + if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance( + entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]): + result["is_compatible"]["os"] = is_os_compatible(entry["compatibility"]["os"]) + + if "python" in entry["compatibility"] and entry["compatibility"]["python"] is not None and isinstance(entry["compatibility"]["python"], basestring): + result["is_compatible"]["python"] = is_python_compatible(entry["compatibility"]["python"]) + else: + # we default to only assume py2 compatiblity for now + result["is_compatible"]["python"] = is_python_compatible(">=2.7,<3") + + return result + + +already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)" +success_string = "Successfully installed" +failure_string = "Could not install" + + class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.AssetPlugin, @@ -72,20 +116,26 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._repository_plugins = [] self._repository_cache_path = None self._repository_cache_ttl = 0 + self._repository_mtime = None self._notices = dict() self._notices_available = False self._notices_cache_path = None self._notices_cache_ttl = 0 + self._notices_mtime = None self._console_logger = None + self._get_throttled = lambda: False + def initialize(self): self._console_logger = logging.getLogger("octoprint.plugins.pluginmanager.console") self._repository_cache_path = os.path.join(self.get_plugin_data_folder(), "plugins.json") self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60 self._notices_cache_path = os.path.join(self.get_plugin_data_folder(), "notices.json") self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60 + self._confirm_uninstall = self._settings.global_get_boolean(["confirm_uninstall"]) + self._confirm_disable = self._settings.global_get_boolean(["confirm_disable"]) self._pip_caller = LocalPipCaller(force_user=self._settings.get_boolean(["pip_force_user"])) self._pip_caller.on_log_call = self._log_call @@ -105,10 +155,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, dict(key="MANAGE", name="Manage plugins", description=gettext("Allows to enable, disable and uninstall installed plugins."), + default_groups=[ADMIN_GROUP], roles=["manage"]), dict(key="INSTALL", name="Install new plugins", description=gettext("Allows to install new plugins. Includes the \"Manage plugins\" permission."), + default_groups=[ADMIN_GROUP], roles=["install"], permissions=["PLUGIN_PLUGINMANAGER_MANAGE"], dangerous=True) @@ -126,6 +178,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._console_logger.setLevel(logging.DEBUG) self._console_logger.propagate = False + helpers = self._plugin_manager.get_helpers("pi_support", "get_throttled") + if helpers and "get_throttled" in helpers: + self._get_throttled = helpers["get_throttled"] + if self._settings.get_boolean(["ignore_throttled"]): + self._logger.warn("!!! THROTTLE STATE IGNORED !!! You have configured the Plugin Manager plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it.") + # decouple repository fetching from server startup self._fetch_all_data(do_async=True) @@ -139,8 +197,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, notices_ttl=6*60, pip_args=None, pip_force_user=False, + confirm_uninstall=True, + confirm_disable=False, dependency_links=False, - hidden=[] + hidden=[], + ignore_throttled=False ) def on_settings_save(self, data): @@ -149,12 +210,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60 self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60 self._pip_caller.force_user = self._settings.get_boolean(["pip_force_user"]) + self._confirm_uninstall = self._settings.global_get_boolean(["confirm_uninstall"]) + self._confirm_disable = self._settings.global_get_boolean(["confirm_disable"]) ##~~ AssetPlugin def get_assets(self): return dict( js=["js/pluginmanager.js"], + clientjs=["clientjs/pluginmanager.js"], css=["css/pluginmanager.css"], less=["less/pluginmanager.less"] ) @@ -183,7 +247,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, ##~~ BlueprintPlugin @octoprint.plugin.BlueprintPlugin.route("/upload_archive", methods=["POST"]) - @require_firstrun + @no_firstrun_access @Permissions.PLUGIN_PLUGINMANAGER_INSTALL.require(403) def upload_archive(self): import flask @@ -216,7 +280,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, try: os.remove(archive.name) except Exception as e: - self._logger.warn("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e))) + self._logger.warning("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e))) ##~~ EventHandlerPlugin @@ -244,11 +308,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, from octoprint.server import safe_mode refresh_repository = request.values.get("refresh_repository", "false") in valid_boolean_trues - if refresh_repository: + if refresh_repository or not self._is_repository_cache_valid(): self._repository_available = self._refresh_repository() refresh_notices = request.values.get("refresh_notices", "false") in valid_boolean_trues - if refresh_notices: + if refresh_notices or not self._is_notices_cache_valid(): self._notices_available = self._refresh_notices() def view(): @@ -274,14 +338,18 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def etag(): import hashlib hash = hashlib.sha1() - hash.update(repr(self._get_plugins())) - hash.update(str(self._repository_available)) - hash.update(repr(self._repository_plugins)) - hash.update(str(self._notices_available)) - hash.update(repr(self._notices)) - hash.update(repr(safe_mode)) - hash.update(repr(self._connectivity_checker.online)) - hash.update(repr(_DATA_FORMAT_VERSION)) + def hash_update(value): + value = value.encode('utf-8') + hash.update(value) + + hash_update(repr(self._get_plugins())) + hash_update(str(self._repository_available)) + hash_update(repr(self._repository_plugins)) + hash_update(str(self._notices_available)) + hash_update(repr(self._notices)) + hash_update(repr(safe_mode)) + hash_update(repr(self._connectivity_checker.online)) + hash_update(repr(_DATA_FORMAT_VERSION)) return hash.hexdigest() def condition(): @@ -327,6 +395,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return self.command_toggle(plugin, command) def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False): + throttled = self._get_throttled() + if throttled and isinstance(throttled, dict) and throttled.get("current_issue", False) and not self._settings.get_boolean(["ignore_throttled"]): + # currently throttled, we refuse to run + return make_response("System is currently throttled, refusing to install " + "anything due to possible stability issues", 409) + if url is not None: if not any(map(lambda scheme: url.startswith(scheme + "://"), self.URL_SCHEMES)): raise ValueError("Invalid URL to pip install from") @@ -351,17 +425,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, raise ValueError("Either URL or path must be provided") self._logger.info("Installing plugin from {}".format(source)) - pip_args = ["install", sarge.shell_quote(source), '--no-cache-dir'] + pip_args = ["--disable-pip-version-check", "install", sarge.shell_quote(source), "--no-cache-dir"] if dependency_links or self._settings.get_boolean(["dependency_links"]): pip_args.append("--process-dependency-links") all_plugins_before = self._plugin_manager.find_plugins(existing=dict()) - already_installed_string = "Requirement already satisfied (use --upgrade to upgrade)" - success_string = "Successfully installed" - failure_string = "Could not install" - try: returncode, stdout, stderr = self._call_pip(pip_args) @@ -383,7 +453,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._logger.info("Plugin to be installed from {} was already installed, forcing a reinstall".format(source)) self._log_message("Looks like the plugin was already installed. Forcing a reinstall.") force = True - except: + except Exception: self._logger.exception("Could not install plugin from %s" % url) return make_response("Could not install plugin from URL, see the log for more details", 500) else: @@ -393,7 +463,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"] try: returncode, stdout, stderr = self._call_pip(pip_args) - except: + except Exception: self._logger.exception("Could not install plugin from {}".format(source)) return make_response("Could not install plugin from source {}, see the log for more details" .format(source), 500) @@ -448,7 +518,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, new_plugin = self._find_installed_plugin(installed, plugins=all_plugins_after) if new_plugin is None: - self._logger.warn("The plugin was installed successfully, but couldn't be found afterwards to " + self._logger.warning("The plugin was installed successfully, but couldn't be found afterwards to " "initialize properly during runtime. Please restart OctoPrint.") result = dict(result=True, source=source, @@ -477,10 +547,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.log_all_plugins() self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version)) - self._event_bus.fire("plugin_pluginmanager_installplugin", dict(id=new_plugin.key, - version=new_plugin.version, - source=source, - source_type=source_type)) + + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, dict(id=new_plugin.key, + version=new_plugin.version, + source=source, + source_type=source_type)) result = dict(result=True, source=source, @@ -504,7 +576,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return make_response("Bundled plugins cannot be uninstalled", 403) if plugin.origin is None: - self._logger.warn(u"Trying to uninstall plugin {plugin} but origin is unknown".format(**locals())) + self._logger.warning("Trying to uninstall plugin {plugin} but origin is unknown".format(**locals())) return make_response("Could not uninstall plugin, its origin is unknown") if plugin.origin.type == "entry_point": @@ -513,11 +585,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if origin is None: origin = plugin.origin[2] - pip_args = ["uninstall", "--yes", origin] + pip_args = ["--disable-pip-version-check", "uninstall", "--yes", origin] try: self._call_pip(pip_args) - except: - self._logger.exception(u"Could not uninstall plugin via pip") + except Exception: + self._logger.exception("Could not uninstall plugin via pip") return make_response("Could not uninstall plugin via pip, see the log for more details", 500) elif plugin.origin.type == "folder": @@ -527,10 +599,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if os.path.isdir(full_path): # plugin is installed via a plugin folder, need to use rmtree to get rid of it - self._log_stdout(u"Deleting plugin from {folder}".format(folder=plugin.location)) + self._log_stdout("Deleting plugin from {folder}".format(folder=plugin.location)) shutil.rmtree(full_path) elif os.path.isfile(full_path): - self._log_stdout(u"Deleting plugin from {file}".format(file=plugin.location)) + self._log_stdout("Deleting plugin from {file}".format(file=plugin.location)) os.remove(full_path) if full_path.endswith(".py"): @@ -539,7 +611,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, os.remove(pyc_file) else: - self._logger.warn(u"Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals())) + self._logger.warning("Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals())) return make_response("Could not uninstall plugin, its origin is unknown") needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) @@ -556,7 +628,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if plugin.enabled: self._plugin_manager.disable_plugin(plugin.key, plugin=plugin) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception(u"Problem disabling plugin {name}".format(name=plugin.key)) + self._logger.exception("Problem disabling plugin {name}".format(name=plugin.key)) result = dict(result=False, uninstalled=True, disabled=False, unloaded=False, reason=e.reason) self._send_result_notification("uninstall", result) return jsonify(result) @@ -565,15 +637,16 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if plugin.loaded: self._plugin_manager.unload_plugin(plugin.key) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception(u"Problem unloading plugin {name}".format(name=plugin.key)) + self._logger.exception("Problem unloading plugin {name}".format(name=plugin.key)) result = dict(result=False, uninstalled=True, disabled=True, unloaded=False, reason=e.reason) self._send_result_notification("uninstall", result) return jsonify(result) self._plugin_manager.reload_plugins() - self._event_bus.fire("plugin_pluginmanager_uninstallplugin", dict(id=plugin.key, - version=plugin.version)) + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN, dict(id=plugin.key, + version=plugin.version)) result = dict(result=True, needs_restart=needs_restart, @@ -604,7 +677,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif command == "enable": self._mark_plugin_enabled(plugin, needs_restart=needs_restart) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception(u"Problem toggling enabled state of {name}: {reason}".format(name=plugin.key, reason=e.reason)) + self._logger.exception("Problem toggling enabled state of {name}: {reason}".format(name=plugin.key, reason=e.reason)) result = dict(result=False, reason=e.reason) except octoprint.plugin.core.PluginNeedsRestart: result = dict(result=True, @@ -659,10 +732,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def _call_pip(self, args): if self._pip_caller is None or not self._pip_caller.available: - raise RuntimeError(u"No pip available, can't operate".format(**locals())) + raise RuntimeError("No pip available, can't operate".format(**locals())) if "--process-dependency-links" in args: - self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version") + self._log_message("Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version") additional_args = self._settings.get(["pip_args"]) @@ -675,19 +748,21 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if additional_args: args.append(additional_args) - return self._pip_caller.execute(*args) + kwargs = dict(env=dict(PYTHONWARNINGS="ignore:DEPRECATION::pip._internal.cli.base_command")) + + return self._pip_caller.execute(*args, **kwargs) def _log_message(self, *lines): - self._log(lines, prefix=u"*", stream="message") + self._log(lines, prefix="*", stream="message") def _log_call(self, *lines): - self._log(lines, prefix=u" ", stream="call") + self._log(lines, prefix=" ", stream="call") def _log_stdout(self, *lines): - self._log(lines, prefix=u">", stream="stdout") + self._log(lines, prefix=">", stream="stdout") def _log_stderr(self, *lines): - self._log(lines, prefix=u"!", stream="stderr") + self._log(lines, prefix="!", stream="stderr") def _log(self, lines, prefix=None, stream=None, strip=True): if strip: @@ -696,7 +771,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.send_plugin_message(self._identifier, dict(type="loglines", loglines=[dict(line=line, stream=stream) for line in lines])) for line in lines: - self._console_logger.debug(u"{prefix} {line}".format(**locals())) + self._console_logger.debug("{prefix} {line}".format(**locals())) def _mark_plugin_enabled(self, plugin, needs_restart=False): disabled_list = list(self._settings.global_get(["plugins", "_disabled"], @@ -715,8 +790,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif not plugin.enabled and plugin.key not in self._pending_enable: self._pending_enable.add(plugin.key) - self._event_bus.fire("plugin_pluginmanager_enableplugin", dict(id=plugin.key, - version=plugin.version)) + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, dict(id=plugin.key, + version=plugin.version)) def _mark_plugin_disabled(self, plugin, needs_restart=False): disabled_list = list(self._settings.global_get(["plugins", "_disabled"], @@ -735,8 +811,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif (plugin.enabled or plugin.forced_disabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key not in self._pending_disable: self._pending_disable.add(plugin.key) - self._event_bus.fire("plugin_pluginmanager_disableplugin", dict(id=plugin.key, - version=plugin.version)) + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN, dict(id=plugin.key, + version=plugin.version)) def _fetch_all_data(self, do_async=False): def run(): @@ -750,18 +827,25 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, else: run() + def _is_repository_cache_valid(self, mtime=None): + import time + if mtime is None: + mtime = self._repository_mtime + return mtime + self._repository_cache_ttl >= time.time() > mtime + def _fetch_repository_from_disk(self): repo_data = None if os.path.isfile(self._repository_cache_path): import time mtime = os.path.getmtime(self._repository_cache_path) - if mtime + self._repository_cache_ttl >= time.time() > mtime: + if self._is_repository_cache_valid(mtime=mtime): try: import json - with open(self._repository_cache_path) as f: + with io.open(self._repository_cache_path, 'rt', encoding='utf-8') as f: repo_data = json.load(f) + self._repository_mtime = mtime self._logger.info("Loaded plugin repository data from disk, was still valid") - except: + except Exception: self._logger.exception("Error while loading repository data from {}".format(self._repository_cache_path)) return self._refresh_repository(repo_data=repo_data) @@ -777,17 +861,27 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, r.raise_for_status() self._logger.info("Loaded plugin repository data from {}".format(repository_url)) except Exception as e: - self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=str(e))) + self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=e)) return None - repo_data = r.json() + try: + repo_data = r.json() + except Exception as e: + self._logger.exception("Error while reading repository data: {}".format(e)) + return None + + # validation + if not isinstance(repo_data, (list, tuple)): + self._logger.warn("Invalid repository data: expected a list, got {!r}".format(repo_data)) + return None try: import json - with octoprint.util.atomic_write(self._repository_cache_path, "wb") as f: - json.dump(repo_data, f) + with octoprint.util.atomic_write(self._repository_cache_path, mode='wb') as f: + f.write(to_bytes(json.dumps(repo_data))) + self._repository_mtime = os.path.getmtime(self._repository_cache_path) except Exception as e: - self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e))) + self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, e)) return repo_data @@ -797,45 +891,29 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if repo_data is None: return False - current_os = get_os() - octoprint_version = get_octoprint_version(base=True) - - def map_repository_entry(entry): - result = copy.deepcopy(entry) - - if not "follow_dependency_links" in result: - result["follow_dependency_links"] = False - - result["is_compatible"] = dict( - octoprint=True, - os=True - ) - - if "compatibility" in entry: - if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]): - result["is_compatible"]["octoprint"] = is_octoprint_compatible(*entry["compatibility"]["octoprint"], - octoprint_version=octoprint_version) - - if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]): - result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"]) - - return result - - self._repository_plugins = list(map(map_repository_entry, repo_data)) + self._repository_plugins = list(filter(lambda x: x is not None, + map(map_repository_entry, repo_data))) return True + def _is_notices_cache_valid(self, mtime=None): + import time + if mtime is None: + mtime = self._notices_mtime + return mtime + self._notices_cache_ttl >= time.time() > mtime + def _fetch_notices_from_disk(self): notice_data = None if os.path.isfile(self._notices_cache_path): import time mtime = os.path.getmtime(self._notices_cache_path) - if mtime + self._notices_cache_ttl >= time.time() > mtime: + if self._is_notices_cache_valid(mtime=mtime): try: import json - with open(self._notices_cache_path) as f: + with io.open(self._notices_cache_path, 'rt', encoding='utf-8') as f: notice_data = json.load(f) + self._notices_mtime = mtime self._logger.info("Loaded notice data from disk, was still valid") - except: + except Exception: self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path)) return self._refresh_notices(notice_data=notice_data) @@ -858,8 +936,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, try: import json - with octoprint.util.atomic_write(self._notices_cache_path, "wb") as f: - json.dump(notice_data, f) + with octoprint.util.atomic_write(self._notices_cache_path, mode="wb") as f: + f.write(to_bytes(json.dumps(notice_data))) + self._notices_mtime = os.path.getmtime(self._notices_cache_path) except Exception as e: self._logger.exception("Error while saving notices to {}: {}".format(self._notices_cache_path, str(e))) return notice_data @@ -878,10 +957,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, key = notice["plugin"] try: - parsed_date = dateutil.parser.parse(notice["date"]) + # Jekyll turns "%Y-%m-%d %H:%M:%SZ" into "%Y-%m-%d %H:%M:%S +0000", so be sure to ignore "+0000" + # + # Being able to use dateutil here would make things way easier but sadly that can no longer get + # installed (from source) under OctoPi 0.14 due to its setuptools-scm dependency, so we have to do + # without it for now until we can drop support for OctoPi 0.14. + parsed_date = datetime.strptime(notice["date"], "%Y-%m-%d %H:%M:%S +0000") notice["timestamp"] = parsed_date.timetuple() except Exception as e: - self._logger.warn("Error while parsing date {!r} for plugin notice " + self._logger.warning("Error while parsing date {!r} for plugin notice " "of plugin {}, ignoring notice: {}".format(notice["date"], key, str(e))) continue @@ -892,30 +976,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._notices = notices return True - @staticmethod - def _is_os_compatible(current_os, compatibility_entries): - """ - Tests if the ``current_os`` or ``sys.platform`` are blacklisted or whitelisted in ``compatibility_entries`` - """ - if len(compatibility_entries) == 0: - # shortcut - no compatibility info means we are compatible - return True - - negative_entries = map(lambda x: x[1:], filter(lambda x: x.startswith("!"), compatibility_entries)) - positive_entries = filter(lambda x: not x.startswith("!"), compatibility_entries) - - negative_match = False - if negative_entries: - # check if we are blacklisted - negative_match = current_os in negative_entries or any(map(lambda x: sys.platform.startswith(x), negative_entries)) - - positive_match = True - if positive_entries: - # check if we are whitelisted - positive_match = current_os in positive_entries or any(map(lambda x: sys.platform.startswith(x), positive_entries)) - - return positive_match and not negative_match - @property def _reconnect_hooks(self): reconnect_hooks = self.__class__.RECONNECT_HOOKS @@ -926,9 +986,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, result = hook() if isinstance(result, (list, tuple)): reconnect_hooks.extend(filter(lambda x: isinstance(x, basestring), result)) - except: + except Exception: self._logger.exception("Error while retrieving additional hooks for which a " - "reconnect is required from plugin {name}".format(**locals())) + "reconnect is required from plugin {name}".format(**locals()), + extra=dict(plugin=name)) return reconnect_hooks @@ -1002,6 +1063,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, important=notification.get("important", False)) +def _register_custom_events(*args, **kwargs): + return ["install_plugin", "uninstall_plugin", "enable_plugin", "disable_plugin"] + __plugin_name__ = "Plugin Manager" __plugin_author__ = "Gina Häußge" @@ -1017,5 +1081,6 @@ def __plugin_load__(): __plugin_hooks__ = { "octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize, "octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types, + "octoprint.events.register_custom_events": _register_custom_events, "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions } diff --git a/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js new file mode 100644 index 000000000..acaaf3590 --- /dev/null +++ b/src/octoprint/plugins/pluginmanager/static/clientjs/pluginmanager.js @@ -0,0 +1,82 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintPluginManagerClient = function(base) { + this.base = base; + }; + + OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) { + var refresh_repo, refresh_notices; + if (_.isPlainObject(refresh)) { + refresh_repo = refresh.repo || false; + refresh_notices = refresh.notices || false; + } else { + refresh_repo = refresh; + refresh_notices = false; + } + + var query = []; + if (refresh_repo) query.push("refresh_repository=true"); + if (refresh_notices) query.push("refresh_notices=true"); + + return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts); + }; + + OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) { + return this.get(true, opts); + }; + + OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function(opts) { + return this.get(false, opts); + }; + + OctoPrintPluginManagerClient.prototype.install = function(pluginUrl, dependencyLinks, opts) { + var data = { + url: pluginUrl, + dependency_links: !!dependencyLinks + }; + return this.base.simpleApiCommand("pluginmanager", "install", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) { + var data = { + url: pluginUrl, + dependency_links: !!dependencyLinks, + reinstall: plugin, + force: true + }; + return this.base.simpleApiCommand("pluginmanager", "install", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) { + var data = { + plugin: plugin + }; + return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) { + var data = { + plugin: plugin + }; + return this.base.simpleApiCommand("pluginmanager", "enable", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) { + var data = { + plugin: plugin + }; + return this.base.simpleApiCommand("pluginmanager", "disable", data, opts); + }; + + OctoPrintPluginManagerClient.prototype.upload = function(file) { + return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file); + }; + + OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient); + return OctoPrintPluginManagerClient; +}); diff --git a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css index f34d4e990..b6479776c 100644 --- a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css +++ b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css @@ -1 +1 @@ -table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009} \ No newline at end of file +#settings_plugin_pluginmanager .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009} \ No newline at end of file diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index ba8291d03..26a0bc338 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -1,86 +1,3 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintPluginManagerClient = function(base) { - this.base = base; - }; - - OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) { - var refresh_repo, refresh_notices; - if (_.isPlainObject(refresh)) { - refresh_repo = refresh.repo || false; - refresh_notices = refresh.notices || false; - } else { - refresh_repo = refresh; - refresh_notices = false; - } - - var query = []; - if (refresh_repo) query.push("refresh_repository=true"); - if (refresh_notices) query.push("refresh_notices=true"); - - return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts); - }; - - OctoPrintPluginManagerClient.prototype.getWithRefresh = function(opts) { - return this.get(true, opts); - }; - - OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function(opts) { - return this.get(false, opts); - }; - - OctoPrintPluginManagerClient.prototype.install = function(pluginUrl, dependencyLinks, opts) { - var data = { - url: pluginUrl, - dependency_links: !!dependencyLinks - }; - return this.base.simpleApiCommand("pluginmanager", "install", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) { - var data = { - url: pluginUrl, - dependency_links: !!dependencyLinks, - reinstall: plugin, - force: true - }; - return this.base.simpleApiCommand("pluginmanager", "install", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) { - var data = { - plugin: plugin - }; - return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) { - var data = { - plugin: plugin - }; - return this.base.simpleApiCommand("pluginmanager", "enable", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.disable = function(plugin, opts) { - var data = { - plugin: plugin - }; - return this.base.simpleApiCommand("pluginmanager", "disable", data, opts); - }; - - OctoPrintPluginManagerClient.prototype.upload = function(file) { - return this.base.upload(this.base.getBlueprintUrl("pluginmanager") + "upload_archive", file); - }; - - OctoPrintClient.registerPluginComponent("pluginmanager", OctoPrintPluginManagerClient); - return OctoPrintPluginManagerClient; -}); - $(function() { function PluginManagerViewModel(parameters) { var self = this; @@ -91,12 +8,17 @@ $(function() { self.systemViewModel = parameters[3]; self.access = parameters[4]; + // optional + self.piSupport = parameters[5]; + self.config_repositoryUrl = ko.observable(); self.config_repositoryTtl = ko.observable(); self.config_noticesUrl = ko.observable(); self.config_noticesTtl = ko.observable(); self.config_pipAdditionalArgs = ko.observable(); self.config_pipForceUser = ko.observable(); + self.config_confirmUninstall = ko.observable(); + self.config_confirmDisable = ko.observable(); self.configurationDialog = $("#settings_plugin_pluginmanager_configurationdialog"); @@ -111,11 +33,23 @@ $(function() { } }, { + "bundled": function(item) { + return item.bundled; + }, + "3rdparty": function(item) { + return !item.bundled; + }, + "enabled": function(item) { + return item.enabled; + }, + "disabled": function(item) { + return !item.enabled; + } }, "name", [], - [], - 5 + [["bundled", "3rdparty"], ["enabled", "disabled"]], + 0 ); self.repositoryplugins = new ItemListHelper( @@ -139,7 +73,7 @@ $(function() { return !self.installed(plugin); }, "filter_incompatible": function(plugin) { - return plugin.is_compatible.octoprint && plugin.is_compatible.os; + return plugin.is_compatible.octoprint && plugin.is_compatible.os && plugin.is_compatible.python; } }, "title", @@ -158,6 +92,11 @@ $(function() { self.performRepositorySearch(); }); + self.listingSearchQuery = ko.observable(); + self.listingSearchQuery.subscribe(function() { + self.performListingSearch(); + }); + self.installUrl = ko.observable(); self.uploadFilename = ko.observable(); @@ -228,7 +167,7 @@ $(function() { }); self.enableManagement = ko.pureComputed(function() { - return !self.printerState.isPrinting(); + return !self.printerState.isBusy(); }); self.enableToggle = function(data) { @@ -248,9 +187,13 @@ $(function() { }; self.enableRepoInstall = function(data) { - return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && self.isCompatible(data); + return self.enableManagement() && self.pipAvailable() && !self.safeMode() && !self.throttled() && self.online() && self.isCompatible(data); }; + self.throttled = ko.pureComputed(function() { + return self.piSupport && self.piSupport.currentIssue() && !self.settingsViewModel.settings.plugins.pluginmanager.ignore_throttled(); + }); + self.invalidUrl = ko.pureComputed(function() { // supported pip install URL schemes, according to https://pip.pypa.io/en/stable/reference/pip_install/ var allowedUrlSchemes = ["http", "https", @@ -275,6 +218,7 @@ $(function() { return self.enableManagement() && self.pipAvailable() && !self.safeMode() + && !self.throttled() && self.online() && url !== undefined && url.trim() !== "" @@ -300,6 +244,7 @@ $(function() { return self.enableManagement() && self.pipAvailable() && !self.safeMode() + && !self.throttled() && name !== undefined && name.trim() !== "" && !self.invalidArchive(); @@ -350,9 +295,21 @@ $(function() { } }); + self.performListingSearch = function() { + var query = self.listingSearchQuery(); + if (query !== undefined && query.trim() !== "") { + query = query.toLocaleLowerCase(); + self.plugins.changeSearchFunction(function (entry) { + return entry && (entry["name"].toLocaleLowerCase().indexOf(query) > -1 || (entry.description && entry.description.toLocaleLowerCase().indexOf(query) > -1)); + }); + } else { + self.plugins.resetSearch(); + } + }; + self.performRepositorySearch = function() { var query = self.repositorySearchQuery(); - if (query !== undefined && query.trim() != "") { + if (query !== undefined && query.trim() !== "") { query = query.toLocaleLowerCase(); self.repositoryplugins.changeSearchFunction(function(entry) { return entry && (entry["title"].toLocaleLowerCase().indexOf(query) > -1 || entry["description"].toLocaleLowerCase().indexOf(query) > -1); @@ -478,14 +435,15 @@ $(function() { .done(onSuccess) .fail(onError); } else { - var perform = function() { + var performDisabling = function() { OctoPrint.plugins.pluginmanager.disable(data.key) .done(onSuccess) .fail(onError); }; + // always warn if plugin is marked "disabling discouraged" if (data.disabling_discouraged) { - var message = _.sprintf(gettext("You are about to disable \"%(name)s\"."), {name: data.name}) + var message = _.sprintf(gettext("You are about to disable \"%(name)s\"."), {name: _.escape(data.name)}) + "

" + data.disabling_discouraged; showConfirmationDialog({ title: gettext("This is not recommended"), @@ -493,10 +451,21 @@ $(function() { question: gettext("Do you still want to disable it?"), cancel: gettext("Keep enabled"), proceed: gettext("Disable anyway"), - onproceed: perform - }) + onproceed: performDisabling + }); + } + // warn if global "warn disabling" setting is set" + else if (self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable()) { + showConfirmationDialog({ + message: _.sprintf(gettext("You are about to disable \"%(name)s\""), {name: _.escape(data.name)}), + cancel: gettext("Keep enabled"), + proceed: gettext("Disable plugin"), + onproceed: performDisabling, + nofade: true + }); } else { - perform(); + // otherwise just go ahead and disable... + performDisabling(); } } }; @@ -530,6 +499,10 @@ $(function() { return; } + if (self.throttled()) { + return; + } + if (url === undefined) { url = self.installUrl(); } @@ -543,13 +516,13 @@ $(function() { if (!reinstall) { workTitle = gettext("Installing plugin..."); if (name) { - workText = _.sprintf(gettext("Installing plugin \"%(name)s\" from %(url)s..."), {url: url, name: name}); + workText = _.sprintf(gettext("Installing plugin \"%(name)s\" from %(url)s..."), {url: _.escape(url), name: _.escape(name)}); } else { - workText = _.sprintf(gettext("Installing plugin from %(url)s..."), {url: url}); + workText = _.sprintf(gettext("Installing plugin from %(url)s..."), {url: _.escape(url)}); } } else { workTitle = gettext("Reinstalling plugin..."); - workText = _.sprintf(gettext("Reinstalling plugin \"%(name)s\" from %(url)s..."), {url: url, name: name}); + workText = _.sprintf(gettext("Reinstalling plugin \"%(name)s\" from %(url)s..."), {url: _.escape(url), name: _.escape(name)}); } self._markWorking(workTitle, workText); @@ -595,23 +568,41 @@ $(function() { if (data.bundled) return; if (data.key == "pluginmanager") return; - self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: data.name})); + // defining actual uninstall logic as functor in order to handle + // the confirm/no-confirm logic without duplication of logic + var performUninstall = function() { + self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: _.escape(data.name)})); - OctoPrint.plugins.pluginmanager.uninstall(data.key) - .done(function() { - self.requestData(); - }) - .fail(function() { - new PNotify({ - title: gettext("Something went wrong"), - text: gettext("Please consult octoprint.log for details"), - type: "error", - hide: false + OctoPrint.plugins.pluginmanager.uninstall(data.key) + .done(function() { + self.requestData(); + }) + .fail(function() { + new PNotify({ + title: gettext("Something went wrong"), + text: gettext("Please consult octoprint.log for details"), + type: "error", + hide: false + }); + }) + .always(function() { + self._markDone(); }); - }) - .always(function() { - self._markDone(); + }; + + if (self.settingsViewModel.settings.plugins.pluginmanager.confirm_uninstall()) { + // confirmation needed. Show confirmation dialog and call performUninstall if user clicks Yes + showConfirmationDialog({ + message: _.sprintf(gettext("You are about to uninstall the plugin \"%(name)s\""), {name: _.escape(data.name)}), + cancel: gettext("Keep installed"), + proceed: gettext("Uninstall"), + onproceed: performUninstall, + nofade: true }); + } else { + // no confirmation needed, just go ahead and uninstall + performUninstall(); + } }; self.refreshRepository = function() { @@ -680,7 +671,9 @@ $(function() { notices: notices, notices_ttl: noticesTtl, pip_args: pipArgs, - pip_force_user: self.config_pipForceUser() + pip_force_user: self.config_pipForceUser(), + confirm_uninstall: self.config_confirmUninstall(), + confirm_disable: self.config_confirmDisable(), } } }; @@ -698,6 +691,8 @@ $(function() { self.config_noticesTtl(self.settingsViewModel.settings.plugins.pluginmanager.notices_ttl()); self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args()); self.config_pipForceUser(self.settingsViewModel.settings.plugins.pluginmanager.pip_force_user()); + self.config_confirmUninstall(self.settingsViewModel.settings.plugins.pluginmanager.confirm_uninstall()); + self.config_confirmDisable(self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable()); }; self.installed = function(data) { @@ -705,7 +700,7 @@ $(function() { }; self.isCompatible = function(data) { - return data.is_compatible.octoprint && data.is_compatible.os; + return data.is_compatible.octoprint && data.is_compatible.os && data.is_compatible.python; }; self.installButtonText = function(data) { @@ -760,7 +755,7 @@ $(function() { } text += "

  • " - + _.sprintf(line, {plugin: step.plugin, result: step.result ? "" : ""}) + + _.sprintf(line, {plugin: _.escape(step.plugin), result: step.result ? "" : ""}) + "
  • "; }); text += "

    "; @@ -938,16 +933,16 @@ $(function() { var title; if (important) { - title = _.sprintf(gettext("Important notice regarding plugin \"%(name)s\""), {name: name}); + title = _.sprintf(gettext("Important notice regarding plugin \"%(name)s\""), {name: _.escape(name)}); } else { - title = _.sprintf(gettext("Notice regarding plugin \"%(name)s\""), {name: name}); + title = _.sprintf(gettext("Notice regarding plugin \"%(name)s\""), {name: _.escape(name)}); } var text = ""; if (notification.versions && notification.versions.length > 0) { var versions = _.map(notification.versions, function(v) { return (v == version) ? "" + v + "" : v; }).join(", "); - text += "" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: versions}) + ""; + text += "" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: _.escape(versions)}) + ""; } else { text += "" + gettext("Affected versions: all") + ""; } @@ -1163,7 +1158,8 @@ $(function() { OCTOPRINT_VIEWMODELS.push({ construct: PluginManagerViewModel, - dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel", "accessViewModel"], + dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel", "accessViewModel", "piSupportViewModel"], + optional: ["piSupportViewModel"], elements: ["#settings_plugin_pluginmanager"] }); }); diff --git a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less index b828f87fa..3de4ce398 100644 --- a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less +++ b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less @@ -1,21 +1,39 @@ -table { - th, td { - &.settings_plugin_plugin_manager_plugins_name { - text-overflow: ellipsis; - text-align: left; - } +#settings_plugin_pluginmanager { + .form-search { + text-align: center; + margin-bottom: 5px !important; + } +} - &.settings_plugin_plugin_manager_plugins_actions { - text-align: center; - width: 80px; +#settings_plugin_pluginmanager_pluginlist { + display: block; + width: auto; + max-height: 400px; + overflow-x: hidden; + overflow-y: scroll; + padding-right: 2px; + margin-bottom: 1em; - a { - text-decoration: none; - color: #000; + table { - &.disabled { - color: #ccc; - cursor: default; + th, td { + &.settings_plugin_plugin_manager_plugins_name { + text-overflow: ellipsis; + text-align: left; + } + + &.settings_plugin_plugin_manager_plugins_actions { + text-align: center; + width: 80px; + + a { + text-decoration: none; + color: #000; + + &.disabled { + color: #ccc; + cursor: default; + } } } } @@ -53,7 +71,8 @@ table { } } - #settings_plugin_pluginmanager_repositorydialog_unavailable { + #settings_plugin_pluginmanager_repositorydialog_unavailable, + #settings_plugin_pluginmanager_repositorydialog_empty { overflow: hidden; width: 100%; height: 300px; diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 95e9d9077..e18a8dc51 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -1,6 +1,6 @@ {% macro pluginmanager_printing() %}
    - {{ _('Take note that all plugin management functionality is disabled while your printer is printing.') }} + {{ _('Take note that all plugin management functionality is disabled while your printer is printing or paused.') }}
    {% endmacro %} @@ -20,6 +20,13 @@ {% endtrans %} {% endmacro %} +{% macro pluginmanager_throttled() %} +
    {% trans %} + The system OctoPrint is running on is currently throttled. Due to that it's not possible to install new + plugins in order to avoid possible issues caused by system instability. +{% endtrans %}
    +{% endmacro %} + {% macro pluginmanager_offline() %}
    {% trans %} It looks like OctoPrint has currently no connection to the internet. Due to that it's not possible @@ -30,49 +37,55 @@ {{ pluginmanager_printing() }} {{ pluginmanager_nopip() }} {{ pluginmanager_safemode() }} +{{ pluginmanager_throttled() }}
    - +
    + + + +
    +
    + + + +
    +

    {{ _('Installed Plugins') }}

    -
    {{ _('Name') }} {{ _('Size') }} {{ _('Date') }}
    - - - - - - - - - - - - -
    {{ _('Name') }}{{ _('Actions') }}
    -
    ()
    -
    -
     
    -
    - {{ _('Homepage') }} - - -   -
    -
    -  |  -
    -