diff --git a/.versioneer-lookup b/.versioneer-lookup index b2236eb28..e6efd942e 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.11 +# maintenance is currently the branch for preparation of maintenance release 1.3.12 # so are any fix/... and improve/... branches -maintenance 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev -fix/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev -improve/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev +maintenance 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev +fix/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev +improve/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev -# staging/maintenance is currently the branch for preparation of 1.3.11rc3 +# staging/maintenance is currently the branch for preparation of 1.3.12rc2 # so is regressionfix/... -staging/maintenance 1.3.11rc3 18e7d2b72ad73c5d8e522cebbc001d0e8a3dff14 pep440-dev -regressionfix/.* 1.3.11rc3 18e7d2b72ad73c5d8e522cebbc001d0e8a3dff14 pep440-dev +staging/maintenance 1.3.12rc2 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev +regressionfix/.* 1.3.12rc2 2a42f02aecaedf2c55579984e0bc94e44402cc15 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 ae9b33cf7..38730e8d6 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -99,6 +99,15 @@ date of first contribution): * [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) 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 d364c1ab8..d40eec375 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,115 @@ # 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 diff --git a/SUPPORTERS.md b/SUPPORTERS.md index 8ca7d23b7..475d05956 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -8,8 +8,8 @@ thanks to everyone who contributed! * Andre Bubel * Andrew Moorby + * ANTONIO AUGUSTO DE LIMA PONTES * Arnljot Arntsen - * Bjorn Breckenridge * Boris Hussein * Brad Jackson * Christian Petropolis @@ -27,13 +27,13 @@ thanks to everyone who contributed! * Jeff Renfer * Jefferson Hunt * Jeremiah Avery - * Joseph Payne * Joshua Wills * Justin Kaufman * Kaile Riser * Kale Stedman * Kazuhiro Ogura * LA 3D Printer Repair + * Lee Dohm * LulzBot® * Makespace Madrid * Mark Walker @@ -41,17 +41,19 @@ thanks to everyone who contributed! * Miles Flavel * Mosaic Manufacturing * OMER MEHMET SUTAS + * Patrick Glyré * Patrick McGinnis * Prof Yuh Wen Chen * Randy C. Will + * Ranjib Dey * Robert Gusek * Samer Najia * Shawn Lewis * Simon Hallam * Stefan Krister * Sven Mueller - * TEVO 3D Printers * Trent Shumay * Ulrich Kempken + * Vladislav Kuzemchik -and 1544 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! +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/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/printer.rst b/docs/api/printer.rst index 82f86cc91..3fe43aa18 100644 --- a/docs/api/printer.rst +++ b/docs/api/printer.rst @@ -350,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: @@ -630,7 +630,7 @@ Issue a bed command target 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 bed. Additional parameters: @@ -770,7 +770,7 @@ Retrieve the current bed state Issue a chamber command ======================= -.. http:post:: /api/printer/bed +.. http:post:: /api/printer/chamber Chamber commands allow setting the temperature and temperature offsets for the printer's heated chamber. Available commands are: @@ -778,7 +778,7 @@ Issue a chamber command target Sets the given target temperature on the printer's chamber. 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 chamber. Additional parameters: @@ -790,7 +790,7 @@ Issue a chamber command Upon success, a status code of :http:statuscode:`204` and an empty body is returned. - If no heated chambed is configured for the currently selected printer profile, the resource will return + If no heated chamber is configured for the currently selected printer profile, the resource will return an :http:statuscode:`409`. Requires user rights. diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index d6f049077..c9acf65ec 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -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 diff --git a/docs/development/environment.rst b/docs/development/environment.rst index 04f9af807..8308712b7 100644 --- a/docs/development/environment.rst +++ b/docs/development/environment.rst @@ -25,7 +25,7 @@ below. ``source venv/Scripts/activate`` (Git Bash under Windows, see below) * Update ``pip`` in the virtual environment: ``pip install --upgrade pip`` * Install OctoPrint in `"editable" mode `_, - including its regular *and* development and plugin development dependencies: ``pip install -e '.[develop,plugins]'`` + including its regular *and* development and plugin development dependencies: ``pip install -e .[develop,plugins]`` When the virtual environment is activated you can then: diff --git a/docs/events/index.rst b/docs/events/index.rst index 108cfc20b..791f33d0f 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -38,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 @@ -53,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 @@ -580,6 +588,7 @@ SlicingStarted Payload: + * ``slicer``: the used slicer * ``stl``: the STL's filename * ``stl_location``: the STL's location * ``gcode``: the sliced GCODE's filename @@ -591,6 +600,7 @@ SlicingDone Payload: + * ``slicer``: the used slicer * ``stl``: the STL's filename * ``stl_location``: the STL's location * ``gcode``: the sliced GCODE's filename @@ -603,6 +613,7 @@ SlicingCancelled Payload: + * ``slicer``: the used slicer * ``stl``: the STL's filename * ``stl_location``: the STL's location * ``gcode``: the sliced GCODE's filename @@ -613,6 +624,7 @@ SlicingFailed Payload: + * ``slicer``: the used slicer * ``stl``: the STL's filename * ``stl_location``: the STL's location * ``gcode``: the sliced GCODE's filename @@ -628,7 +640,7 @@ SlicingProfileAdded * ``profile``: the profile that was added SlicingProfileModified - A new slicing profile was modified. + A slicing profile was modified. Payload: @@ -653,3 +665,15 @@ SettingsUpdated 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/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/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/plugins/hooks.rst b/docs/plugins/hooks.rst index c5bb1db3a..b5cd36bf4 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -766,9 +766,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 diff --git a/setup.py b/setup.py index 26b1208be..27d031eb9 100644 --- a/setup.py +++ b/setup.py @@ -61,7 +61,8 @@ INSTALL_REQUIRES = [ "monotonic>=1.5,<1.6", "frozendict>=1.2,<1.3", "sentry-sdk==0.7.7", - "typing>=3.6.6,<4" + "typing>=3.6.6,<4", + "filetype>=1.0.5,<2" ] if sys.platform == "darwin": @@ -81,6 +82,7 @@ EXTRA_REQUIRES = dict( "sphinxcontrib-httpdomain", "sphinxcontrib-mermaid>=0.3", "sphinx_rtd_theme", + "readthedocs-sphinx-ext==0.5.7" ], # Dependencies for developing OctoPrint plugins diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index 34ad3f30e..f2df742b9 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -137,9 +137,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/user.py b/src/octoprint/cli/user.py new file mode 100644 index 000000000..fcf4cac74 --- /dev/null +++ b/src/octoprint/cli/user.py @@ -0,0 +1,157 @@ +# 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.users import FilebasedUserManager, UnknownUser, UserAlreadyExists +from octoprint.util import get_class + +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)) + + name = settings.get(["accessControl", "userManager"]) + try: + clazz = get_class(name) + manager = clazz(settings=settings) + except Exception: + click.echo("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name), err=True) + manager = FilebasedUserManager(settings=settings) + finally: + manager.enabled = settings.getBoolean(["accessControl", "enabled"]) + + ctx.obj.user_manager = 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.getAllUsers() + _print_list(users) + + +@user.command(name="add") +@click.argument("username", type=click.STRING, required=True) +@click.password_option("--password", "password", help="Password for user") +@click.option("--admin", "is_admin", type=click.BOOL, is_flag=True, default=False, + help="Sets admin role on user") +@click.pass_context +def add_user_command(ctx, username, password, is_admin): + """Add a new user.""" + try: + ctx.obj.user_manager.addUser(username, + password, + roles=(("user", "admin") if is_admin else ("user",)), + active=True) + + user = ctx.obj.user_manager.findUser(username) + if user: + click.echo("User created:") + click.echo("\t{}".format(_user_to_line(user.asDict()))) + 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.removeUser(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.changeUserPassword(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.changeUserActivation(username, True) + click.echo("User {} activated.".format(username)) + + user = ctx.obj.user_manager.findUser(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.changeUserActivation(username, False) + click.echo("User {} activated.".format(username)) + + user = ctx.obj.user_manager.findUser(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(users, key=lambda x: x.get("name")): + click.echo("\t{}".format(_user_to_line(user))) + + +def _user_to_line(user): + return "{} (active: {}, admin: {})".format(user.get("name"), + "yes" if user.get("active", False) else "no", + "yes" if user.get("admin", False) else "no") diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 74374f7ec..dc5478cd6 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -343,17 +343,24 @@ class CommandTrigger(GenericEventListener): 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 not event in self._subscriptions.keys(): + self._subscriptions[event] = [] + self._subscriptions[event].append((command, commandType, debug)) + + if not event in eventsToSubscribe: + eventsToSubscribe.append(event) self.subscribe(eventsToSubscribe) @@ -373,9 +380,9 @@ 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) @@ -424,13 +431,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 @@ -452,6 +460,7 @@ class CommandTrigger(GenericEventListener): 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 8124c06ce..c33f00c24 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -17,6 +17,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 @@ -329,25 +330,27 @@ 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.BytesIO(u";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) @@ -356,11 +359,12 @@ class FileManager(object): printer_profile=printer_profile, analysis=_analysis) end_time = octoprint.util.monotonic_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)) + 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: @@ -381,7 +385,8 @@ class FileManager(object): slicer = self._slicing_manager.get_slicer(slicer_name) start_time = octoprint.util.monotonic_time() - eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, + eventManager().fire(Events.SLICING_STARTED, {"slicer": slicer_name, + "stl": source_path, "stl_location": source_location, "gcode": dest_path, "gcode_location": dest_location, @@ -425,7 +430,8 @@ class FileManager(object): 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") + except: 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): @@ -654,6 +660,8 @@ class FileManager(object): try: with open(self._recovery_file) 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: self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file)) diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index cdb61b5a1..181320d16 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -19,6 +19,7 @@ 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")): @@ -109,7 +110,11 @@ class AnalysisQueue(object): 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, diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 1b2b66b8f..c7b66c3e1 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -1547,13 +1547,21 @@ class LocalFileStorage(StorageInterface): except: self._logger.exception("Error while reading .metadata.json from {path}".format(**locals())) + 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 entries from metadata for path {}".format(old_size - new_size, - path)) + 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): diff --git a/src/octoprint/logging/__init__.py b/src/octoprint/logging/__init__.py index 1021b169a..d9237cfee 100644 --- a/src/octoprint/logging/__init__.py +++ b/src/octoprint/logging/__init__.py @@ -3,6 +3,8 @@ from __future__ import absolute_import 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. @@ -137,14 +139,17 @@ 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 to_unicode(lines[0]) - return lines[0] + "\n" + "\n".join(map(lambda line: prefix + line, - lines[1:])) + return to_unicode(lines[0]) + u"\n" + u"\n".join(map(lambda line: prefix + to_unicode(line), + lines[1:])) diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 467aac652..dc5f796e8 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -69,6 +69,8 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, 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 @@ -213,7 +215,7 @@ __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__ = { 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 e077903a2..cb7181cda 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 @@ -4,7 +4,17 @@ $(function() { self.loginState = parameters[0]; - 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.isUser()) return; @@ -15,26 +25,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) { @@ -42,8 +61,9 @@ $(function() { }; self._closePrompt = function() { - if (self._modal) { - self._modal.modal("hide"); + var modal = self.modal(); + if (modal) { + modal.modal("hide"); } }; @@ -59,10 +79,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; } @@ -73,6 +97,7 @@ $(function() { OCTOPRINT_VIEWMODELS.push({ construct: ActionCommandPromptViewModel, - dependencies: ["loginStateViewModel"] + dependencies: ["loginStateViewModel"], + 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/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 index 310638360..d67c8de9a 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -43,6 +43,12 @@ class PendingDecision(object): 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): @@ -54,6 +60,11 @@ class ReadyDecision(object): 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): @@ -74,6 +85,11 @@ class ActiveKey(object): 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, @@ -121,12 +137,15 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, @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: + 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) diff --git a/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 index 700fb8f2b..6da481c60 100644 --- a/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 +++ b/src/octoprint/plugins/appkeys/templates/appkeys_settings.jinja2 @@ -40,8 +40,8 @@ -
{{ _('API Key') }}: - +
{{ _('API Key') }}: + diff --git a/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 b/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 index 2499b2330..1bfeaf07f 100644 --- a/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 +++ b/src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2 @@ -13,8 +13,8 @@ -
{{ _('API Key') }}: - +
{{ _('API Key') }}: + diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 14cacaf08..5408e71ad 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -619,6 +619,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, try: if exclude is None: exclude = [] + if not isinstance(exclude, list): + exclude = list(exclude) if "timelapse" in exclude: exclude.append("timelapse_tmp") diff --git a/src/octoprint/plugins/backup/static/js/backup.js b/src/octoprint/plugins/backup/static/js/backup.js index 26929ec57..348860204 100644 --- a/src/octoprint/plugins/backup/static/js/backup.js +++ b/src/octoprint/plugins/backup/static/js/backup.js @@ -197,10 +197,10 @@ $(function() { self.loglines.push({line: " ", stream: "message"}); self.loglines.push({line: gettext("Restore successful! The server will now be restarted!"), stream: "message"}); self.restoreInProgress(false); - } else if (data.type === "install_plugin") { + } else if (data.type === "installing_plugin") { self.loglines.push({line: " ", stream: "message"}); self.loglines.push({ - line: _.sprintf(gettext("Installing plugin \"%(plugin)s}\"..."), {plugin: data.plugin.name}), + line: _.sprintf(gettext("Installing plugin \"%(plugin)s\"..."), {plugin: data.plugin}), stream: "message" }); } else if (data.type === "plugin_incompatible") { diff --git a/src/octoprint/plugins/backup/templates/backup_settings.jinja2 b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 index e9546adb2..6fcc72ca4 100644 --- a/src/octoprint/plugins/backup/templates/backup_settings.jinja2 +++ b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 @@ -46,7 +46,7 @@ -  |  |  +  |  |  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/errortracking/__init__.py b/src/octoprint/plugins/errortracking/__init__.py index 341adf66b..816c49eee 100644 --- a/src/octoprint/plugins/errortracking/__init__.py +++ b/src/octoprint/plugins/errortracking/__init__.py @@ -7,13 +7,14 @@ __copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms 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://4069187705ab4e76921eb19db2e9ccbb@sentry.io/1373987" -SENTRY_URL_COREUI = "https://a4ab48f27daf4c129392b78be15412b8@sentry.io/1374096" +SENTRY_URL_SERVER = "https://6c066dfe16c244d38fca46dbc05e1028@sentry.io/1373987" +SENTRY_URL_COREUI = "https://fb45e3d5210b43bfaccd5f3c45c2b28d@sentry.io/1374096" SETTINGS_DEFAULTS = dict(enabled=False, enabled_unreleased=False, @@ -29,19 +30,24 @@ import tornado.websocket IGNORED_EXCEPTIONS = [ # serial exceptions in octoprint.util.comm - (serial.SerialException, lambda exc, logger, plugin: logger == "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: logger == "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: getattr(exc, "errno") and exc.errno in (getattr(errno, "ENOSPC"),)), + (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 + 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: @@ -138,6 +144,7 @@ def _enable_errortracking(): 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): @@ -147,8 +154,8 @@ def _enable_errortracking(): matcher = lambda *args: True exc = hint["exc_info"][1] - if isinstance(exc, ignored_exc) and matcher(exc, logger, plugin): - # exception ignored for logger + 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): diff --git a/src/octoprint/plugins/errortracking/templates/errortracking_settings.jinja2 b/src/octoprint/plugins/errortracking/templates/errortracking_settings.jinja2 index e5adefa92..56f86efee 100644 --- a/src/octoprint/plugins/errortracking/templates/errortracking_settings.jinja2 +++ b/src/octoprint/plugins/errortracking/templates/errortracking_settings.jinja2 @@ -25,7 +25,7 @@
- +
diff --git a/src/octoprint/plugins/forcelogin/__init__.py b/src/octoprint/plugins/forcelogin/__init__.py index 03b0083ac..d9654798e 100644 --- a/src/octoprint/plugins/forcelogin/__init__.py +++ b/src/octoprint/plugins/forcelogin/__init__.py @@ -123,7 +123,7 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin, # not active, no handling return - if flask.request.endpoint in ("api.login",): + if flask.request.endpoint in ("api.login",) or flask.request.endpoint.endswith(".static"): return if plugin is not None and not plugin.is_blueprint_protected(): diff --git a/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2 b/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2 index c5b6e28dc..f12e6ad4f 100644 --- a/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2 +++ b/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2 @@ -21,8 +21,9 @@
{{ _('Incorrect username or password.') }}
{{ _('Server is currently offline.') }} {{ _('Reconnect...') }}
- - + + + {{ _('Forgot password?') }} diff --git a/src/octoprint/plugins/logging/templates/logging_settings.jinja2 b/src/octoprint/plugins/logging/templates/logging_settings.jinja2 index 7d427324b..56353a20c 100644 --- a/src/octoprint/plugins/logging/templates/logging_settings.jinja2 +++ b/src/octoprint/plugins/logging/templates/logging_settings.jinja2 @@ -84,7 +84,7 @@
- +
@@ -103,7 +103,7 @@
- +
diff --git a/src/octoprint/plugins/pi_support/__init__.py b/src/octoprint/plugins/pi_support/__init__.py index 4c79b6151..7983c97c8 100644 --- a/src/octoprint/plugins/pi_support/__init__.py +++ b/src/octoprint/plugins/pi_support/__init__.py @@ -304,7 +304,7 @@ __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" 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 6349f9180..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 5caa980b6..221007443 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -37,6 +37,9 @@ _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: @@ -103,20 +106,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 @@ -141,6 +150,10 @@ 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"] + # decouple repository fetching from server startup self._fetch_all_data(do_async=True) @@ -154,6 +167,8 @@ 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=[] ) @@ -164,6 +179,8 @@ 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 @@ -260,11 +277,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(): @@ -341,6 +358,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): + # 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") @@ -767,16 +790,23 @@ 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: repo_data = json.load(f) + self._repository_mtime = mtime self._logger.info("Loaded plugin repository data from disk, was still valid") except: self._logger.exception("Error while loading repository data from {}".format(self._repository_cache_path)) @@ -797,12 +827,22 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=str(e))) return None - repo_data = r.json() + try: + repo_data = r.json() + except Exception as e: + self._logger.exception("Error while reading repository data") + 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) + 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))) @@ -814,19 +854,27 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if repo_data is None: return False - self._repository_plugins = map(map_repository_entry, repo_data) + self._repository_plugins = 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: notice_data = json.load(f) + self._notices_mtime = mtime self._logger.info("Loaded notice data from disk, was still valid") except: self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path)) @@ -853,6 +901,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, import json with octoprint.util.atomic_write(self._notices_cache_path, "wb") as f: json.dump(notice_data, f) + 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 diff --git a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css index ea7017ed7..3a37ccc85 100644 --- a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css +++ b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css @@ -1 +1 @@ -#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;height:500px;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_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_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_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 diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 8557c4a4b..0cff5d58b 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -7,12 +7,17 @@ $(function() { self.printerState = parameters[2]; self.systemViewModel = parameters[3]; + // optional + self.piSupport = parameters[4]; + 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"); @@ -164,9 +169,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.invalidUrl = ko.pureComputed(function() { // supported pip install URL schemes, according to https://pip.pypa.io/en/stable/reference/pip_install/ var allowedUrlSchemes = ["http", "https", @@ -191,6 +200,7 @@ $(function() { return self.enableManagement() && self.pipAvailable() && !self.safeMode() + && !self.throttled() && self.online() && url !== undefined && url.trim() !== "" @@ -216,6 +226,7 @@ $(function() { return self.enableManagement() && self.pipAvailable() && !self.safeMode() + && !self.throttled() && name !== undefined && name.trim() !== "" && !self.invalidArchive(); @@ -394,12 +405,13 @@ $(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}) + "

" + data.disabling_discouraged; @@ -409,10 +421,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: data.name}), + cancel: gettext("Keep enabled"), + proceed: gettext("Disable plugin"), + onproceed: performDisabling, + nofade: true + }); } else { - perform(); + // otherwise just go ahead and disable... + performDisabling(); } } }; @@ -446,6 +469,10 @@ $(function() { return; } + if (self.throttled()) { + return; + } + if (url === undefined) { url = self.installUrl(); } @@ -511,23 +538,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: 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: 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() { @@ -596,7 +641,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(), } } }; @@ -614,6 +661,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) { @@ -1083,7 +1132,8 @@ $(function() { OCTOPRINT_VIEWMODELS.push({ construct: PluginManagerViewModel, - dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel"], + dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel", "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 39a7bb0a6..2f5832fde 100644 --- a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less +++ b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less @@ -1,7 +1,7 @@ #settings_plugin_pluginmanager_pluginlist { display: block; width: auto; - height: 500px; + height: 400px; overflow-x: hidden; overflow-y: scroll; padding-right: 2px; diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 0e4eef7ee..3b0ca7826 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -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,9 +37,10 @@ {{ pluginmanager_printing() }} {{ pluginmanager_nopip() }} {{ pluginmanager_safemode() }} +{{ pluginmanager_throttled() }}
- +

{{ _('Installed Plugins') }}

@@ -48,7 +56,7 @@ -
()
+
()
 
@@ -59,7 +67,7 @@
-  |  +  |  @@ -122,6 +130,7 @@ {{ pluginmanager_printing() }} {{ pluginmanager_nopip() }} {{ pluginmanager_safemode() }} + {{ pluginmanager_throttled() }} {{ pluginmanager_offline() }}

{{ _('... from the Plugin Repository', url='https://plugins.octoprint.org') }} @@ -142,7 +151,7 @@

@@ -184,7 +193,7 @@
- +
@@ -234,18 +243,37 @@