diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 97a7e30cc..00bd36a44 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -62,7 +62,7 @@ to also include a link to a file with which to reproduce the problem.] [Try to reproduce your problem in safe mode. You can find information on how to enable safe mode in the Contribution Guidelines.] -#### Branch & Commit or Version of OctoPrint +#### Version of OctoPrint [Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.] diff --git a/.versioneer-lookup b/.versioneer-lookup index 13592921d..992641e5a 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -16,16 +16,16 @@ prerelease HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.3.6 +# maintenance is currently the branch for preparation of maintenance release 1.3.7 # so are any fix/... and improve/... branches -maintenance 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev -fix/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev -improve/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev +maintenance 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev +fix/.* 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev +improve/.* 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev -# staging/maintenance is currently the branch for preparation of 1.3.6rc1 +# staging/maintenance is currently the branch for preparation of 1.3.6rc4 # so is regressionfix/... -staging/maintenance 1.3.6rc1 77753ca02602d3a798d6b0a22535e6fd69ff448a pep440-dev -regressionfix/.* 1.3.6rc1 77753ca02602d3a798d6b0a22535e6fd69ff448a pep440-dev +staging/maintenance 1.3.6rc4 a8747f7e36a03ff2449b62cdf68b8a26a6fa61b3 pep440-dev +regressionfix/.* 1.3.6rc4 a8747f7e36a03ff2449b62cdf68b8a26a6fa61b3 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 d3419f4d9..773a6c45e 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -87,6 +87,7 @@ date of first contribution): * [Peter Backx](https://github.com/pbackx) * [Josh Major](https://github.com/astateofblank) * ["alex-gh"](https://github.com/alex-gh) + * [Bernd Zeimetz](https://github.com/bzed) 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 2ff2da42f..ff1707b71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,128 @@ # OctoPrint Changelog +## 1.3.6 (2017-12-12) + +### Note for upgraders and plugin authors: Change in the bundling of JS assets can lead to issues in plugins + +A change to solve issues with plugins bundling JS assets that cause interference with other plugins (e.g. through the declaration of `"use strict"`) and in general to add better isolation and error handling might cause errors for some plugins that go beyond your run-off-the-mill view model and also implicitly declare new globals. + +If you happen to run into any such issues, you can switch back to the old way of bundling JS assets via the newly introduced "Settings > Feature > Enable legacy plugin asset bundling" toggle (check it, save the settings, restart the server). This is provided to allow for a minimally invasive adjustment period until affected plugins have been updated. + +You can find out more about the change, how to know if a plugin is even affected and what do about it [on the OctoBlog](https://octoprint.org/blog/2017/12/01/heads-up-plugin-authors/). + +### Improvements + + * [#203](https://github.com/foosel/OctoPrint/issues/203) - Allow selecting the current tab via URL hashs. Also update URL hash when switching tabs, thus adding this to the browser history and allowing quicker back and forth navigation through the browser's back and forward buttons. + * [#1026](https://github.com/foosel/OctoPrint/issues/1026) - Automatically upper case parameters in GCODE commands sent from the Terminal tab. A black list is in place that prevent upper casing of parameters for GCODE commands where it doesn't make sense (default: `M117`). See also [#2177](https://github.com/foosel/OctoPrint/pull/2177). + * [#2050](https://github.com/foosel/OctoPrint/issues/2050) - New hook [`octoprint.comm.protocol.temperatures.received`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-temperatures-received) that allows plugins to further preprocess/sanitize temperature data received from the printer. + * [#2055](https://github.com/foosel/OctoPrint/issues/2055) - Increased the size of the API key field in the settings. + * [#2056](https://github.com/foosel/OctoPrint/issues/2056) - Added a Copy button to the API key field in the settings and user settings. + * [#2094](https://github.com/foosel/OctoPrint/issues/2094) - Allow UTF-8 display names for uploaded files. The files will still get an ASCII only name on disk, but the UTF-8 name used during upload will also be persisted and shown in the file list. This also allows using emojis in your file and folder names now. + * [#2104](https://github.com/foosel/OctoPrint/issues/2104) - Allow more URL schemes for installing plugins from. Supported schemes should now mirror what `pip` itself supports: `http`, `https`, `git`, `git+http`, `git+https`, `git+ssh`, `git+git`, `hg+http`, `hg+https`, `hg+static-http`, `hg+ssh`, `svn`, `svn+svn`, `svn+http`, `svn+https`, `svn+ssh`, `bzr+http`, `bzr+https`, `bzr+ssh`, `bzr+sftp`, `bzr+ftp`, `bzr+lp`. + * [#2109](https://github.com/foosel/OctoPrint/pull/2109) - New decorator `@firstrun_only_access` for API endpoints that should only be available before first setup has been completed. + * [#2111](https://github.com/foosel/OctoPrint/issues/2111) - Made the file list's scroll bar wider. + * [#2131](https://github.com/foosel/OctoPrint/issues/2131) - Added warning to restart, shutdown, reboot and update confirmations that that may disrupt ongoing prints, even those run from the printer's internal storage/SD. See also [#2146](https://github.com/foosel/OctoPrint/pull/2146) and [#2152](https://github.com/foosel/OctoPrint/pull/2152). + * [#2138](https://github.com/foosel/OctoPrint/issues/2138) - Slightly longer timeout when attempting to read from serial during auto detection via programming mode. Might help with detection of some slower printer controllers under certain circumstances. + * [#2200](https://github.com/foosel/OctoPrint/issues/2200) - Wrap all JS assets of plugins into one anonymous function per plugin. That way plugins using `"use strict";` won't cause hard to debug and weird issues with other plugins bundled after them. The down side is that plugins currently relying on implicit declaration of global helper functions or variables (`function convert(value) { ... }`) to be available outside of their own plugin's JS assets will now run into errors. To compensate for that while affected plugins are adjusted to declare globals explicitly (`window.convert = function(value) { ... }`), a temporary feature flag was added as "Settings > Features > Enable legacy plugin asset bundling" that switches back to the old form of bundling until plugins you rely on are updated. This flag will be removed again in a later version (currently planned for 1.3.8). See also the note above and [#2246](https://github.com/foosel/OctoPrint/issues/2246). + * [#2229](https://github.com/foosel/OctoPrint/issues/2229) - Added note to printer profile dialog that the nozzle offsets for multi extruder setups are only to be configured if they are not already set in the printer's firmware. + * [#2232](https://github.com/foosel/OctoPrint/issues/2232) - Disable movement distance buttons when not connected to the printer or when printing, since they don't have any use then. + * [#2239](https://github.com/foosel/OctoPrint/pull/2239) - Improved the check summing speed, thus improving the general achievable throughput on the comm layer. + * Allow cancelling of file transfers + * Made check of how old an unrendered timelapse is more lenient buy looking at both the creation and last modification date and using the younger one. + * Made notifications in general auto-close faster. + * Make the first profile saved for a slicer the default profile for that slicer. + * New command `server` for testing server connections on the [JS test API](http://docs.octoprint.org/en/maintenance/api/util.html#post--api-util-test). + * New hook [`octoprint.accesscontrol.keyvalidator`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-accesscontrol-keyvalidator) that allows plugins to validate their own customized API keys to be used to access OctoPrint. + * Updated `cookiecutter`, `requests` and `psutil` dependencies. + * Added safety warning to first run wizard. + * More error resilience against broken view models. + * New sub command `octoprint safemode`. Will set the `server.startOnceInSafeMode` setting in the config so that the next (re)start of the server after issuing this command will happen in safe mode. + * New sub command `octoprint config effective`. Will report the effective config. + * New centralized plugin blacklist (opt-in). Allows to prevent plugins/certain versions of plugins known to cause crippling issues with the normal operation of OctoPrint to be disabled from loading, if the user has opted to do so in the settings/wizard. + * Log how to enable `serial.log` to `serial.log` if it's disabled. That will hopefully put at least a small dent in the amount of "It's empty!" responses in tickets ;) + * Force new Pypi index URL in `requirements.txt` as an additional work around against old tooling. + * Prefer plain `pip` over `git` for updating OctoPrint. + * Added environment detection and logging on startup. That should give us more information about the environment to produce a reported bug in. + * Added OctoPi support plugin that provides information about the detected OctoPi version. Will only load if OctoPi is detected. + * More dynamic plugin mixin detection. Now using a base class instead of having to list all types manually. Should greatly reduce overhead of adding new mixin types. + * Support leaf merging for file extension tree, allowing to add new file extensions to types registered by default. + * Allow non GCODE SD file transfers if registered as `machinecode` through e.g. a plugin's file extension hook. Caution: This doesn't make streaming arbitrary files to the printer via serial work magically. It merely allows that, it's up to the firmware to actually be able to handle that. Also, the regular GCODE streaming protocol is used, so if the streamed file contains control characters from that (e.g. `M29` to signal the end of the streaming process), stuff will break! + * Added a test button for the online connectivity check. + * Announcements plugin: Added UTM Tags. + * Cura plugin: Less `not configured yet` logging. + * GCODE viewer: Added advanced options that allow configuring display of bounding boxes, sorting by layers and hiding of empty layers. + * GCODE viewer: Persist all options to local storage so they will be automatically set again the next time the GCODE viewer is used in the same browser. + * Software update: Auto-hide "Everything is up-to-date" notification. + * Easier copying of terminal contents thanks to dedicated copy button. + * Timelapse: [#2067](https://github.com/foosel/OctoPrint/issues/2067) - Added rate limiting to z-based timelapse capturing to prevent issues when accidentally leaving this mode on with vase mode prints. + * Timelapse: Refactored configuration form & added reset button to switch back to currently active settings. + * Timelapse: Sort timelapses by modification instead of creation time (creation time can be newer if a backup restore was done). + * Virtual printer: Support configurable ambient temperature for testing. + * Virtual printer: Support configurable reset lines. + * Virtual printer: Added new debug trigger `trigger_missing_lineno`. + * Virtual printer: Allow empty/`None` prepared oks, allowing to simulate lost acknowledgements right on start. + * Docs: [#2142](https://github.com/foosel/OctoPrint/pull/2142) - Added documentation for the bundled virtual printer plugin. + * Docs: [#2234](https://github.com/foosel/OctoPrint/pull/2234) - Added info on how to install under Suse Linux. + * Docs: Added example PyCharm run configuration that includes automatic dependency updates on start. + * Docs: Added information on how to run the test suite. + * Various refactorings + * Various documentation updates + * Fetch plugin blacklist (and also announcements, plugin notices and plugin repository) via https instead of http. + +### Bug fixes + + * [#2044](https://github.com/foosel/OctoPrint/pull/2044) - Fix various typos in strings and comments + * [#2048](https://github.com/foosel/OctoPrint/pull/2048) & [#2176](https://github.com/foosel/OctoPrint/pull/2176) - Fixed various warnings during documentation generation. + * [#2077](https://github.com/foosel/OctoPrint/issues/2077) - Fix an issue with shared nozzles and the temperature graph, causing temperature to not be reported properly when another tool but the first one is selected. See also [#2077](https://github.com/foosel/OctoPrint/pull/2123) + * [#2108](https://github.com/foosel/OctoPrint/issues/2108) - Added no-op default action to login form so that username + password aren't sent as GET parameters if for some reason the user tries to log in before the view models are properly bound and thus the AJAX POST submission method is attached. + * [#2111](https://github.com/foosel/OctoPrint/issues/2111) - Prevent file list's scroll bar from fading out. + * [#2146](https://github.com/foosel/OctoPrint/issues/2147) - Fix initialization of temperature graph if it's not on the first tab due to tab reordering. + * [#2166](https://github.com/foosel/OctoPrint/issues/2166) - Workaround for a Firefox bug that causes the Drag-n-Drop overlay to never go away if the file is dragged outside of the browser window. + * [#2167](https://github.com/foosel/OctoPrint/issues/2167) - Fixed grammar of print time estimation tooltip + * [#2175](https://github.com/foosel/OctoPrint/issues/2175) - Cancel printing when an external reset of the printer is detected on the serial connection. + * [#2181](https://github.com/foosel/OctoPrint/issues/2181) - More resilience against non-standard `M115` responses. + * [#2182](https://github.com/foosel/OctoPrint/pull/2182) - Don't start tracking non existing or nonfunctional tools if encountering a temperature command referencing said tool. See also [kantlivelong/OctoPrint-PSUControl#68](https://github.com/kantlivelong/OctoPrint-PSUControl/issues/68). + * [#2196](https://github.com/foosel/OctoPrint/issues/2196) - Marked API key fields as `readonly` instead of `disabled` to allow their contents to be copied in Firefox (which wasn't possible before). + * [#2203](https://github.com/foosel/OctoPrint/issues/2203) - Reset temperature offsets to 0 when disconnected from the printer. + * [#2206](https://github.com/foosel/OctoPrint/issues/2206) - Disable pre-configured timelapse if snapshot URL of ffmpeg path are unset. + * [#2214](https://github.com/foosel/OctoPrint/issues/2214) - Fixed temperature fields not selecting in MS Edge on focus. + * [#2217](https://github.com/foosel/OctoPrint/pull/2217) - Fix an issue in `octoprint.util` causing a crash when running under PyPy instead of CPython. + * [#2226](https://github.com/foosel/OctoPrint/issues/2226) - Handle `No Line Number with checksum, Last Line: ...` errors from the firmware. + * [#2233](https://github.com/foosel/OctoPrint/pull/2233) - Respond with `411 Length Required` when content length is missing on file uploads. + * [#2242](https://github.com/foosel/OctoPrint/issues/2242) - Fixed an issue where print time left could show "1 days" instead of "1 day". + * [#2262](https://github.com/foosel/OctoPrint/issues/2262) (regression) - Fixed a bug causing `Error:checksum mismatch, Last Line: ...` errors from the firmware to be handled incorrectly. + * [#2267](https://github.com/foosel/OctoPrint/issues/2267) (regression) - Fixed a bug causing the GCODE viewer to not get properly initialized due to a JS error on load if "Also show next layer" was selected. + * [#2268](https://github.com/foosel/OctoPrint/issues/2268) (regression) - Fixed a bug causing a display error with the temperature offsets. If one offset was changed, all others seemed to revert back to 0. + * Fixed cleanup of unrendered timelapses with certain names. + * Fixed a caching issue with the file list API and the slicing API. + * Fixed initial sizing of the temperature graph. + * More resilience against corrupt `.metadata.yaml` files. + * More resilience against corrupt/invalid entries for system actions. + * More resilience against invalid JSON command requests. + * More resilience against broken packages in the python environment. + * Don't evaluate `onWebcamLoaded` more than once when switching to the webcam tab. + * Fixed `octoprint config` sub command. + * Fixed deactivated user accounts being able to login (albeit without a persistent session). Show fitting error instead. + * Fixed temperature auto report after an external reset. + * Don't log full request headers in Tornado on an error. + * Fix displayed notification message for synchronous system commands. Was accidentally swapped with the one for asynchronous system commands. + * GCODE viewer: Fix error on empty layers. + * Virtual printer: Fix resend simuation. + * Docs: Fixed CSS of line numbered listings. + * Docs: Updated mermaid to fix a deprecation warning. + * Fixed ordering of plugin assets, should be alphabetical based on the plugin identifier. (regression) + * Fixed an issue causing redundant software update configuration settings to be written to `config.yaml`, in turn causing issues when downgrading to <1.3.5. (regression) + * Fixed an issue detecting whether the installed version is a release version or a development version. (regression) + +### More Information + + * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.5...1.3.6) + * Release Candidates: + * [1.3.5rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.6rc1) + * [1.3.5rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.6rc2) + * [1.3.5rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.6rc3) + * A special **Thank you!** to everyone who reported back on these release candidates this time: [andrivet](https://github.com/andrivet), [b-morgan](https://github.com/b-morgan), [bjarchi](https://github.com/bjarchi), [chippypilot](https://github.com/chippypilot), [ChrisHeerschap](https://github.com/ChrisHeerschap), [cosmith71](https://github.com/cosmith71), [Crowlord](https://github.com/Crowlord), [ctgreybeard](https://github.com/ctgreybeard), [fiveangle](https://github.com/fiveangle), [goeland86](https://github.com/goeland86), [jbjones27](https://github.com/jbjones27), [jneilliii](https://github.com/jneilliii), [JohnOCFII](https://github.com/JohnOCFII), [Kunsi](https://github.com/Kunsi), [Lordxv](https://github.com/Lordxv), [malnvenshorn](https://github.com/malnvenshorn), [mcp5500](https://github.com/mcp5500), [ntoff](https://github.com/ntoff), [ripp2003](https://github.com/ripp2003) and [schorsch3000](https://github.com/schorsch3000) + ## 1.3.5 (2017-10-16) ### Improvements diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 66f936c58..74b8be4fb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -160,7 +160,7 @@ only provided here as some additional information for you), **even if only addin [Try to reproduce your problem in safe mode. You can find information on how to enable safe mode in the Contribution Guidelines.] - #### Branch & Commit or Version of OctoPrint + #### Version of OctoPrint [Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.] diff --git a/README.md b/README.md index 817884a57..1571a3308 100644 --- a/README.md +++ b/README.md @@ -5,14 +5,14 @@ OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html). -Its website can be found at [octoprint.org](http://octoprint.org). +Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=github&utm_medium=readme). The documentation is located at [docs.octoprint.org](http://docs.octoprint.org). -The official plugin repository can be reached at [plugins.octoprint.org](http://plugins.octoprint.org). +The official plugin repository can be reached at [plugins.octoprint.org](https://plugins.octoprint.org/?utm_source=github&utm_medium=readme). -OctoPrint's development wouldn't be possible without the [financial support by its community](http://octoprint.org/support-octoprint/). -If you enjoy OctoPrint, please consider becoming a regular supporter! +**OctoPrint's development wouldn't be possible without the [financial support by its community](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme). +If you enjoy OctoPrint, please consider becoming a regular supporter!** ![Screenshot](http://i.imgur.com/dF3noFp.png) @@ -29,7 +29,7 @@ Contributions of all kinds are welcome, not only in the form of code but also wi [official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), support of other users in the [bug tracker](https://github.com/foosel/OctoPrint/issues), [the Mailinglist](https://groups.google.com/group/octoprint) or -[the G+ Community](https://plus.google.com/communities/102771308349328485741) and also [financially](http://octoprint.org/support-octoprint/). +[the G+ Community](https://plus.google.com/communities/102771308349328485741) and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme). If you think something is bad about OctoPrint or its documentation the way it is, please help in any way to make it better instead of just complaining about it -- this is an Open Source Project diff --git a/SUPPORTERS.md b/SUPPORTERS.md index 32b246639..29c55a3e3 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -21,16 +21,13 @@ thanks to everyone who contributed! * DeltaMaker 3D Printers * E3D BigBox * Ernesto Martinez - * Exovite * F. Kunsmann - * Farren Young II * Frank Sander * Gary Deen * Gary N McKinney * George Robles * günter weber * James Seigel - * Jamie R McGuigan * Jason Lawrence * Jeff Moe * Josh Daniels @@ -39,19 +36,16 @@ thanks to everyone who contributed! * Kazuhiro Ogura * Makespace Madrid * Marcus Ackermann - * Mark Qvist * Mark Walker - * Masayoshi Mitsui * Michael Aumock * Miles Flavel * mitchell hirsch * Mohammed khorakiwala * Noe Ruiz * Patrick McGinnis - * Peter Grace * Peter Schmehl * PRINT3Dforum.com - * Robert Gusek + * Randy C. Will * Roger Strolz * Roy Cortes * Samer Najia @@ -64,4 +58,4 @@ thanks to everyone who contributed! * Timeshell.ca * Trent Shumay -and 1133 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! \ No newline at end of file +and 1062 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! \ No newline at end of file diff --git a/docs/api/job.rst b/docs/api/job.rst index 5d727228e..338a10ea7 100644 --- a/docs/api/job.rst +++ b/docs/api/job.rst @@ -4,6 +4,9 @@ Job operations ************** +Use these operations to query the currently selected file and start/cancel/restart/pause the +actual print job. + .. contents:: .. _sec-api-jobs-command: diff --git a/docs/api/logs.rst b/docs/api/logs.rst index ee1c19561..f357494df 100644 --- a/docs/api/logs.rst +++ b/docs/api/logs.rst @@ -4,172 +4,9 @@ Log file management ******************* -.. note:: +Log file management (and logging configuration) was moved into a bundled plugin in OctoPrint 1.3.7. Refer to +:ref:`the Logging's plugins API ` for the API documentation. - All log file management operations require admin rights. - -.. contents:: - -.. _sec-api-logs-list: - -Retrieve a list of available log files -====================================== - -.. http:get:: /api/logs - - Retrieve information regarding all log files currently available and regarding the disk space still available - in the system on the location the log files are being stored. - - Returns a :ref:`Logfile Retrieve response `. - - **Example** - - .. sourcecode:: http - - GET /api/logs HTTP/1.1 - Host: example.com - X-Api-Key: abcdef... - - .. sourcecode:: http - - HTTP/1.1 200 OK - Content-Type: application/json - - { - "files" : [ - { - "date" : 1393158814, - "name" : "octoprint.log", - "size" : 43712, - "refs": { - "resource": "http://example.com/api/logs/octoprint.log", - "download": "http://example.com/downloads/logs/octoprint.log" - } - }, - { - "date" : 1392628936, - "name" : "octoprint.log.2014-02-17", - "size" : 13205, - "refs": { - "resource": "http://example.com/api/logs/octoprint.log.2014-02-17", - "download": "http://example.com/downloads/logs/octoprint.log.2014-02-17" - } - }, - { - "date" : 1393158814, - "name" : "serial.log", - "size" : 1798419, - "refs": { - "resource": "http://example.com/api/logs/serial.log", - "download": "http://example.com/downloads/logs/serial.log" - } - } - ], - "free": 12237201408 - } - - :statuscode 200: No error - :statuscode 403: If the given API token did not have admin rights associated with it - -.. _sec-api-logs-delete: - -Delete a specific logfile -========================= - -.. http:delete:: /api/logs/(path:filename) - - Delete the selected log file with name `filename`. - - Returns a :http:statuscode:`204` after successful deletion. - - **Example Request** - - .. sourcecode:: http - - DELETE /api/logs/octoprint.log.2014-02-17 HTTP/1.1 - Host: example.com - X-Api-Key: abcdef... - - :param filename: The filename of the log file to delete - :statuscode 204: No error - :statuscode 403: If the given API token did not have admin rights associated with it - :statuscode 404: If the file was not found - -.. _sec-api-logs-datamodel: - -Data model -========== - -.. _sec-api-logs-datamodel-retrieveresponse: - -Logfile Retrieve Response -------------------------- - -.. list-table:: - :widths: 15 5 10 30 - :header-rows: 1 - - * - Name - - Multiplicity - - Type - - Description - * - ``files`` - - 0..* - - Array of :ref:`File information items ` - - The list of requested files. Might be an empty list if no files are available - * - ``free`` - - 1 - - String - - The amount of disk space in bytes available in the local disk space (refers to OctoPrint's ``logs`` folder). - -.. _sec-api-logs-datamodel-fileinfo: - -File information ----------------- - -.. list-table:: - :widths: 15 5 10 30 - :header-rows: 1 - - * - Name - - Multiplicity - - Type - - Description - * - ``name`` - - 1 - - String - - The name of the file - * - ``size`` - - 1 - - Number - - The size of the file in bytes. - * - ``date`` - - 1 - - Unix timestamp - - The timestamp when this file was last modified. - * - ``refs`` - - 1 - - :ref:`sec-api-logs-datamodel-ref` - - References relevant to this file - -.. _sec-api-logs-datamodel-ref: - -References ----------- - -.. list-table:: - :widths: 15 5 10 30 - :header-rows: 1 - - * - Name - - Multiplicity - - Type - - Description - * - ``resource`` - - 1 - - URL - - The resource that represents the file (e.g. for deleting) - * - ``download`` - - 1 - - URL - - The download URL for the file +The former endpoints ``/api/logs`` and ``api/logs/`` are marked as deprecated but still work for now. New +client implementations should directly use the new endpoints provided by the bundled plugin. Existing implementations +should adapt their endpoints as soon as possible. diff --git a/docs/bundledplugins/cura.rst b/docs/bundledplugins/cura.rst index aac96397f..d365e9ac3 100644 --- a/docs/bundledplugins/cura.rst +++ b/docs/bundledplugins/cura.rst @@ -1,4 +1,4 @@ -.. _sec-bundledplugins_cura: +.. _sec-bundledplugins-cura: Cura ==== diff --git a/docs/bundledplugins/index.rst b/docs/bundledplugins/index.rst index d5935a96a..53516474c 100644 --- a/docs/bundledplugins/index.rst +++ b/docs/bundledplugins/index.rst @@ -9,5 +9,6 @@ Bundled Plugins cura.rst discovery.rst + logging.rst pluginmanager.rst softwareupdate.rst diff --git a/docs/bundledplugins/logging.rst b/docs/bundledplugins/logging.rst new file mode 100644 index 000000000..67e0a923e --- /dev/null +++ b/docs/bundledplugins/logging.rst @@ -0,0 +1,238 @@ +.. _sec-bundledplugins-logging: + +Logging +======= + +The OctoPrint Logging plugin comes bundled with OctoPrint starting with version 1.3.7. + +It implements the log management functionality that was formerly part of the core application and adds features to +configure logging levels for sub modules through the included settings dialog. + +.. _fig-bundledplugins-logging-settings: +.. figure:: ../images/bundledplugins-logging-settings.png + :align: center + :alt: Logging plugin + + The settings dialog of the Logging plugin + +.. _sec-bundledplugins-logging-api: + +API +--- + +.. note:: + + All log file management operations require admin rights. + +.. _sec-bundledplugins-logging-api-list_logs: + +Retrieve a list of available log files +++++++++++++++++++++++++++++++++++++++ + +.. http:get:: /plugin/logging/logs + + Retrieve information regarding all log files currently available and regarding the disk space still available + in the system on the location the log files are being stored. + + Returns a :ref:`Logfile Retrieve response `. + + **Example** + + .. sourcecode:: http + + GET /plugin/logging/logs HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "files" : [ + { + "date" : 1393158814, + "name" : "octoprint.log", + "size" : 43712, + "refs": { + "resource": "http://example.com/plugin/logging/logs/octoprint.log", + "download": "http://example.com/downloads/logs/octoprint.log" + } + }, + { + "date" : 1392628936, + "name" : "octoprint.log.2014-02-17", + "size" : 13205, + "refs": { + "resource": "http://example.com/plugin/logging/logs/octoprint.log.2014-02-17", + "download": "http://example.com/downloads/logs/octoprint.log.2014-02-17" + } + }, + { + "date" : 1393158814, + "name" : "serial.log", + "size" : 1798419, + "refs": { + "resource": "http://example.com/plugin/logging/logs/serial.log", + "download": "http://example.com/downloads/logs/serial.log" + } + } + ], + "free": 12237201408 + } + + :statuscode 200: No error + :statuscode 403: If the given API token did not have admin rights associated with it + +.. _sec-bundledplugins-logging-api-delete_logs: + +Delete a specific logfile ++++++++++++++++++++++++++ + +.. http:delete:: /plugin/logging/logs/(path:filename) + + Delete the selected log file with name `filename`. + + Returns a :http:statuscode:`204` after successful deletion. + + **Example Request** + + .. sourcecode:: http + + DELETE /plugin/logging/logs/octoprint.log.2014-02-17 HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + + :param filename: The filename of the log file to delete + :statuscode 204: No error + :statuscode 403: If the given API token did not have admin rights associated with it + :statuscode 404: If the file was not found + +.. _sec-bundledplugins-logging-api-datamodel: + +Data model +++++++++++ + +.. _sec-bundledplugins-logging-api-datamodel-retrieveresponse: + +Logfile Retrieve Response +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``files`` + - 0..* + - Array of :ref:`File information items ` + - The list of requested files. Might be an empty list if no files are available + * - ``free`` + - 1 + - String + - The amount of disk space in bytes available in the local disk space (refers to OctoPrint's ``logs`` folder). + +.. _sec-bundledplugins-logging-api-datamodel-fileinfo: + +File information +~~~~~~~~~~~~~~~~ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``name`` + - 1 + - String + - The name of the file + * - ``size`` + - 1 + - Number + - The size of the file in bytes. + * - ``date`` + - 1 + - Unix timestamp + - The timestamp when this file was last modified. + * - ``refs`` + - 1 + - :ref:`References ` + - References relevant to this file + +.. _sec-bundledplugins-logging-api-datamodel-ref: + +References +~~~~~~~~~~ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``resource`` + - 1 + - URL + - The resource that represents the file (e.g. for deleting) + * - ``download`` + - 1 + - URL + - The download URL for the file + +.. _sec-bundledplugins-logging-jsclientlib: + +JS Client Library +----------------- + +:mod:`OctoPrintClient.plugins.logging` +-------------------------------------- + +.. note:: + + All methods here require that the used API token or a the existing browser session + has admin rights. + +.. js:function:: OctoPrintClient.plugins.logging.listLogs(opts) + + Retrieves a list of log files. + + See :ref:`Retrieve a list of available log files ` for details. + + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.logging.deleteLog(path, opts) + + Deletes the specified log ``path``. + + See :ref:`Delete a specific log file ` for details. + + :param string path: The path to the log file to delete + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.plugins.logging.downloadLog(path, opts) + + Downloads the specified log ``file``. + + See :js:func:`OctoPrint.download` for more details on the underlying library download mechanism. + + :param string path: The path to the log file to download + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. _sec-bundledplugins-logging-sourcecode: + +Source Code +----------- + +The source of the Logging plugin is bundled with OctoPrint and can be found in its source repository under ``src/octoprint/plugins/logging``. diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index b68a6751b..dfc837f36 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -213,6 +213,17 @@ Version checks information and whether the current version is up-to-date or not, see below for details. + * ``always_current``: Always reports that no update is necessary. Useful for debugging + software update mechanisms during development. Additional config parameters: + + * ``current_version``: Version to report for both local and remote version. + + * ``never_current``: Always reports that an update is necessary. Useful for debugging + software update mechanisms during development. Additional config parameters: + + * ``local_version``: Current local version. Defaults to ``1.0.0``. + * ``remote_version``: Remote version to offer update to. Defaults to ``1.0.1``. + .. _sec-bundledplugins-softwareupdate-configuration-updatemethods: Update methods diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 3465fd5d1..7205ee149 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -36,7 +36,7 @@ Use the following settings to enable access control: # If set to true, will automatically log on clients originating from any of the networks defined in # "localNetworks" as the user defined in "autologinAs". Defaults to false. - autologinLocal: true + autologinLocal: false # The name of the user to automatically log on clients originating from "localNetworks" as. Must # be the name of one of your configured users. @@ -51,6 +51,17 @@ Use the following settings to enable access control: - 127.0.0.0/8 - 192.168.1.0/24 + # Whether to trust Basic Authentication headers. If you have setup Basic Authentication in front of + # OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will + # be logged into OctoPrint as the user user during Basic Authentication. Your should ONLY ENABLE THIS if your + # OctoPrint instance is only accessible through a connection locked down through Basic Authentication! + trustBasicAuthentication: false + + # Whether to also check the password provided through Basic Authentication if the Basic Authentication + # header is to be trusted. Disabling this will only match the user name in the Basic Authentication + # header and login the user without further checks. Use with caution. + checkBasicAuthenticationPassword: true + .. _sec-configuration-config_yaml-api: API @@ -522,52 +533,16 @@ Use the following settings to enable or disable OctoPrint features: .. code-block:: yaml feature: + # Whether to enable the gcode viewer in the UI or not gCodeVisualizer: true # Whether to enable the temperature graph in the UI or not temperatureGraph: true - # Specifies whether OctoPrint should wait for the start response from the printer before trying to send commands - # during connect. - waitForStartOnConnect: false - - # Specifies whether OctoPrint should send linenumber + checksum with every printer command. Needed for - # successful communication with Repetier firmware - alwaysSendChecksum: false - - # Specifies whether OctoPrint should also send linenumber + checksum with commands that are *not* - # detected as valid GCODE (as in, they do not match the regular expression "^\s*([GM]\d+|T)"). - sendChecksumWithUnknownCommands: false - - # Specifies whether OctoPrint should also use up acknowledgments ("ok") for commands that are *not* - # detected as valid GCODE (as in, they do not match the regular expression "^\s*([GM]\d+|T)"). - unknownCommandsNeedAck: false - - # Whether to ignore the first ok after a resend response. Needed for successful communication with - # Repetier firmware - swallowOkAfterResend: false - # Specifies whether support for SD printing and file management should be enabled sdSupport: true - # Specifies whether firmware expects relative paths for selecting SD files - sdRelativePath: false - - # Whether to always assume that an SD card is present in the printer. - # Needed by some firmwares which don't report the SD card status properly. - sdAlwaysAvailable: false - - # Whether the printer sends repetier style target temperatures in the format - # TargetExtr0: - # instead of attaching that information to the regular M105 responses - repetierTargetTemp: false - - # Whether to enable external heatup detection (to detect heatup triggered e.g. through the printer's LCD panel or - # while printing from SD) or not. Causes issues with Repetier's "first ok then response" approach to - # communication, so disable for printers running Repetier firmware. - externalHeatupDetection: true - # Whether to enable the keyboard control feature in the control tab keyboardControl: true @@ -575,28 +550,16 @@ Use the following settings to enable or disable OctoPrint features: # notifications instead (false) pollWatched: false - # Whether to ignore identical resends from the printer (true, repetier) or not (false) - ignoreIdenticalResends: false - - # If ignoredIdenticalResends is true, how many consecutive identical resends to ignore - identicalResendsCount: 7 - - # Whether to support F on its own as a valid GCODE command (true) or not (false) - supportFAsCommand: false - # Whether to enable model size detection and warning (true) or not (false) modelSizeDetection: true - # Whether to attempt to auto detect the firmware of the printer and adjust settings - # accordingly (true) or not and rely on manual configuration (false) - firmwareDetection: true - # Whether to show a confirmation on print cancelling (true) or not (false) printCancelConfirmation: true - # Whether to block all sending to the printer while a G4 (dwell) command is active (true, repetier) - # or not (false) - blockWhileDwelling: false + # Commands that should never be auto-uppercased when sent to the printer through the Terminal tab. + # Defaults to only M117. + autoUppercaseBlacklist: + - M117 .. _sec-configuration-config_yaml-folder: @@ -800,6 +763,10 @@ Use the following settings to configure the serial connection to the printer: # Defaults to 30 sec communication: 30 + # Timeout during serial communication when busy protocol support is detected, in seconds. + # Defaults to 3 sec + communicationBusy: 3 + # Timeout after which to query temperature when no target is set temperature: 5 @@ -824,7 +791,7 @@ Use the following settings to configure the serial connection to the printer: # Maximum number of write attempts to serial during which nothing can be written before the communication # with the printer is considered dead and OctoPrint will disconnect with an error - maxWritePasses: + maxWritePasses: 5 # Use this to define additional patterns to consider for serial port listing. Must be a valid # "glob" pattern (see http://docs.python.org/2/library/glob.html). Defaults to not set. @@ -858,10 +825,6 @@ Use the following settings to configure the serial connection to the printer: helloCommand: - M110 N0 - # Commands that should never be auto-uppercased when sent to the printer. Defaults to only M117. - autoUppercaseBlacklist: - - M117 - # Whether to disconnect on errors or not disconnectOnErrors: true @@ -872,6 +835,60 @@ Use the following settings to configure the serial connection to the printer: # impact, leave on if possible please logResends: true + # Specifies whether OctoPrint should wait for the start response from the printer before trying to send commands + # during connect. + waitForStartOnConnect: false + + # Specifies whether OctoPrint should send linenumber + checksum with every printer command. Needed for + # successful communication with Repetier firmware + alwaysSendChecksum: false + + # Specifies whether OctoPrint should also send linenumber + checksum with commands that are *not* + # detected as valid GCODE (as in, they do not match the regular expression "^\s*([GM]\d+|T)"). + sendChecksumWithUnknownCommands: false + + # Specifies whether OctoPrint should also use up acknowledgments ("ok") for commands that are *not* + # detected as valid GCODE (as in, they do not match the regular expression "^\s*([GM]\d+|T)"). + unknownCommandsNeedAck: false + + # Whether to ignore the first ok after a resend response. Needed for successful communication with + # Repetier firmware + swallowOkAfterResend: false + + # Specifies whether firmware expects relative paths for selecting SD files + sdRelativePath: false + + # Whether to always assume that an SD card is present in the printer. + # Needed by some firmwares which don't report the SD card status properly. + sdAlwaysAvailable: false + + # Whether the printer sends repetier style target temperatures in the format + # TargetExtr0: + # instead of attaching that information to the regular M105 responses + repetierTargetTemp: false + + # Whether to enable external heatup detection (to detect heatup triggered e.g. through the printer's LCD panel or + # while printing from SD) or not. Causes issues with Repetier's "first ok then response" approach to + # communication, so disable for printers running Repetier firmware. + externalHeatupDetection: true + + # Whether to ignore identical resends from the printer (true, repetier) or not (false) + ignoreIdenticalResends: false + + # If ignoredIdenticalResends is true, how many consecutive identical resends to ignore + identicalResendsCount: 7 + + # Whether to support F on its own as a valid GCODE command (true) or not (false) + supportFAsCommand: false + + # Whether to attempt to auto detect the firmware of the printer and adjust settings + # accordingly (true) or not and rely on manual configuration (false) + firmwareDetection: true + + # Whether to block all sending to the printer while a G4 (dwell) command is active (true, repetier) + # or not (false) + blockWhileDwelling: false + # Whether to support resends without follow-up ok or not supportResendsWithoutOk: false @@ -879,6 +896,14 @@ Use the following settings to configure the serial connection to the printer: # the responds skips on the ok) triggerOkForM29: true + capabilities: + + # Whether to enable temperature autoreport in the firmware if its support is detected + autoreport_temp: true + + # Whether to shorten the communication timeout if the firmware seems to support the busy protocol + busy_protocol: true + .. _sec-configuration-config_yaml-server: Server @@ -990,6 +1015,17 @@ Use the following settings to configure the server: # DNS port against which to check (default: 53 - the default DNS port) port: 53 + # Configuration of the plugin blacklist + pluginBlacklist: + # whether use of the blacklist is enabled, defaults to false + enabled: false + + # the URL from which to fetch the blacklist + url: http://plugins.octoprint.org/blacklist.json + + # time to live of the cached blacklist, in seconds (default: 15 minutes) + ttl: 15 * 60 + # Settings of when to display what disk space warning diskspace: diff --git a/docs/features/action_commands.rst b/docs/features/action_commands.rst index 82591cf9e..502f068b8 100644 --- a/docs/features/action_commands.rst +++ b/docs/features/action_commands.rst @@ -21,16 +21,20 @@ Action commands are a feature defined for the GCODE based RepRap communication p OctoPrint out of the box supports handling of the above mentioned commands: +cancel + When this command is received from the printer, OctoPrint will cancel a current print job like if the + "Cancel" button had been clicked. + pause - When this command is received from the printer, OctoPrint will pause streaming of a current print job just like if the + When this command is received from the printer, OctoPrint will pause a current print job just like if the "Pause" button had been clicked. resume - When this command is received from the printer, OctoPrint will resume streaming of a current print job just like if + When this command is received from the printer, OctoPrint will resume a current print job just like if the "Resume" button had been clicked. disconnect - When this command is Received from the printer, OctoPrint will immediately disconnect from it. + When this command is received from the printer, OctoPrint will immediately disconnect from it. Support for additional commands may be added by plugins by implementing a handler for the :ref:`octoprint.comm.protocol.action ` hook. diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index 9c12a35c7..2533bdada 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -80,6 +80,7 @@ All GCODE scripts have access to the following template variables through the te note that ``actual`` and ``target`` might be ``None``. * ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type`` and ``script.name`` respectively. + * ``plugins``: An object containing variables provided by plugins (e.g ``plugins.myplugin.myvariable``) There are a few additional template variables available for the following specific scripts: @@ -146,7 +147,7 @@ Out of the box, OctoPrint defaults to the following script setup for ``afterPrin ;disable all heaters {% snippet 'disable_hotends' %} - [% snippet 'disable_bed' %} + {% snippet 'disable_bed' %} ;disable fan M106 S0 @@ -174,6 +175,75 @@ As you can see, the ``disable_hotends`` and ``disable_bed`` snippets utilize the extruders and set their temperature to 0, and to also set the bed temperature to 0 if a heated bed is configured. +.. _sec-features-gcode_scripts-examples: + +Examples +-------- + +.. _sec-features-gcode_scripts-examples-more_nifty_pause_and_resume: + +More nifty pause and resume +........................... + +If you do not have a multi-extruder setup, aren't printing from SD and have "Log position on pause" enabled under +Settings > Serial > Advanced options, the following ``afterPrintPaused`` and +``beforePrintResumed`` scripts might be interesting for you. With something like them in place, OctoPrint will move your print head +out of the way to a safe rest position (here ``G1 X0 Y0``, you might want to adjust that) on pause and move it back +to the persisted pause position on resume, making sure to also reset the extruder and feedrate. + +.. code-block:: jinja + :caption: ``afterPrintPaused`` script + + {% if pause_position.x is not none %} + ; relative XYZE + G91 + M83 + + ; retract filament, move Z slightly upwards + G1 Z+5 E-5 F4500 + + ; absolute XYZE + M82 + G90 + + ; move to a safe rest position, adjust as necessary + G1 X0 Y0 + {% endif %} + +.. code-block:: jinja + :caption: ``beforePrintResumed`` script + + {% if pause_position.x is not none %} + ; relative extruder + M83 + + ; prime nozzle + G1 E-5 F4500 + G1 E5 F4500 + G1 E5 F4500 + + ; absolute E + M82 + + ; absolute XYZ + G90 + + ; reset E + G92 E{{ pause_position.e }} + + ; move back to pause position XYZ + G1 X{{ pause_position.x }} Y{{ pause_position.y }} Z{{ pause_position.z }} F4500 + + ; reset to feed rate before pause if available + {% if pause_position.f is not none %}G1 F{{ pause_position.f }}{% endif %} + {% endif %} + +.. warning:: + + As mentioned in the warning above and the description of the example itself, this will *only* work if you are + not printing from SD and not using multiple extruders since OctoPrint will only then be able to track the + necessary position data and print parameters due to firmware limitations. + .. seealso:: `Jinja Template Designer Documentation `_ diff --git a/docs/images/bundledplugins-logging-settings.png b/docs/images/bundledplugins-logging-settings.png new file mode 100644 index 000000000..c5b761246 Binary files /dev/null and b/docs/images/bundledplugins-logging-settings.png differ diff --git a/docs/jsclientlib/logs.rst b/docs/jsclientlib/logs.rst index 41d928661..fae86fb55 100644 --- a/docs/jsclientlib/logs.rst +++ b/docs/jsclientlib/logs.rst @@ -3,37 +3,9 @@ :mod:`OctoPrintClient.logs` --------------------------- -.. note:: - - All methods here require that the used API token or a the existing browser session - has admin rights. - -.. js:function:: OctoPrintClient.logs.list(opts) - - Retrieves a list of log files. - - See :ref:`Retrieve a list of available log files ` for details. - - :param object opts: Additional options for the request - :returns Promise: A `jQuery Promise `_ for the request's response - -.. js:function:: OctoPrintClient.logs.delete(path, opts) - - Deletes the specified log ``path``. - - See :ref:`Delete a specific log file ` for details. - - :param string path: The path to the log file to delete - :param object opts: Additional options for the request - :returns Promise: A `jQuery Promise `_ for the request's response - -.. js:function:: OctoPrintClient.logs.download(path, opts) - - Downloads the specified log ``file``. - - See :js:func:`OctoPrint.download` for more details on the underlying library download mechanism. - - :param string path: The path to the log file to download - :param object opts: Additional options for the request - :returns Promise: A `jQuery Promise `_ for the request's response +Log file management (and logging configuration) was moved into a bundled plugin in OctoPrint 1.3.7. Refer to +:ref:`the Logging's plugins JS Client Library ` for the JS Client documentation. +The former module ``OctoPrintClient.logs`` and its methods are marked as deprecated but still work for now. New +client implementations should directly use the new module provided by the bundled plugin. Existing implementations +should adapt their used module as soon as possible. diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index ca0af0420..9b5061ae0 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -420,7 +420,7 @@ This describes actually four hooks: * ``octoprint.comm.protocol.gcode.sending`` * ``octoprint.comm.protocol.gcode.sent`` -.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, *args, **kwargs) +.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs) Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases are the following: @@ -443,7 +443,39 @@ This describes actually four hooks: the communication layer or before they are actually sent over the serial port, or to react to the queuing or sending of commands after the fact. The hook handler will be called with the processing ``phase``, the ``cmd`` to be sent to the printer as well as the ``cmd_type`` parameter used for enqueuing (OctoPrint will make sure that the send queue - will never contain more than one line with the same ``cmd_type``) and the detected gcode command (if it is one). + will never contain more than one line with the same ``cmd_type``) and the detected ``gcode`` command (if it is one) + as well as its ``subcode`` (if it has one). OctoPrint will also provide any ``tags`` attached to the command throughout + its lifecycle. + + Tags are arbitrary strings that can be attached to a command as it moves through the various phases and can be used to e.g. + distinguish between commands that originated in a printed file (``source:file``) vs. a configured GCODE script + (``source:script``) vs. an API call (``source:api``) vs. a plugin (``source:plugin`` or ``source:rewrite`` and + ``plugin:``). If during development you want to get an idea of the various possible tags, set + the logger ``octoprint.util.comm.command_phases`` to ``DEBUG``, connect to a printer (real or virtual) and take a + look at your ``octoprint.log`` during serial traffic: + + .. code-block:: none + + 2018-02-16 18:20:31,213 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ] + 2018-02-16 18:20:31,216 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: M117 Before T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ] + 2018-02-16 18:20:31,217 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: M117 Before T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ] + 2018-02-16 18:20:31,217 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ] + 2018-02-16 18:20:31,219 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: M117 After T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ] + 2018-02-16 18:20:31,220 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: M117 Before T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ] + 2018-02-16 18:20:31,230 - tornado.access - INFO - 204 POST /api/printer/command (127.0.0.1) 23.00ms + 2018-02-16 18:20:31,232 - tornado.access - INFO - 200 POST /api/printer/command (127.0.0.1) 25.00ms + 2018-02-16 18:20:31,232 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ] + 2018-02-16 18:20:31,234 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: T0 | gcode: T | tags: [ api:printer.command, source:api, trigger:printer.commands ] + 2018-02-16 18:20:31,242 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: M117 After T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ] + 2018-02-16 18:20:31,243 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: M117 After T! | gcode: M117 | tags: [ api:printer.command, phase:queuing, plugin:multi_gcode_test, source:api, source:rewrite, trigger:printer.commands ] + 2018-02-16 18:20:38,552 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ] + 2018-02-16 18:20:38,552 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ] + 2018-02-16 18:20:38,553 - octoprint.util.comm.command_phases - DEBUG - phase: sending | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ] + 2018-02-16 18:20:38,553 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: G1 X10 F6000 | gcode: G1 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ] + 2018-02-16 18:20:38,555 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: G1 X10 F6000 | gcode: G1 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ] + 2018-02-16 18:20:38,556 - octoprint.util.comm.command_phases - DEBUG - phase: sent | command: G91 | gcode: G91 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ] + 2018-02-16 18:20:38,556 - octoprint.util.comm.command_phases - DEBUG - phase: queuing | command: G90 | gcode: G90 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ] + 2018-02-16 18:20:38,558 - octoprint.util.comm.command_phases - DEBUG - phase: queued | command: G90 | gcode: G90 | tags: [ api:printer.printhead, source:api, trigger:printer.commands, trigger:printer.jog ] Defining a ``cmd_type`` other than None will make sure OctoPrint takes care of only having one command of that type in its sending queue. Predefined types are ``temperature_poll`` for temperature polling via ``M105`` and @@ -482,6 +514,8 @@ This describes actually four hooks: should use this option. * A 2-tuple consisting of a rewritten version of the ``cmd`` and the ``cmd_type``, e.g. ``return "M105", "temperature_poll"``. Handlers which wish to rewrite both the command and the command type should use this option. + * A 3-tuple consisting of a rewritten version of the ``cmd``, the ``cmd_type`` and any additional ``tags`` you might + want to attach to the lifecycle of the command in a set, e.g. ``return "M105", "temperature_poll", {"my_custom_tag"}`` * **"queuing" phase only**: A list of any of the above to allow for expanding one command into many. The following example shows how any queued command could be turned into a sequence of a temperature query, line number reset, display of the ``gcode`` on the printer's display and finally the actual command (this example @@ -489,7 +523,7 @@ This describes actually four hooks: .. code-block:: python - def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs): + def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None *args, **kwargs): if gcode or not cmd.startswith("@foo"): return @@ -524,6 +558,7 @@ This describes actually four hooks: :param str gcode: Parsed GCODE command, e.g. ``G0`` or ``M110``, may also be None if no known command could be parsed :param str subcode: Parsed subcode of the GCODE command, e.g. ``1`` for ``M80.1``. Will be None if no subcode was provided or no command could be parsed. + :param set tags: Tags attached to the command :return: None, 1-tuple, 2-tuple or string, see the description above for details. .. _sec-plugins-hook-comm-protocol-gcode-received: @@ -559,19 +594,19 @@ octoprint.comm.protocol.scripts .. py:function:: protocol_scripts_hook(comm_instance, script_type, script_name, *args, **kwargs) - Return a prefix to prepend and a postfix to append to the script ``script_name`` of type ``type``. Handlers should + Return a prefix to prepend, postfix to append, and optionally a dictionary of variables to provide to the script ``script_name`` of type ``type``. Handlers should make sure to only proceed with returning additional scripts if the ``script_type`` and ``script_name`` match handled scripts. If not, None should be returned directly. - If the hook handler has something to add to the specified script, it may return a 2-tuple, with the first entry - defining the prefix (what to *prepend* to the script in question) and the last entry defining the postfix (what to - *append* to the script in question). Both prefix and postfix can be None to signify that nothing should be prepended + If the hook handler has something to add to the specified script, it may return a 2-tuple or a 3-tuple with the first entry + defining the prefix (what to *prepend* to the script in question), the second entry defining the postfix (what to + *append* to the script in question), and finally if desired a dictionary of variables to be made available to the script. Both prefix and postfix can be None to signify that nothing should be prepended respectively appended. - The returned entries may be either iterables of script lines or a string including newlines of the script lines (which + The returned prefix and postfix entries may be either iterables of script lines or a string including newlines of the script lines (which will be split by the caller if necessary). - **Example:** + **Example 1:** Appends an ``M117 OctoPrint connected`` to the configured ``afterPrinterConnected`` GCODE script. @@ -580,10 +615,19 @@ octoprint.comm.protocol.scripts :tab-width: 4 :caption: `message_on_connect.py `_ + **Example 2:** + + Provides the variable ``myvariable`` to the configured ``beforePrintStarted`` GCODE script. + + .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/gcode_script_variables.py + :linenos: + :tab-width: 4 + :caption: `gcode_script_variables.py `_ + :param MachineCom comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook. :param str script_type: The type of the script for which the hook was called, currently only "gcode" is supported here. :param str script_name: The name of the script for which the hook was called. - :return: A 2-tuple in the form ``(prefix, postfix)`` or None + :return: A 2-tuple in the form ``(prefix, postfix)``, 3-tuple in the form ``(prefix, postfix, variables)``, or None :rtype: tuple or None .. _sec-plugins-hook-comm-protocol-temperatures-received: diff --git a/setup.py b/setup.py index b78980a37..c098e8617 100644 --- a/setup.py +++ b/setup.py @@ -27,7 +27,7 @@ INSTALL_REQUIRES = [ "Flask-Babel>=0.11,<0.12", "Flask-Assets>=0.12,<0.13", "markdown>=2.6.4,<2.7", - "pyserial>=3.2.1,<3.3", + "pyserial>=3.4,<3.5", "netaddr>=0.7.17,<0.8", "watchdog>=0.8.3,<0.9", "sarge>=0.1.4,<0.2", @@ -60,7 +60,7 @@ EXTRA_REQUIRES = dict( # Dependencies for developing OctoPrint develop=[ # Testing dependencies - "mock>=2.0,<2.1", + "mock>=2.0.0,<3", "nose>=1.3.0,<1.4", "ddt", diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 7a85c4879..f04a963f1 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -12,7 +12,7 @@ versions = get_versions() __version__ = versions['version'] __branch__ = versions.get('branch', None) -__display_version__ = "{} ({} branch)".format(__version__, __branch__) if __branch__ else __version__ +__display_version__ = __version__ __revision__ = versions.get('full-revisionid', versions.get('full', None)) del versions @@ -96,17 +96,17 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, after_safe_mode(**kwargs) event_manager = init_event_manager(settings) - + kwargs["event_manager"] = event_manager if callable(after_event_manager): after_event_manager(**kwargs) - + connectivity_checker = init_connectivity_checker(settings, event_manager) - + kwargs["connectivity_checker"] = connectivity_checker if callable(after_connectivity_checker): after_connectivity_checker(**kwargs) - + plugin_manager = init_pluginsystem(settings, safe_mode=safe_mode, ignore_blacklist=ignore_blacklist, @@ -115,10 +115,10 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, if callable(after_plugin_manager): after_plugin_manager(**kwargs) - + environment_detector = init_environment_detector(plugin_manager) kwargs["environment_detector"] = environment_detector - + if callable(after_environment_detector): after_environment_detector(**kwargs) @@ -314,7 +314,7 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti settings.getBaseFolder("plugins")] plugin_entry_points = ["octoprint.plugin"] plugin_disabled_list = settings.get(["plugins", "_disabled"]) - + plugin_blacklist = [] if not ignore_blacklist and settings.getBoolean(["server", "pluginBlacklist", "enabled"]): plugin_blacklist = get_plugin_blacklist(settings, connectivity_checker=connectivity_checker) @@ -403,34 +403,34 @@ def get_plugin_blacklist(settings, connectivity_checker=None): import os import time import yaml - + from octoprint.util import bom_aware_open from octoprint.util.version import is_octoprint_compatible - + logger = log.getLogger(__name__ + ".startup") - + if connectivity_checker is not None and not connectivity_checker.online: logger.info("We don't appear to be online, not fetching plugin blacklist") return [] - + def format_blacklist(entries): format_entry = lambda x: "{} ({})".format(x[0], x[1]) if isinstance(x, (list, tuple)) and len(x) == 2 \ else "{} (any)".format(x) return ", ".join(map(format_entry, entries)) - + def process_blacklist(entries): result = [] - + if not isinstance(entries, list): return result - + for entry in entries: if not "plugin" in entry: continue - + if "octoversions" in entry and not is_octoprint_compatible(*entry["octoversions"]): continue - + if "version" in entry: logger.debug("Blacklisted plugin: {}, version: {}".format(entry["plugin"], entry["version"])) result.append((entry["plugin"], entry["version"])) @@ -441,28 +441,28 @@ def get_plugin_blacklist(settings, connectivity_checker=None): else: logger.debug("Blacklisted plugin: {}".format(entry["plugin"])) result.append(entry["key"]) - + return result - + def fetch_blacklist_from_cache(path, ttl): if not os.path.isfile(path): return None - + if os.stat(path).st_mtime + ttl < time.time(): return None - + with bom_aware_open(path, encoding="utf-8", mode="r") as f: result = yaml.safe_load(f) - + if isinstance(result, list): return result - + def fetch_blacklist_from_url(url, timeout=3, cache=None): result = [] try: r = requests.get(url, timeout=timeout) result = process_blacklist(r.json()) - + if cache is not None: try: with bom_aware_open(cache, encoding="utf-8", mode="w") as f: @@ -472,23 +472,23 @@ def get_plugin_blacklist(settings, connectivity_checker=None): except: logger.info("Unable to fetch plugin blacklist from {}, proceeding without it.".format(url)) return result - + try: # first attempt to fetch from cache cache_path = os.path.join(settings.getBaseFolder("data"), "plugin_blacklist.yaml") ttl = settings.getInt(["server", "pluginBlacklist", "ttl"]) blacklist = fetch_blacklist_from_cache(cache_path, ttl) - + if blacklist is None: # no result from the cache, let's fetch it fresh url = settings.get(["server", "pluginBlacklist", "url"]) timeout = settings.getFloat(["server", "pluginBlacklist", "timeout"]) blacklist = fetch_blacklist_from_url(url, timeout=timeout, cache=cache_path) - + if blacklist is None: # still now result, so no blacklist blacklist = [] - + if blacklist: logger.info("Blacklist processing done, " "adding {} blacklisted plugin versions: {}".format(len(blacklist), @@ -509,16 +509,16 @@ def init_event_manager(settings): def init_connectivity_checker(settings, event_manager): from octoprint.events import Events from octoprint.util import ConnectivityChecker - + # start regular check if we are connected to the internet connectivityEnabled = settings.getBoolean(["server", "onlineCheck", "enabled"]) connectivityInterval = settings.getInt(["server", "onlineCheck", "interval"]) connectivityHost = settings.get(["server", "onlineCheck", "host"]) connectivityPort = settings.getInt(["server", "onlineCheck", "port"]) - + def on_connectivity_change(old_value, new_value): event_manager.fire(Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value, new=new_value)) - + connectivityChecker = ConnectivityChecker(connectivityInterval, connectivityHost, port=connectivityPort, diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index a9d90ea08..1e7a98f19 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -81,8 +81,8 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi safe_mode=safe_mode, ignore_blacklist=ignore_blacklist, after_safe_mode=log_startup, - after_plugin_manager=log_register_rollover) - + after_environment_detector=log_register_rollover) + settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components except FatalStartupError as e: @@ -152,7 +152,7 @@ def enable_safemode(ctx, **kwargs): settings.setBoolean(["server", "startOnceInSafeMode"], True) settings.save() - + click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.") diff --git a/src/octoprint/environment.py b/src/octoprint/environment.py index 13c513ffd..2a369d5ae 100644 --- a/src/octoprint/environment.py +++ b/src/octoprint/environment.py @@ -1,5 +1,9 @@ +# coding=utf-8 from __future__ import absolute_import +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" + import copy import logging import os @@ -11,7 +15,6 @@ import yaml import psutil from octoprint.plugin import EnvironmentDetectionPlugin -from octoprint.util import get_formatted_size from octoprint.util.platform import get_os class EnvironmentDetector(object): @@ -34,58 +37,77 @@ class EnvironmentDetector(object): return copy.deepcopy(self._cache) def run_detection(self, notify_plugins=True): - environment = dict() - environment["os"] = self._detect_os() - environment["python"] = self._detect_python() - environment["hardware"] = self._detect_hardware() + try: + environment = dict() + environment["os"] = self._detect_os() + environment["python"] = self._detect_python() + environment["hardware"] = self._detect_hardware() - plugin_result = self._detect_from_plugins() - if plugin_result: - environment["plugins"] = plugin_result + plugin_result = self._detect_from_plugins() + if plugin_result: + environment["plugins"] = plugin_result - with self._cache_lock: - self._cache = environment + with self._cache_lock: + self._cache = environment - if notify_plugins: - self.notify_plugins() + if notify_plugins: + self.notify_plugins() - return environment + return environment + except: + self._logger.exception("Unexpected error while detecting environment") + with self._cache_lock: + self._cache = dict() + return self._cache def _detect_os(self): return dict(id=get_os(), platform=sys.platform) def _detect_python(self): - result = dict() + result = dict(version="unknown", + pip="unknown") # determine python version - result["version"] = platform.python_version() + try: + result["version"] = platform.python_version() + except: + self._logger.exception("Error detecting python version") # determine if we are running from a virtual environment - 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 + try: + if hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)): + result["virtualenv"] = sys.prefix + except: + self._logger.exception("Error detecting whether we are running in a virtual environment") # try to find pip version try: import pip result["pip"] = pip.__version__ except: - result["pip"] = "unknown" + self._logger.exception("Error detecting pip version") return result def _detect_hardware(self): - cores = psutil.cpu_count() - cpu_freq = psutil.cpu_freq() - ram = psutil.virtual_memory() + result = dict(cores="unknown", + freq="unknown", + ram="unknown") + + try: + cores = psutil.cpu_count() + cpu_freq = psutil.cpu_freq() + ram = psutil.virtual_memory() + if cores: + result["cores"] = cores + if cpu_freq and hasattr(cpu_freq, "max"): + result["freq"] = cpu_freq.max + if ram and hasattr(ram, "total"): + result["ram"] = ram.total + except: + self._logger.exception("Error while detecting hardware environment") - result = dict() - if cores: - result["cores"] = cores - if cpu_freq and hasattr(cpu_freq, "max"): - result["freq"] = cpu_freq.max - if ram and hasattr(ram, "total"): - result["ram"] = ram.total return result def _detect_from_plugins(self): @@ -110,7 +132,10 @@ class EnvironmentDetector(object): else: self._logger.log(level, message) - _log(self._format()) + try: + _log(self._format()) + except: + self._logger.exception("Error logging detected environment") def _format(self): with self._cache_lock: diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 794a7f72a..01622b837 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -470,7 +470,9 @@ class FileManager(object): file_object = hook_file_object queue_entry = self._analysis_queue_entry(destination, path) - self._analysis_queue.dequeue(queue_entry) + + if queue_entry is not None: + self._analysis_queue.dequeue(queue_entry) path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite, display=display) diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index 9c913d815..11c5aac29 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -76,6 +76,9 @@ class AnalysisQueue(object): self._callbacks.remove(callback) def enqueue(self, entry, high_priority=False): + if entry is None: + return False + if not entry.type in self._queues: return False @@ -83,6 +86,9 @@ class AnalysisQueue(object): return True def dequeue(self, entry): + if entry is None: + return False + if not entry.type in self._queues: return False diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index e4d9d9068..dc4e9f16b 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -695,7 +695,7 @@ class LocalFileStorage(StorageInterface): display = destination_data["display"] else: display = None - + destination_meta = self._get_metadata_entry(destination_data["path"], destination_data["name"], default=dict()) if display: @@ -712,14 +712,14 @@ class LocalFileStorage(StorageInterface): shutil.copytree(source_data["fullpath"], destination_data["fullpath"]) except Exception as e: raise StorageError("Could not copy %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e) - + self._set_display_metadata(destination_data, source_data=source_data) return self.path_in_storage(destination_data["fullpath"]) def move_folder(self, source, destination): source_data, destination_data = self._get_source_destination_data(source, destination) - + # only a display rename? Update that and bail early if source_data["fullpath"] == destination_data["fullpath"]: self._set_display_metadata(destination_data) @@ -839,7 +839,7 @@ class LocalFileStorage(StorageInterface): destination_data["path"], destination_data["name"], delete_source=True) self._set_display_metadata(destination_data, source_data=source_data) - + return self.path_in_storage(destination_data["fullpath"]) def has_analysis(self, path): @@ -988,7 +988,7 @@ class LocalFileStorage(StorageInterface): absolute path including leading ``basefolder`` path. """ path = to_unicode(path) - + if len(path): if path[0] == u"/": path = path[1:] @@ -1316,91 +1316,96 @@ class LocalFileStorage(StorageInterface): path_in_location = entry_name if not base else base + entry_name - # file handling - if entry_is_file: - type_path = octoprint.filemanager.get_file_type(entry_name) - if not type_path: - # only supported extensions - continue - else: - file_type = type_path[0] + try: + # file handling + if entry_is_file: + type_path = octoprint.filemanager.get_file_type(entry_name) + if not type_path: + # only supported extensions + continue + else: + file_type = type_path[0] - if entry_name in metadata and isinstance(metadata[entry_name], dict): - entry_metadata = metadata[entry_name] - if not "display" in entry_metadata and entry_display != entry_name: - metadata[entry_name]["display"] = entry_display - entry_metadata["display"] = entry_display + if entry_name in metadata and isinstance(metadata[entry_name], dict): + entry_metadata = metadata[entry_name] + if not "display" in entry_metadata and entry_display != entry_name: + metadata[entry_name]["display"] = entry_display + entry_metadata["display"] = entry_display + metadata_dirty = True + else: + entry_metadata = self._add_basic_metadata(path, entry_name, + display_name=entry_display, + save=False, + metadata=metadata) metadata_dirty = True - else: - entry_metadata = self._add_basic_metadata(path, entry_name, - display_name=entry_display, - save=False, - metadata=metadata) - metadata_dirty = True - # TODO extract model hash from source if possible to recreate link + # TODO extract model hash from source if possible to recreate link - if not entry_filter or entry_filter(entry_name, entry_metadata): - # only add files passing the optional filter - extended_entry_data = dict() - extended_entry_data.update(entry_metadata) - extended_entry_data["name"] = entry_name - extended_entry_data["display"] = entry_metadata.get("display", entry_name) - extended_entry_data["path"] = path_in_location - extended_entry_data["type"] = file_type - extended_entry_data["typePath"] = type_path - stat = entry_stat - if stat: - extended_entry_data["size"] = stat.st_size - extended_entry_data["date"] = int(stat.st_mtime) + if not entry_filter or entry_filter(entry_name, entry_metadata): + # only add files passing the optional filter + extended_entry_data = dict() + extended_entry_data.update(entry_metadata) + extended_entry_data["name"] = entry_name + extended_entry_data["display"] = entry_metadata.get("display", entry_name) + extended_entry_data["path"] = path_in_location + extended_entry_data["type"] = file_type + extended_entry_data["typePath"] = type_path + stat = entry_stat + if stat: + extended_entry_data["size"] = stat.st_size + extended_entry_data["date"] = int(stat.st_mtime) - result[entry_name] = extended_entry_data + result[entry_name] = extended_entry_data - # folder recursion - elif entry_is_dir: - if entry_name in metadata and isinstance(metadata[entry_name], dict): - entry_metadata = metadata[entry_name] - if not "display" in entry_metadata and entry_display != entry_name: - metadata[entry_name]["display"] = entry_display - entry_metadata["display"] = entry_display + # folder recursion + elif entry_is_dir: + if entry_name in metadata and isinstance(metadata[entry_name], dict): + entry_metadata = metadata[entry_name] + if not "display" in entry_metadata and entry_display != entry_name: + metadata[entry_name]["display"] = entry_display + entry_metadata["display"] = entry_display + metadata_dirty = True + elif entry_name != entry_display: + entry_metadata = self._add_basic_metadata(path, entry_name, + display_name=entry_display, + save=False, + metadata=metadata) metadata_dirty = True - elif entry_name != entry_display: - entry_metadata = self._add_basic_metadata(path, entry_name, - display_name=entry_display, - save=False, - metadata=metadata) - metadata_dirty = True - else: - entry_metadata = dict() + else: + entry_metadata = dict() - entry_data = dict( - name=entry_name, - display=entry_metadata.get("display", entry_name), - path=path_in_location, - type="folder", - typePath=["folder"] - ) - if recursive: - sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter, - recursive=recursive) - entry_data["children"] = sub_result - - if not entry_filter or entry_filter(entry_name, entry_data): - def get_size(): - total_size = 0 - for element in entry_data["children"].values(): - if "size" in element: - total_size += element["size"] - - return total_size - - # only add folders passing the optional filter - extended_entry_data = dict() - extended_entry_data.update(entry_data) + entry_data = dict( + name=entry_name, + display=entry_metadata.get("display", entry_name), + path=path_in_location, + type="folder", + typePath=["folder"] + ) if recursive: - extended_entry_data["size"] = get_size() + sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter, + recursive=recursive) + entry_data["children"] = sub_result - result[entry_name] = extended_entry_data + if not entry_filter or entry_filter(entry_name, entry_data): + def get_size(): + total_size = 0 + for element in entry_data["children"].values(): + if "size" in element: + total_size += element["size"] + + return total_size + + # only add folders passing the optional filter + extended_entry_data = dict() + extended_entry_data.update(entry_data) + if recursive: + extended_entry_data["size"] = get_size() + + result[entry_name] = extended_entry_data + except: + # So something went wrong somewhere while processing this file entry - log that and continue + self._logger.exception("Error while processing entry {}".format(entry_path)) + continue # TODO recreate links if we have metadata less entries diff --git a/src/octoprint/logging/handlers.py b/src/octoprint/logging/handlers.py index 7d106a4b1..232216ee0 100644 --- a/src/octoprint/logging/handlers.py +++ b/src/octoprint/logging/handlers.py @@ -27,7 +27,7 @@ class OctoPrintLogHandler(CleaningTimedRotatingFileHandler): def doRollover(self): CleaningTimedRotatingFileHandler.doRollover(self) - for rcb in self.__class__.rollover_callbacks: + for rcb in self.rollover_callbacks: callback, args, kwargs = rcb callback(*args, **kwargs) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 722fca82f..014155097 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -1571,6 +1571,13 @@ class Plugin(object): initialization of the implementation. """ + def __init__(self): + self._identifier = None + self._plugin_name = None + self._plugin_version = None + self._basefolder = None + self._logger = None + def initialize(self): """ Called by the plugin core after performing all injections. Override this to initialize your implementation. diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index bcea5bdfd..41013b34c 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -8,9 +8,11 @@ Please note that the plugin implementation types are documented in the section .. autoclass:: OctoPrintPlugin :show-inheritance: + :members: .. autoclass:: ReloadNeedingPlugin :show-inheritance: + :members: """ @@ -23,6 +25,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from .core import (Plugin, RestartNeedingPlugin, SortablePlugin) +# noinspection PyCompatibility from past.builtins import basestring class OctoPrintPlugin(Plugin): @@ -74,16 +77,39 @@ class OctoPrintPlugin(Plugin): The :class:`~octoprint.server.LifecycleManager` instance. Injected by the plugin core system upon initialization of the implementation. + .. attribute:: _user_manager + + The :class:`~octoprint.users.UserManager` instance. Injected by the plugin core system upon initialization + of the implementation. + + .. attribute:: _connectivity_checker + + The :class:`~octoprint.util.ConnectivityChecker` instance. Injected by the plugin core system upon initialization + of the implementation. + .. attribute:: _data_folder Path to the data folder for the plugin to use for any data it might have to persist. Should always be accessed through :meth:`get_plugin_data_folder` since that function will also ensure that the data folder actually exists and if not creating it before returning it. Injected by the plugin core system upon initialization of the implementation. - - .. automethod:: get_plugin_data_folder """ + # noinspection PyMissingConstructor + def __init__(self): + self._plugin_manager = None + self._printer_profile_manager = None + self._event_bus = None + self._analysis_queue = None + self._slicing_manager = None + self._file_manager = None + self._printer = None + self._app_session_manager = None + self._plugin_lifecycle_manager = None + self._user_manager = None + self._connectivity_checker = None + self._data_folder = None + def get_plugin_data_folder(self): """ Retrieves the path to a data folder specifically for the plugin, ensuring it exists and if not creating it @@ -107,10 +133,10 @@ class ReloadNeedingPlugin(Plugin): class EnvironmentDetectionPlugin(OctoPrintPlugin, RestartNeedingPlugin): - + def get_additional_environment(self): pass - + def on_environment_detected(self, environment, *args, **kwargs): pass @@ -602,6 +628,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): See below for details on this. """ + # noinspection PyMethodMayBeStatic,PyUnusedLocal def will_handle_ui(self, request): """ Called by OctoPrint to determine if the mixin implementation will be @@ -624,6 +651,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): """ return False + # noinspection PyMethodMayBeStatic,PyUnusedLocal def on_ui_render(self, now, request, render_kwargs): """ Called by OctoPrint to retrieve the response to send to the client @@ -712,6 +740,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): return None + # noinspection PyMethodMayBeStatic def get_ui_additional_key_data_for_cache(self): """ Allows to return additional data to use in the cache key. @@ -723,6 +752,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): """ return None + # noinspection PyMethodMayBeStatic def get_ui_additional_tracked_files(self): """ Allows to return additional files to track for validating existing caches. By default OctoPrint @@ -735,6 +765,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): """ return None + # noinspection PyMethodMayBeStatic def get_ui_custom_tracked_files(self): """ Allows to define a complete separate set of files to track for (in)validating the cache. If this @@ -747,6 +778,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): """ return None + # noinspection PyMethodMayBeStatic def get_ui_custom_etag(self): """ Allows to use a custom way to calculate the ETag, instead of the default method (hashing @@ -757,6 +789,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): """ return None + # noinspection PyMethodMayBeStatic def get_ui_additional_etag(self, default_additional): """ Allows to provide a list of additional fields to use for ETag generation. @@ -772,6 +805,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): """ return default_additional + # noinspection PyMethodMayBeStatic def get_ui_custom_lastmodified(self): """ Allows to calculate the LastModified differently than using the most recent modification @@ -782,6 +816,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): """ return None + # noinspection PyMethodMayBeStatic def get_ui_preemptive_caching_enabled(self): """ Allows to control whether the view provided by the plugin should be preemptively @@ -794,6 +829,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): """ return True + # noinspection PyMethodMayBeStatic def get_ui_data_for_preemptive_caching(self): """ Allows defining additional data to be persisted in the preemptive cache configuration, on @@ -804,6 +840,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): """ return None + # noinspection PyMethodMayBeStatic def get_ui_additional_request_data_for_preemptive_caching(self): """ Allows defining additional request data to persist in the preemptive cache configuration and @@ -819,6 +856,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): """ return None + # noinspection PyMethodMayBeStatic def get_ui_preemptive_caching_additional_unless(self): """ Allows defining additional reasons for temporarily not adding a preemptive cache record for @@ -832,6 +870,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): """ return False + # noinspection PyMethodMayBeStatic def get_ui_custom_template_filter(self, default_template_filter): """ Allows to specify a custom template filter to use for filtering the template contained in the @@ -916,6 +955,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin): ``WizardPlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`. """ + # noinspection PyMethodMayBeStatic def is_wizard_required(self): """ Allows the plugin to report whether it needs to display a wizard to the @@ -931,6 +971,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin): """ return False + # noinspection PyMethodMayBeStatic def get_wizard_version(self): """ The version of this plugin's wizard. OctoPrint will only display a wizard @@ -950,6 +991,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin): """ return None + # noinspection PyMethodMayBeStatic def get_wizard_details(self): """ Called by OctoPrint when the wizard wrapper dialog is shown. Allows the plugin to return data @@ -964,6 +1006,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin): """ return dict() + # noinspection PyMethodMayBeStatic,PyUnusedLocal def on_wizard_finish(self, handled): """ Called by OctoPrint whenever the user finishes a wizard session. @@ -982,6 +1025,7 @@ class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin): """ pass + # noinspection PyProtectedMember @classmethod def is_wizard_ignored(cls, seen_wizards, implementation): """ @@ -1132,6 +1176,7 @@ class SimpleApiPlugin(OctoPrintPlugin): } """ + # noinspection PyMethodMayBeStatic def get_api_commands(self): """ Return a dictionary here with the keys representing the accepted commands and the values being lists of @@ -1139,12 +1184,14 @@ class SimpleApiPlugin(OctoPrintPlugin): """ return None + # noinspection PyMethodMayBeStatic def is_api_adminonly(self): """ Return True if the API is only available to users having the admin role. """ return False + # noinspection PyMethodMayBeStatic def on_api_command(self, command, data): """ Called by OctoPrint upon a POST request to ``/api/plugin/``. ``command`` will contain one of @@ -1164,6 +1211,7 @@ class SimpleApiPlugin(OctoPrintPlugin): """ return None + # noinspection PyMethodMayBeStatic def on_api_get(self, request): """ Called by OctoPrint upon a GET request to ``/api/plugin/``. ``request`` will contain the @@ -1262,6 +1310,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): return f return decorator + # noinspection PyProtectedMember def get_blueprint(self): """ Creates and returns the blueprint for your plugin. Override this if you want to define and handle your blueprint yourself. @@ -1327,6 +1376,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): template_folder=template_folder ) + # noinspection PyMethodMayBeStatic def is_blueprint_protected(self): """ Whether a valid API key is needed to access the blueprint (the default) or not. Note that this only restricts @@ -1395,16 +1445,19 @@ class SettingsPlugin(OctoPrintPlugin): should have access to via :meth:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths`. OctoPrint will return its settings on the REST API even to anonymous clients, but will filter out fields it know are restricted, therefore you **must** make sure that you specify sensitive information accordingly to limit access as required! - - .. attribute:: _settings - - The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by - the plugin core system upon initialization of the implementation. """ config_version_key = "_config_version" """Key of the field in the settings that holds the configuration format version.""" + # noinspection PyMissingConstructor + def __init__(self): + self._settings = None + """ + The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by + the plugin core system upon initialization of the implementation. + """ + def on_settings_load(self): """ Loads the settings for the plugin, called by the Settings API view in order to retrieve all settings from @@ -1439,6 +1492,7 @@ class SettingsPlugin(OctoPrintPlugin): restricted_paths = self.get_settings_restricted_paths() + # noinspection PyShadowingNames def restrict_path_unless(data, path, condition): if not path: return @@ -1537,6 +1591,7 @@ class SettingsPlugin(OctoPrintPlugin): return diff + # noinspection PyMethodMayBeStatic def get_settings_defaults(self): """ Retrieves the plugin's default settings with which the plugin's settings manager will be initialized. @@ -1546,6 +1601,7 @@ class SettingsPlugin(OctoPrintPlugin): """ return dict() + # noinspection PyMethodMayBeStatic def get_settings_restricted_paths(self): """ Retrieves the list of paths in the plugin's settings which be restricted on the REST API. @@ -1600,6 +1656,7 @@ class SettingsPlugin(OctoPrintPlugin): """ return dict() + # noinspection PyMethodMayBeStatic def get_settings_preprocessors(self): """ Retrieves the plugin's preprocessors to use for preprocessing returned or set values prior to returning/setting @@ -1637,6 +1694,7 @@ class SettingsPlugin(OctoPrintPlugin): """ return dict(), dict() + # noinspection PyMethodMayBeStatic def get_settings_version(self): """ Retrieves the settings format version of the plugin. @@ -1651,6 +1709,7 @@ class SettingsPlugin(OctoPrintPlugin): """ return None + # noinspection PyMethodMayBeStatic def on_settings_migrate(self, target, current): """ Called by OctoPrint if it detects that the installed version of the plugin necessitates a higher settings version @@ -1737,6 +1796,7 @@ class EventHandlerPlugin(OctoPrintPlugin): videos rendering etc. """ + # noinspection PyMethodMayBeStatic def on_event(self, event, payload): """ Called by OctoPrint upon processing of a fired event on the platform. @@ -1755,6 +1815,7 @@ class SlicerPlugin(OctoPrintPlugin): """ + # noinspection PyMethodMayBeStatic def is_slicer_configured(self): """ Unless the return value of this method is ``True``, OctoPrint will not register the slicer within the slicing @@ -1764,6 +1825,7 @@ class SlicerPlugin(OctoPrintPlugin): """ return False + # noinspection PyMethodMayBeStatic def get_slicer_properties(self): """ Plugins should override this method to return a ``dict`` containing a bunch of meta data about the implemented slicer. @@ -1801,6 +1863,7 @@ class SlicerPlugin(OctoPrintPlugin): destination_extensions=["gco", "gcode", "g"] ) + # noinspection PyMethodMayBeStatic def get_slicer_default_profile(self): """ Should return a :class:`~octoprint.slicing.SlicingProfile` containing the default slicing profile to use with @@ -1812,6 +1875,7 @@ class SlicerPlugin(OctoPrintPlugin): """ return None + # noinspection PyMethodMayBeStatic def get_slicer_profile(self, path): """ Should return a :class:`~octoprint.slicing.SlicingProfile` parsed from the slicing profile stored at the @@ -1825,6 +1889,7 @@ class SlicerPlugin(OctoPrintPlugin): """ return None + # noinspection PyMethodMayBeStatic def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None): """ Should save the provided :class:`~octoprint.slicing.SlicingProfile` to the indicated ``path``, after applying @@ -1841,6 +1906,7 @@ class SlicerPlugin(OctoPrintPlugin): """ pass + # noinspection PyMethodMayBeStatic def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None): """ Called by OctoPrint to slice ``model_path`` for the indicated ``printer_profile``. If the ``machinecode_path`` is ``None``, @@ -1897,6 +1963,7 @@ class SlicerPlugin(OctoPrintPlugin): """ pass + # noinspection PyMethodMayBeStatic def cancel_slicing(self, machinecode_path): """ Cancels the slicing to the indicated file. @@ -1913,16 +1980,18 @@ class ProgressPlugin(OctoPrintPlugin): limited to minimally 1% steps. """ + # noinspection PyMethodMayBeStatic def on_print_progress(self, storage, path, progress): """ Called by OctoPrint on minimally 1% increments during a running print job. - :param string location: Location of the file + :param string storage: Location of the file :param string path: Path of the file :param int progress: Current progress as a value between 0 and 100 """ pass + # noinspection PyMethodMayBeStatic def on_slicing_progress(self, slicer, source_location, source_path, destination_location, destination_path, progress): """ Called by OctoPrint on minimally 1% increments during a running slicing job. @@ -1948,6 +2017,7 @@ class AppPlugin(OctoPrintPlugin): """ + # noinspection PyMethodMayBeStatic def get_additional_apps(self): return [] diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 69e0962e6..6297e2a4a 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -34,6 +34,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.EventHandlerPlugin): + # noinspection PyMissingConstructor def __init__(self): self._cached_channel_configs = None self._cached_channel_configs_mutex = threading.RLock() @@ -75,27 +76,27 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, description="Important announcements about OctoPrint.", priority=1, type="rss", - url="http://octoprint.org/feeds/important.xml"), + url="https://octoprint.org/feeds/important.xml"), _releases=dict(name="Release Announcements", description="Announcements of new releases and release candidates of OctoPrint.", priority=2, type="rss", - url="http://octoprint.org/feeds/releases.xml"), + url="https://octoprint.org/feeds/releases.xml"), _blog=dict(name="On the OctoBlog", description="Development news, community spotlights, OctoPrint On Air episodes and more from the official OctoBlog.", priority=2, type="rss", - url="http://octoprint.org/feeds/octoblog.xml"), + url="https://octoprint.org/feeds/octoblog.xml"), _plugins=dict(name="New Plugins in the Repository", description="Announcements of new plugins released on the official Plugin Repository.", priority=2, type="rss", - url="http://plugins.octoprint.org/feed.xml"), + url="https://plugins.octoprint.org/feed.xml"), _octopi=dict(name="OctoPi News", description="News around OctoPi, the Raspberry Pi image including OctoPrint.", priority=2, type="rss", - url="http://octoprint.org/feeds/octopi.xml")), + url="https://octoprint.org/feeds/octopi.xml")), enabled_channels=[], forced_channels=["_important"], channel_order=["_important", "_releases", "_blog", "_plugins", "_octopi"], @@ -200,6 +201,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, return hash.hexdigest() + # noinspection PyShadowingNames def condition(lm, etag): return check_etag(etag) diff --git a/src/octoprint/plugins/announcements/static/js/announcements.js b/src/octoprint/plugins/announcements/static/js/announcements.js index f41d33a97..3d050ee25 100644 --- a/src/octoprint/plugins/announcements/static/js/announcements.js +++ b/src/octoprint/plugins/announcements/static/js/announcements.js @@ -257,7 +257,7 @@ $(function() { text += ""; if (rest) { - text += gettext(_.sprintf("... and %(rest)d more.", {rest: rest})); + text += "

" + gettext(_.sprintf("... and %(rest)d more.", {rest: rest})) + "

"; } text += "" + gettext("You can edit your announcement subscriptions under Settings > Announcements.") + ""; diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index 5dc692928..2b817d541 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -1,22 +1,21 @@ # coding=utf-8 from __future__ import absolute_import, division, print_function -__author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" - import octoprint.plugin - from flask_babel import gettext +from .subwizards import Subwizards class CoreWizardPlugin(octoprint.plugin.AssetPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.WizardPlugin, octoprint.plugin.SettingsPlugin, - octoprint.plugin.BlueprintPlugin): + octoprint.plugin.BlueprintPlugin, + Subwizards): #~~ TemplatePlugin API @@ -34,6 +33,9 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, result = list() for key, method in required.items(): + if not callable(method): + continue + if not method(): continue @@ -92,135 +94,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, return result def get_wizard_version(self): - return 2 - - #~~ ACL subwizard - - def _is_acl_wizard_firstrunonly(self): - return True - - def _is_acl_wizard_required(self): - 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()) - - def _get_acl_wizard_name(self): - return gettext("Access Control") - - def _get_acl_additional_wizard_template_data(self): - return dict(mandatory=self._is_acl_wizard_required()) - - @octoprint.plugin.BlueprintPlugin.route("/acl", methods=["POST"]) - def acl_wizard_api(self): - from flask import request - from octoprint.server.api import valid_boolean_trues, NO_CONTENT - - data = request.get_json() - if data is None: - data = request.values - - if "ac" in data and data["ac"] in valid_boolean_trues and \ - "user" in data.keys() and "pass1" in data.keys() and \ - "pass2" in data.keys() and data["pass1"] == data["pass2"]: - # configure access control - self._settings.global_set_boolean(["accessControl", "enabled"], True) - self._user_manager.enable() - self._user_manager.add_user(data["user"], data["pass1"], True, groups=[self._group_manager.admin_group], overwrite=True) - elif "ac" in data.keys() and not data["ac"] in valid_boolean_trues: - # disable access control - self._settings.global_set_boolean(["accessControl", "enabled"], False) - - octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser - octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader) - - self._user_manager.disable() - self._settings.save() - return NO_CONTENT - - #~~ Webcam subwizard - - def _is_webcam_wizard_firstrunonly(self): - return True - - def _is_webcam_wizard_required(self): - webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"]) - webcam_stream_url = self._settings.global_get(["webcam", "stream"]) - ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"]) - - return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path) - - def _get_webcam_wizard_details(self): - return dict(required=self._is_webcam_wizard_required()) - - def _get_webcam_wizard_name(self): - return gettext("Webcam & Timelapse") - - #~~ Server commands subwizard - - def _is_servercommands_wizard_firstrunonly(self): - return True - - def _is_servercommands_wizard_required(self): - system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"]) - system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"]) - server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"]) - - return not (system_shutdown_command and system_restart_command and server_restart_command) - - def _get_servercommands_wizard_details(self): - return dict(required=self._is_servercommands_wizard_required()) - - def _get_servercommands_wizard_name(self): - return gettext("Server Commands") - - #~~ Online check subwizard - - def _is_onlinecheck_wizard_firstrunonly(self): - return False - - def _is_onlinecheck_wizard_required(self): - return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None - - def _get_onlinecheck_wizard_details(self): - return dict(required=self._is_onlinecheck_wizard_required()) - - def _get_onlinecheck_wizard_name(self): - return gettext("Online connectivity check") - - def _get_onlinecheck_additional_wizard_template_data(self): - return dict(mandatory=self._is_onlinecheck_wizard_required()) - - #~~ Plugin blacklist subwizard - - def _is_pluginblacklist_wizard_firstrunonly(self): - return False - - def _is_pluginblacklist_wizard_required(self): - return self._settings.global_get(["server", "pluginBlacklist", "enabled"]) is None - - def _get_pluginblacklist_wizard_details(self): - return dict(required=self._is_pluginblacklist_wizard_required()) - - def _get_pluginblacklist_wizard_name(self): - return gettext("Plugin blacklist") - - def _get_pluginblacklist_additional_wizard_template_data(self): - return dict(mandatory=self._is_pluginblacklist_wizard_required()) - - #~~ Printer profile subwizard - - def _is_printerprofile_wizard_firstrunonly(self): - return True - - def _is_printerprofile_wizard_required(self): - return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1 - - def _get_printerprofile_wizard_details(self): - return dict(required=self._is_printerprofile_wizard_required()) - - def _get_printerprofile_wizard_name(self): - return gettext("Default Printer Profile") + return 3 #~~ helpers diff --git a/src/octoprint/plugins/corewizard/subwizards.py b/src/octoprint/plugins/corewizard/subwizards.py new file mode 100644 index 000000000..550b701a2 --- /dev/null +++ b/src/octoprint/plugins/corewizard/subwizards.py @@ -0,0 +1,154 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import octoprint.plugin + +import sys +import inspect +from flask_babel import gettext + + +# noinspection PyUnresolvedReferences,PyMethodMayBeStatic +class ServerCommandsSubwizard(object): + def _is_servercommands_wizard_firstrunonly(self): + return True + + def _is_servercommands_wizard_required(self): + system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"]) + system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"]) + server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"]) + + return not (system_shutdown_command and system_restart_command and server_restart_command) + + def _get_servercommands_wizard_details(self): + return dict(required=self._is_servercommands_wizard_required()) + + def _get_servercommands_wizard_name(self): + return gettext("Server Commands") + + +# noinspection PyUnresolvedReferences,PyMethodMayBeStatic +class WebcamSubwizard(object): + def _is_webcam_wizard_firstrunonly(self): + return True + + def _is_webcam_wizard_required(self): + webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"]) + webcam_stream_url = self._settings.global_get(["webcam", "stream"]) + ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"]) + + return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path) + + def _get_webcam_wizard_details(self): + return dict(required=self._is_webcam_wizard_required()) + + def _get_webcam_wizard_name(self): + return gettext("Webcam & Timelapse") + + +# noinspection PyUnresolvedReferences,PyMethodMayBeStatic +class AclSubwizard(object): + def _is_acl_wizard_firstrunonly(self): + return True + + def _is_acl_wizard_required(self): + return self._user_manager.enabled and not self._user_manager.hasBeenCustomized() + + def _get_acl_wizard_details(self): + return dict(required=self._is_acl_wizard_required()) + + def _get_acl_wizard_name(self): + return gettext("Access Control") + + def _get_acl_additional_wizard_template_data(self): + return dict(mandatory=self._is_acl_wizard_required()) + + @octoprint.plugin.BlueprintPlugin.route("/acl", methods=["POST"]) + def acl_wizard_api(self): + from flask import request, abort + from octoprint.server.api import valid_boolean_trues, NO_CONTENT + + if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.hasBeenCustomized(): + abort(404) + + data = request.get_json() + if data is None: + data = request.values + + if "ac" in data and data["ac"] in valid_boolean_trues and \ + "user" in data.keys() and "pass1" in data.keys() and \ + "pass2" in data.keys() and data["pass1"] == data["pass2"]: + # configure access control + self._settings.global_set_boolean(["accessControl", "enabled"], True) + self._user_manager.enable() + self._user_manager.addUser(data["user"], data["pass1"], True, ["user", "admin"], overwrite=True) + elif "ac" in data.keys() and not data["ac"] in valid_boolean_trues: + # disable access control + self._settings.global_set_boolean(["accessControl", "enabled"], False) + + octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser + octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader) + + self._user_manager.disable() + self._settings.save() + return NO_CONTENT + + +# noinspection PyUnresolvedReferences,PyMethodMayBeStatic +class OnlineCheckSubwizard(object): + def _is_onlinecheck_wizard_firstrunonly(self): + return False + + def _is_onlinecheck_wizard_required(self): + return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None + + def _get_onlinecheck_wizard_details(self): + return dict(required=self._is_onlinecheck_wizard_required()) + + def _get_onlinecheck_wizard_name(self): + return gettext("Online connectivity check") + + def _get_onlinecheck_additional_wizard_template_data(self): + return dict(mandatory=self._is_onlinecheck_wizard_required()) + + +# noinspection PyUnresolvedReferences,PyMethodMayBeStatic +class PluginBlacklistSubwizard(object): + def _is_pluginblacklist_wizard_firstrunonly(self): + return False + + def _is_pluginblacklist_wizard_required(self): + return self._settings.global_get(["server", "pluginBlacklist", "enabled"]) is None + + def _get_pluginblacklist_wizard_details(self): + return dict(required=self._is_pluginblacklist_wizard_required()) + + def _get_pluginblacklist_wizard_name(self): + return gettext("Plugin blacklist") + + def _get_pluginblacklist_additional_wizard_template_data(self): + return dict(mandatory=self._is_pluginblacklist_wizard_required()) + + +# noinspection PyUnresolvedReferences,PyMethodMayBeStatic +class PrinterProfileSubwizard(object): + def _is_printerprofile_wizard_firstrunonly(self): + return True + + def _is_printerprofile_wizard_required(self): + return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1 + + def _get_printerprofile_wizard_details(self): + return dict(required=self._is_printerprofile_wizard_required()) + + def _get_printerprofile_wizard_name(self): + return gettext("Default Printer Profile") + + +Subwizards = type("Subwizwards", + tuple(cls for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass) + if clsname.endswith("Subwizard")), + dict()) diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_pluginblacklist_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_pluginblacklist_wizard.jinja2 index f046ac2fb..744bcbc0d 100644 --- a/src/octoprint/plugins/corewizard/templates/corewizard_pluginblacklist_wizard.jinja2 +++ b/src/octoprint/plugins/corewizard/templates/corewizard_pluginblacklist_wizard.jinja2 @@ -6,6 +6,11 @@ normal operation, allowing you to uninstall or update them to a newer version. {% endtrans %}

+

{% trans url="https://plugins.octoprint.org/blacklist/" %} + By default, OctoPrint will use the blacklist hosted at plugins.octoprint.org/blacklist.json which you + can also take a look at in a more human readable format here. +{% endtrans %}

+

{% trans %} Please decide whether to allow fetch and use of this centralized blacklist starting with the next server start. You may also change your decision at any time through Settings > Server right from within OctoPrint. diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py index 3285316d5..79bcd31c9 100644 --- a/src/octoprint/plugins/cura/__init__.py +++ b/src/octoprint/plugins/cura/__init__.py @@ -31,6 +31,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, octoprint.plugin.StartupPlugin, octoprint.plugin.WizardPlugin): + # noinspection PyMissingConstructor def __init__(self): self._logger = logging.getLogger("octoprint.plugins.cura") self._cura_logger = logging.getLogger("octoprint.plugins.cura.engine") @@ -79,11 +80,11 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, 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("Path to CuraEngine has not been configured or does not exist (currently set to %r), " - "Cura will not be selectable for slicing" % 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 @@ -100,23 +101,23 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, try: profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path]) except Exception as e: - self._logger.exception("Error while converting the imported profile") - return flask.make_response("Something went wrong while converting imported profile: {message}".format(message=str(e)), 500) + self._logger.exception(u"Error while converting the imported profile") + return flask.make_response(u"Something went wrong while converting imported profile: {message}".format(message=str(e)), 500) else: - self._logger.warn("No profile file included for importing, aborting") - return flask.make_response("No file included", 400) + self._logger.warn(u"No profile file included for importing, aborting") + return flask.make_response(u"No file included", 400) if profile_dict is None: - self._logger.warn("Could not convert profile, aborting") - return flask.make_response("Could not convert Cura profile", 400) + self._logger.warn(u"Could not convert profile, aborting") + return flask.make_response(u"Could not convert Cura profile", 400) name, _ = os.path.splitext(filename) # default values for name, display name and description profile_name = _sanitize_name(name) profile_display_name = name - profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now())) + profile_description = u"Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now())) profile_allow_overwrite = False profile_make_default = False @@ -141,15 +142,15 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, display_name=profile_display_name, description=profile_description) except octoprint.slicing.ProfileAlreadyExists: - self._logger.warn("Profile {profile_name} already exists, aborting".format(**locals())) - return flask.make_response("A profile named {profile_name} already exists for slicer cura".format(**locals()), 409) + self._logger.warn(u"Profile {profile_name} already exists, aborting".format(**locals())) + return flask.make_response(u"A profile named {profile_name} already exists for slicer cura".format(**locals()), 409) if profile_make_default: try: self._slicing_manager.set_default_profile("cura", profile_name) except octoprint.slicing.UnknownProfile: - self._logger.warn("Profile {profile_name} could not be set as default, aborting".format(**locals())) - return flask.make_response("The profile {profile_name} for slicer cura could not be set as default".format(**locals()), 500) + self._logger.warn(u"Profile {profile_name} could not be set as default, aborting".format(**locals())) + return flask.make_response(u"The profile {profile_name} for slicer cura could not be set as default".format(**locals()), 500) result = dict( resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True), @@ -182,8 +183,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, 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("Path to CuraEngine has not been configured or does not exist (currently set to %r), " - "Cura will not be selectable for slicing" % 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: @@ -275,7 +276,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, executable = normalize_path(self._settings.get(["cura_engine"])) if not executable: - return False, "Path to CuraEngine is not configured " + return False, u"Path to CuraEngine is not configured " working_dir = os.path.dirname(executable) @@ -462,7 +463,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, try: profile_dict = yaml.safe_load(f) except: - raise IOError("Couldn't read profile from {path}".format(path=path)) + raise IOError(u"Couldn't read profile from {path}".format(path=path)) if "gcode_flavor" in profile_dict and not isinstance(profile_dict["gcode_flavor"], (list, tuple)): profile_dict["gcode_flavor"] = parse_gcode_flavor(profile_dict["gcode_flavor"]) @@ -484,7 +485,7 @@ def _sanitize_name(name): return None if "/" in name or "\\" in name: - raise ValueError("name must not contain / or \\") + raise ValueError(u"name must not contain / or \\") import string valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits) @@ -519,6 +520,7 @@ def _get_usage_from_length(filament_length, filament_diameter): return usage + __plugin_name__ = "CuraEngine (<= 15.04)" __plugin_author__ = "Gina Häußge" __plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/cura.html" diff --git a/src/octoprint/plugins/cura/profile.py b/src/octoprint/plugins/cura/profile.py index c8dd13772..7b74fcdde 100644 --- a/src/octoprint/plugins/cura/profile.py +++ b/src/octoprint/plugins/cura/profile.py @@ -8,7 +8,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import re +# noinspection PyCompatibility from builtins import range +# noinspection PyCompatibility from past.builtins import basestring class SupportLocationTypes(object): diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index 7d5b5f44c..604e6337e 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -10,9 +10,10 @@ The SSDP/UPNP implementations has been largely inspired by https://gist.github.c """ import logging -import os import flask from flask_babel import gettext + +# noinspection PyCompatibility from builtins import range import octoprint.plugin @@ -24,14 +25,6 @@ except: pybonjour = False -__plugin_name__ = "Discovery" -__plugin_author__ = "Gina Häußge" -__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/discovery.html" -__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP" -__plugin_disabling_discouraged__ = gettext("Without this plugin your OctoPrint instance will no longer be " - "discoverable on the network via Bonjour and uPnP.") -__plugin_license__ = "AGPLv3" - def __plugin_load__(): if not pybonjour: # no pybonjour available, we can't use that @@ -62,6 +55,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, ssdp_multicast_port = 1900 + # noinspection PyMissingConstructor def __init__(self): self.host = None self.port = None @@ -685,3 +679,12 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, else: import socket return u"OctoPrint instance on {}".format(socket.gethostname()) + + +__plugin_name__ = "Discovery" +__plugin_author__ = "Gina Häußge" +__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/discovery.html" +__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP" +__plugin_disabling_discouraged__ = gettext("Without this plugin your OctoPrint instance will no longer be " + "discoverable on the network via Bonjour and uPnP.") +__plugin_license__ = "AGPLv3" diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py new file mode 100644 index 000000000..06fcab632 --- /dev/null +++ b/src/octoprint/plugins/logging/__init__.py @@ -0,0 +1,203 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import octoprint.plugin +from octoprint.settings import settings + +from octoprint.server import NO_CONTENT, admin_permission +from octoprint.server.util.flask import redirect_to_tornado, restricted_access + +from flask import request, jsonify, url_for, make_response +from werkzeug.utils import secure_filename +from werkzeug.exceptions import BadRequest +import yaml + +import os + +try: + from os import scandir +except ImportError: + from scandir import scandir + +class LoggingPlugin(octoprint.plugin.AssetPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.BlueprintPlugin): + @octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"]) + @restricted_access + @admin_permission.require(403) + def get_all(self): + files = self._getLogFiles() + free, total = self._get_usage() + loggers = self._get_available_loggers() + levels = self._get_logging_levels() + return jsonify(logs=dict(files=files, free=free, total=total), + setup=dict(loggers=loggers, levels=levels)) + + @octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"]) + @restricted_access + @admin_permission.require(403) + def get_log_files(self): + files = self._getLogFiles() + free, total = self._get_usage() + return jsonify(files=files, free=free, total=total) + + @octoprint.plugin.BlueprintPlugin.route("/logs/", methods=["GET"]) + @restricted_access + @admin_permission.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"]) + @restricted_access + @admin_permission.require(403) + def delete_log(self, filename): + secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename)) + if not os.path.exists(secure): + return make_response("File not found: %s" % filename, 404) + + os.remove(secure) + + return NO_CONTENT + + @octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"]) + @restricted_access + @admin_permission.require(403) + def get_logging_setup(self): + loggers = self._get_available_loggers() + levels = self._get_logging_levels() + return jsonify(loggers=loggers, levels=levels) + + @octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"]) + @restricted_access + @admin_permission.require(403) + def get_logging_levels_api(self): + return jsonify(self._get_logging_levels()) + + @octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"]) + @restricted_access + @admin_permission.require(403) + def set_logging_levels_api(self): + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) + + try: + json_data = request.json + except BadRequest: + return make_response("Malformed JSON body in request", 400) + + if not isinstance(json_data, dict): + return make_response("Invalid log level configuration", 400) + + # TODO validate further + + self._set_logging_levels(json_data) + return self.get_logging_levels_api() + + def _get_usage(self): + import psutil + usage = psutil.disk_usage(settings().getBaseFolder("logs")) + return usage.free, usage.total + + def _getLogFiles(self): + files = [] + basedir = settings().getBaseFolder("logs") + for entry in scandir(basedir): + files.append({ + "name": entry.name, + "date": int(entry.stat().st_mtime), + "size": entry.stat().st_size, + "refs": { + "resource": url_for(".download_log", filename=entry.name, _external=True), + "download": url_for("index", _external=True) + "downloads/logs/" + entry.name + } + }) + + return files + + def _get_available_loggers(self): + return filter(lambda x: self._is_managed_logger(x), self._logger.manager.loggerDict.keys()) + + def _get_logging_file(self): + # TODO this might not be the logging config we are actually using here (command line parameter...) + return os.path.join(self._settings.getBaseFolder("base"), "logging.yaml") + + def _get_logging_config(self): + logging_file = self._get_logging_file() + + config_from_file = {} + if os.path.exists(logging_file) and os.path.isfile(logging_file): + import yaml + with open(logging_file, "r") as f: + config_from_file = yaml.safe_load(f) + return config_from_file + + def _get_logging_levels(self): + config = self._get_logging_config() + if config is None or not isinstance(config, dict): + return dict() + + return dict((key, value.get("level")) + for key, value in config.get("loggers", dict()).items() + if isinstance(value, dict) and "level" in value) + + def _set_logging_levels(self, new_levels): + import logging + + config = self._get_logging_config() + + # clear all configured logging levels + if config.has_key("loggers"): + purge = [] + for component in config["loggers"]: + if not self._is_managed_logger(component): continue + try: + del config["loggers"][component]["level"] + self._logger.manager.loggerDict[component].setLevel(logging.INFO) + except: + pass + if len(config["loggers"][component]) == 0: + purge.append(component) + else: + config["loggers"] = dict() + + # update all logging levels + for logger, level in new_levels.items(): + if not config["loggers"].has_key(logger): + config["loggers"][logger] = dict() + config["loggers"][logger]["level"] = level + + # delete empty entries + config["loggers"] = {k: v for k, v in config["loggers"].items() if len(v)} + + # save + with octoprint.util.atomic_write(self._get_logging_file(), "wb", max_permissions=0o666) as f: + yaml.safe_dump(config, f, default_flow_style=False, indent=" ", allow_unicode=True) + + # set runtime logging levels now + for logger, level in new_levels.items(): + level = logging.getLevelName(level) + + self._logger.info("Setting logger {} level to {}".format(logger, level)) + self._logger.manager.loggerDict[logger].setLevel(level) + + def _is_managed_logger(self, logger): + return logger and (logger.startswith("octoprint") or logger.startswith("tornado")) + + def get_template_configs(self): + return [ + dict(type="settings", custom_bindings=True) + ] + + def get_assets(self): + return dict(js=["js/logging.js"], + less=["less/logging.less"], + css=["css/logging.css"]) + +__plugin_name__ = "Logging" +__plugin_author__ = "Shawn Bruce, based on work by Gina Häußge and Marc Hannappel" +__plugin_description__ = "Provides access to OctoPrint's logs and logging configuration." +__plugin_implementation__ = LoggingPlugin() diff --git a/src/octoprint/plugins/logging/static/js/logging.js b/src/octoprint/plugins/logging/static/js/logging.js new file mode 100644 index 000000000..c4131debb --- /dev/null +++ b/src/octoprint/plugins/logging/static/js/logging.js @@ -0,0 +1,214 @@ +(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; + + self.loginState = parameters[0]; + self.availableLoggers = ko.observableArray(); + self.availableLoggersName = ko.observable(); + self.availableLoggersLevel = ko.observable(); + self.configuredLoggers = ko.observableArray(); + self.configuredLoggersChanged = false; + + self.availableLoggersSorted = ko.computed(function() { + return _.sortBy(self.availableLoggers()); + }); + + self.configuredLoggersSorted = ko.computed(function() { + return _.sortBy(self.configuredLoggers(), function (o) { + o.level(); + return o.component; + }); + }); + + // initialize list helper + self.listHelper = new ItemListHelper( + "logFiles", + { + "name": function(a, b) { + // sorts ascending + if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1; + if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1; + return 0; + }, + "modification": function(a, b) { + // sorts descending + if (a["date"] > b["date"]) return -1; + if (a["date"] < b["date"]) return 1; + return 0; + }, + "size": function(a, b) { + // sorts descending + if (a["size"] > b["size"]) return -1; + if (a["size"] < b["size"]) return 1; + return 0; + } + }, + { + }, + "name", + [], + [], + CONFIG_LOGFILESPERPAGE + ); + + self.requestData = function() { + OctoPrint.plugins.logging.get() + .done(self.fromResponse); + }; + + self.fromResponse = function(response) { + self.fromLogsResponse(response.logs); + self.fromSetupResponse(response.setup); + }; + + self.fromLogsResponse = function(response) { + if (!response) return; + + var files = response.files; + if (files === undefined) + return; + + self.listHelper.updateItems(files); + }; + + self.fromSetupResponse = function(response) { + if (!response) return; + + // levels + var levels = []; + var configuredLoggers = []; + _.each(response.levels, function(level, logger) { + var item = {component: logger, level: ko.observable(level)}; + item.level.subscribe(function() { + self.configuredLoggersHasChanged(); + }); + levels.push(item); + configuredLoggers.push(logger); + }); + self.configuredLoggers(levels); + + // loggers + var availableLoggers = _.without(response.loggers, configuredLoggers); + self.availableLoggers(availableLoggers); + }; + + self.configuredLoggersHasChanged = function () { + self.configuredLoggersChanged = true; + }; + + self.addLogger = function() { + var component = self.availableLoggersName(); + var level = self.availableLoggersLevel(); + + self.configuredLoggers.push({component: component, level: ko.observable(level)}); + self.availableLoggers.remove(component); + + self.configuredLoggersHasChanged(); + }; + + self.removeLogger = function(logger) { + self.configuredLoggers.remove(logger); + self.availableLoggers.push(logger.component); + + self.configuredLoggersHasChanged(); + }; + + self.removeFile = function(filename) { + OctoPrint.plugins.logging.deleteLog(filename) + .done(self.requestData); + }; + + self.onSettingsShown = function() { + self.requestData(); + }; + + self.onSettingsBeforeSave = function () { + if ( self.configuredLoggersChanged ) { + console.log("ConfiguredLoggers has changed. Saving!"); + var levels = {}; + _.each(self.configuredLoggers(), function(data) { + levels[data.component] = data.level(); + }); + OctoPrint.plugins.logging.updateLevels(levels); + } else { + console.log("ConfiguredLoggers has not changed. Not saving."); + } + }; + } + + OCTOPRINT_VIEWMODELS.push({ + construct: LoggingViewModel, + additionalNames: ["logsViewModel"], + dependencies: ["loginStateViewModel"], + elements: ["#settings_plugin_logging"] + }); +}); diff --git a/src/octoprint/plugins/logging/static/less/logging.less b/src/octoprint/plugins/logging/static/less/logging.less new file mode 100644 index 000000000..dfcb1c1f7 --- /dev/null +++ b/src/octoprint/plugins/logging/static/less/logging.less @@ -0,0 +1,34 @@ +table { + th, td { + &.settings_logs_name { + text-overflow: ellipsis; + text-align: left; + } + + &.settings_logs_size { + text-align: right; + width: 70px; + } + + &.settings_logs_date { + text-align: left; + width: 130px; + } + + &.settings_logs_action { + width: 70px; + text-align: center; + white-space: nowrap; + + a { + text-decoration: none; + color: #000; + + &.disabled { + color: #ccc; + cursor: default; + } + } + } + } +} diff --git a/src/octoprint/plugins/logging/templates/logging_settings.jinja2 b/src/octoprint/plugins/logging/templates/logging_settings.jinja2 new file mode 100644 index 000000000..7a082ec6b --- /dev/null +++ b/src/octoprint/plugins/logging/templates/logging_settings.jinja2 @@ -0,0 +1,91 @@ +

{{ _('Logs') }}

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

{{ _('Logging Levels') }}

+
+ +
+
{{ _('Name') }}
+
{{ _('Level') }}
+
+
+
+
+ +
+
+ +
+
+ +
+
+
+
+
+
+ +
+
+ +
+
+ +
+
+
+
diff --git a/src/octoprint/plugins/octopi_support/__init__.py b/src/octoprint/plugins/octopi_support/__init__.py index 7e814e663..3885b6525 100644 --- a/src/octoprint/plugins/octopi_support/__init__.py +++ b/src/octoprint/plugins/octopi_support/__init__.py @@ -91,6 +91,7 @@ class OctoPiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin, octoprint.plugin.AssetPlugin, octoprint.plugin.TemplatePlugin): + # noinspection PyMissingConstructor def __init__(self): self._version = None self._cpuinfo = None @@ -124,14 +125,7 @@ class OctoPiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin, ] def get_template_vars(self): - version = self._get_version() - cpuinfo = self._get_cpuinfo() - model = self._get_model() - - return dict(version=version, - rpi_revision=cpuinfo.get("revision", "unknown"), - rpi_serial=cpuinfo.get("serial", "unknown"), - rpi_model=model) + return dict(version=self._get_version()) #~~ Helpers diff --git a/src/octoprint/plugins/octopi_support/templates/octopi_support_about.jinja2 b/src/octoprint/plugins/octopi_support/templates/octopi_support_about.jinja2 index dcc15c26e..6dcb2d674 100644 --- a/src/octoprint/plugins/octopi_support/templates/octopi_support_about.jinja2 +++ b/src/octoprint/plugins/octopi_support/templates/octopi_support_about.jinja2 @@ -1,11 +1,11 @@

{{ _('About OctoPi') }}

-

{{ _('The ready-to-go Raspberry Pi image with OctoPrint') }}

+

The ready-to-go Raspberry Pi image with OctoPrint

Version {{ plugin_octopi_support_version }}

@@ -30,13 +30,3 @@ www.gnu.org/licenses/gpl-3.0.en.html.

-{% if plugin_octopi_support_rpi_model != "unknown" %} -

{{ _('About this Raspberry Pi') }}

- -
    -
  • Model: {{ plugin_octopi_support_rpi_model }}
  • -
  • Revision: {{ plugin_octopi_support_rpi_revision }}
  • -
  • Serial: {{ plugin_octopi_support_rpi_serial }}
  • -
-{% endif %} - diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 81faffa41..d1cf17603 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -12,15 +12,13 @@ import octoprint.plugin.core from octoprint.settings import valid_boolean_trues from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag -from octoprint.server import VERSION from octoprint.access.permissions import Permissions -from octoprint.util.pip import LocalPipCaller, UnknownPip +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 flask import jsonify, make_response from flask_babel import gettext -from collections import OrderedDict import logging import sarge @@ -28,7 +26,6 @@ import sys import requests import re import os -import pkg_resources import copy import dateutil.parser import time @@ -62,6 +59,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, RECONNECT_HOOKS = ["octoprint.comm.protocol.*",] + # noinspection PyMissingConstructor def __init__(self): self._pending_enable = set() self._pending_disable = set() @@ -134,9 +132,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def get_settings_defaults(self): return dict( - repository="http://plugins.octoprint.org/plugins.json", + repository="https://plugins.octoprint.org/plugins.json", repository_ttl=24*60, - notices="http://plugins.octoprint.org/notices.json", + notices="https://plugins.octoprint.org/notices.json", notices_ttl=6*60, pip_args=None, pip_force_user=False, diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 5be271e1a..f276a6c1b 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -197,8 +197,8 @@ $(function() { return; } - var restartSpec = _.filter(lastResponse.core, function(spec) { return spec.action === "restart" }); - self.restartCommandSpec = restartSpec !== undefined && restartSpec.length > 0 ? restartSpec[0] : undefined; + var restartSpec = _.filter(lastResponse.core, function(spec) { return spec.action == "restart" }); + self.restartCommandSpec = restartSpec != undefined && restartSpec.length > 0 ? restartSpec[0] : undefined; }); self.notifications = []; @@ -208,9 +208,9 @@ $(function() { self.noticeCountText = ko.pureComputed(function() { var count = self.noticeCount(); - if (count === 0) { + if (count == 0) { return gettext("There are no plugin notices. Great!"); - } else if (count === 1) { + } else if (count == 1) { return gettext("There is a plugin notice for one of your installed plugins."); } else { return _.sprintf(gettext("There are %(count)d plugin notices for one or more of your installed plugins."), {count: count}); @@ -225,15 +225,15 @@ $(function() { var command = self._getToggleCommand(data); var not_safemode_victim = !data.safe_mode_victim || data.safe_mode_enabled; var not_blacklisted = !data.blacklisted; - return self.enableManagement() && (command === "disable" || (not_safemode_victim && not_blacklisted)) && data.key !== 'pluginmanager'; + return self.enableManagement() && (command == "disable" || (not_safemode_victim && not_blacklisted)) && data.key != 'pluginmanager'; }; self.enableUninstall = function(data) { return self.enableManagement() - && (data.origin !== "entry_point" || self.pipAvailable()) + && (data.origin != "entry_point" || self.pipAvailable()) && data.managable && !data.bundled - && data.key !== 'pluginmanager' + && data.key != 'pluginmanager' && !data.pending_uninstall; }; @@ -300,7 +300,7 @@ $(function() { maxNumberOfFiles: 1, autoUpload: false, add: function(e, data) { - if (data.files.length === 0) { + if (data.files.length == 0) { return false; } @@ -342,7 +342,7 @@ $(function() { 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); @@ -448,7 +448,7 @@ $(function() { return; } - if (data.key === "pluginmanager") return; + if (data.key == "pluginmanager") return; var onSuccess = function() { self.requestData(); @@ -462,7 +462,7 @@ $(function() { }) }; - if (self._getToggleCommand(data) === "enable") { + if (self._getToggleCommand(data) == "enable") { if (data.safe_mode_victim && !data.safe_mode_enabled) return; OctoPrint.plugins.pluginmanager.enable(data.key) .done(onSuccess) @@ -583,7 +583,7 @@ $(function() { } if (data.bundled) return; - if (data.key === "pluginmanager") return; + if (data.key == "pluginmanager") return; self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: data.name})); @@ -634,7 +634,7 @@ $(function() { self.savePluginSettings = function() { var repository = self.config_repositoryUrl(); - if (repository !== undefined && repository.trim() === "") { + if (repository != undefined && repository.trim() == "") { repository = null; } @@ -646,7 +646,7 @@ $(function() { } var notices = self.config_noticesUrl(); - if (notices !== undefined && notices.trim() === "") { + if (notices != undefined && notices.trim() == "") { notices = null; } @@ -658,7 +658,7 @@ $(function() { } var pipArgs = self.config_pipAdditionalArgs(); - if (pipArgs !== undefined && pipArgs.trim() === "") { + if (pipArgs != undefined && pipArgs.trim() == "") { pipArgs = null; } @@ -710,7 +710,7 @@ $(function() { }; if (response.result) { - if (action === "install" && response.plugin && response.plugin.blacklisted) { + if (action == "install" && response.plugin && response.plugin.blacklisted) { notification = new PNotify({ title: titleSuccess, text: textSuccess, @@ -863,7 +863,7 @@ $(function() { }; self.toggleButtonCss = function(data) { - var icon = self._getToggleCommand(data) === "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on"; + var icon = self._getToggleCommand(data) == "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on"; var disabled = (self.enableToggle(data)) ? "" : " disabled"; return icon + disabled; @@ -871,7 +871,7 @@ $(function() { self.toggleButtonTitle = function(data) { var command = self._getToggleCommand(data); - if (command === "enable") { + if (command == "enable") { if (data.blacklisted) { return gettext("Blacklisted"); } else if (data.safe_mode_victim && !data.safe_mode_enabled) { @@ -885,7 +885,7 @@ $(function() { }; self.showPluginNotifications = function(plugin) { - if (!plugin.notifications || plugin.notifications.length === 0) return; + if (!plugin.notifications || plugin.notifications.length == 0) return; self._removeAllNoticeNotificationsForPlugin(plugin.key); _.each(plugin.notifications, function(notification) { @@ -894,7 +894,7 @@ $(function() { }; self.showPluginNotificationsLinkText = function(plugins) { - if (!plugins.notifications || plugins.notifications.length === 0) return; + if (!plugins.notifications || plugins.notifications.length == 0) return; var count = plugins.notifications.length; var importantCount = _.filter(plugins.notifications, function(notification) { return notification.important }).length; @@ -930,7 +930,7 @@ $(function() { var text = ""; if (notification.versions && notification.versions.length > 0) { - var versions = _.map(notification.versions, function(v) { return (v === version) ? "" + v + "" : v; }).join(", "); + var versions = _.map(notification.versions, function(v) { return (v == version) ? "" + v + "" : v; }).join(", "); text += "" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: versions}) + ""; } else { text += "" + gettext("Affected versions: all") + ""; @@ -1006,7 +1006,7 @@ $(function() { self._isNoticeNotificationHidden = function(key, date) { if (!self.hiddenNoticeNotifications[key]) return false; - return _.any(_.map(self.hiddenNoticeNotifications[key], function(d) { return date === d; })); + return _.any(_.map(self.hiddenNoticeNotifications[key], function(d) { return date == d; })); }; var noticeLocalStorageKey = "plugin.pluginmanager.seen_notices"; @@ -1040,7 +1040,7 @@ $(function() { if (!Modernizr.localstorage) return false; - if (localStorage[noticeLocalStorageKey] === undefined) + if (localStorage[noticeLocalStorageKey] == undefined) return false; var knownData = JSON.parse(localStorage[noticeLocalStorageKey]); @@ -1095,7 +1095,7 @@ $(function() { }; self.onDataUpdaterPluginMessage = function(plugin, data) { - if (plugin !== "pluginmanager") { + if (plugin != "pluginmanager") { return; } @@ -1109,21 +1109,21 @@ $(function() { var messageType = data.type; - if (messageType === "loglines" && self.working()) { + if (messageType == "loglines" && self.working()) { _.each(data.loglines, function(line) { self.loglines.push(self._preprocessLine(line)); }); self._scrollWorkingOutputToEnd(); - } else if (messageType === "result") { + } else if (messageType == "result") { var titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError; var action = data.action; var name = "Unknown"; - if (action === "install") { + if (action == "install") { var unknown = false; if (data.hasOwnProperty("plugin")) { - if (data.plugin === "unknown") { + if (data.plugin == "unknown") { unknown = true; } else { name = data.plugin.name; @@ -1173,13 +1173,13 @@ $(function() { if (data.hasOwnProperty("reason")) { if (data.was_reinstalled) { - if (sourceType === "path") { + if (sourceType == "path") { textError = _.sprintf(gettext("Reinstalling the plugin from file failed: %(reason)s"), {reason: data.reason}); } else { textError = _.sprintf(gettext("Reinstalling the plugin from \"%(source)s\" failed: %(reason)s"), {reason: data.reason, source: source}); } } else { - if (sourceType === "path") { + if (sourceType == "path") { textError = _.sprintf(gettext("Installing the plugin from file failed: %(reason)s"), {reason: data.reason}); } else { textError = _.sprintf(gettext("Installing the plugin from \"%(source)s\" failed: %(reason)s"), {reason: data.reason, source: source}); @@ -1187,13 +1187,13 @@ $(function() { } } else { if (data.was_reinstalled) { - if (sourceType === "path") { + if (sourceType == "path") { textError = gettext("Reinstalling the plugin from file failed, please see the log for details."); } else { textError = _.sprintf(gettext("Reinstalling the plugin from \"%(source)s\" failed, please see the log for details."), {source: source}); } } else { - if (sourceType === "path") { + if (sourceType == "path") { textError = gettext("Installing the plugin from file failed, please see the log for details."); } else { textError = _.sprintf(gettext("Installing the plugin from \"%(source)s\" failed, please see the log for details."), {source: source}); @@ -1201,7 +1201,7 @@ $(function() { } } - } else if (action === "uninstall") { + } else if (action == "uninstall") { if (data.hasOwnProperty("plugin")) { name = data.plugin.name; } @@ -1219,7 +1219,7 @@ $(function() { textError = gettext("Uninstalling the plugin failed, please see the log for details."); } - } else if (action === "enable") { + } else if (action == "enable") { if (data.hasOwnProperty("plugin")) { name = data.plugin.name; } @@ -1237,7 +1237,7 @@ $(function() { textError = gettext("Toggling the plugin failed, please see the log for details."); } - } else if (action === "disable") { + } else if (action == "disable") { if (data.hasOwnProperty("plugin")) { name = data.plugin.name; } diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 4dc8b2ae7..6541c2b58 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -133,7 +133,7 @@ {{ pluginmanager_safemode() }} {{ pluginmanager_offline() }}

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