Merge branch 'devel' into dev/permission

# Conflicts:
#	src/octoprint/plugins/corewizard/__init__.py
#	src/octoprint/plugins/pluginmanager/__init__.py
#	src/octoprint/plugins/softwareupdate/__init__.py
#	src/octoprint/printer/standard.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/api/job.py
#	src/octoprint/server/api/log.py
#	src/octoprint/server/util/__init__.py
#	src/octoprint/server/views.py
#	src/octoprint/static/css/octoprint.css
#	src/octoprint/static/js/app/main.js
#	src/octoprint/static/js/app/viewmodels/log.js
#	src/octoprint/static/js/app/viewmodels/loginstate.js
#	src/octoprint/static/js/app/viewmodels/printerstate.js
#	src/octoprint/static/js/app/viewmodels/users.js
#	src/octoprint/static/less/octoprint.less
#	src/octoprint/templates/dialogs/settings/logs.jinja2
#	src/octoprint/templates/tabs/control.jinja2
#	src/octoprint/util/__init__.py
This commit is contained in:
Gina Häußge committed 2018-02-20 15:42:43 +01:00
commit b9a5e1db69
115 files changed
+7946 -6501

No files matched your search

+1 -1
View File
@@ -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.]
+7 -7
View File
@@ -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
+1
View File
@@ -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
+123
View File
@@ -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
+1 -1
View File
@@ -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.]
+5 -5
View File
@@ -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
+2 -8
View File
@@ -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)!
and 1062 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+3
View File
@@ -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:
+5 -168
View File
@@ -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 <sec-bundledplugins-logging-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 <sec-api-logs-datamodel-retrieveresponse>`.
**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 <sec-api-logs-datamodel-fileinfo>`
- 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/<path>`` 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.
+1 -1
View File
@@ -1,4 +1,4 @@
.. _sec-bundledplugins_cura:
.. _sec-bundledplugins-cura:
Cura
====
+1
View File
@@ -9,5 +9,6 @@ Bundled Plugins
cura.rst
discovery.rst
logging.rst
pluginmanager.rst
softwareupdate.rst
+238
View File
@@ -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 <sec-bundledplugins-logging-api-datamodel-retrieveresponse>`.
**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 <sec-bundledplugins-logging-api-datamodel-fileinfo>`
- 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 <sec-bundledplugins-logging-api-datamodel-ref>`
- 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 <sec-bundledplugins-logging-api-list_logs>` for details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#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 <sec-bundledplugins-logging-api-delete_logs>` 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 <http://api.jquery.com/Types/#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 <http://api.jquery.com/Types/#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``.
+11
View File
@@ -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
+95 -59
View File
@@ -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:<temperature>
# 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:<temperature>
# 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:
+7 -3
View File
@@ -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 <sec-plugins-hook-comm-protocol-action>` hook.
+71 -1
View File
@@ -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 <http://jinja.octoprint.org/templates.html>`_
Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

+5 -33
View File
@@ -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 <sec-api-logs-list>` for details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#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 <sec-api-logs-delete>` 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 <http://api.jquery.com/Types/#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 <http://api.jquery.com/Types/#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 <sec-bundledplugins-logging-jsclientlib>` 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.
+54 -10
View File
@@ -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:<plugin identifier>``). 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 <https://github.com/OctoPrint/Plugin-Examples/blob/master/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 <https://github.com/OctoPrint/Plugin-Examples/blob/master/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:
+2 -2
View File
@@ -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",
+31 -31
View File
@@ -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,
+3 -3
View File
@@ -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.")
+54 -29
View File
@@ -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:
+3 -1
View File
@@ -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)
+6
View File
@@ -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
+85 -80
View File
@@ -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
+1 -1
View File
@@ -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)
+7
View File
@@ -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.
+80 -10
View File
@@ -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/<plugin identifier>``. ``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/<plugin identifier>``. ``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 []
@@ -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)
@@ -257,7 +257,7 @@ $(function() {
text += "</ul>";
if (rest) {
text += gettext(_.sprintf("... and %(rest)d more.", {rest: rest}));
text += "<p>" + gettext(_.sprintf("... and %(rest)d more.", {rest: rest})) + "</p>";
}
text += "<small>" + gettext("You can edit your announcement subscriptions under Settings > Announcements.") + "</small>";
+7 -133
View File
@@ -1,22 +1,21 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__author__ = "Gina Häußge <osd@foosel.net>"
__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
@@ -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())
@@ -6,6 +6,11 @@
normal operation, allowing you to uninstall or update them to a newer version.
{% endtrans %}</p>
<p>{% trans url="https://plugins.octoprint.org/blacklist/" %}
By default, OctoPrint will use the blacklist hosted at <code>plugins.octoprint.org/blacklist.json</code> which you
can also take a look at in a more human readable format <a href="{{ url }}" target="_blank">here</a>.
{% endtrans %}</p>
<p>{% 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.
+21 -19
View File
@@ -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"
+2
View File
@@ -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):
+12 -9
View File
@@ -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"
+203
View File
@@ -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/<path:filename>", 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/<path:filename>", 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()
@@ -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"]
});
});
@@ -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;
}
}
}
}
}
@@ -0,0 +1,91 @@
<h3>{{ _('Logs') }}</h3>
<div class="pull-right">
<small>
{{ _('Sort by') }}: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('modification'); }">{{ _('Modification date') }} ({{ _('descending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">{{ _('Size') }} ({{ _('descending') }})</a>
</small>
</div>
<table class="table table-striped table-hover table-condensed table-hover" id="log_files">
<thead>
<tr>
<th class="settings_logs_name">{{ _('Name') }}</th>
<th class="settings_logs_size">{{ _('Size') }}</th>
<th class="settings_logs_date">{{ _('Date') }}</th>
<th class="settings_logs_action">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: listHelper.paginatedItems">
<tr data-bind="attr: {title: name}">
<td class="settings_logs_name" data-bind="text: name"></td>
<td class="settings_logs_size" data-bind="text: formatSize(size)"></td>
<td class="settings_logs_date" data-bind="text: formatDate(date)"></td>
<td class="settings_logs_action">
<a href="#" class="icon-trash" data-bind="click: function() { if ($root.loginState.isUser()) { $parent.removeFile($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser()}"></a>&nbsp;|&nbsp;<a href="#" class="icon-download" data-bind="attr: {href: refs.download}"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: listHelper.currentPage() === 0}">
<a href="#" data-bind="click: listHelper.prevPage">«</a>
</li>
</ul>
<ul data-bind="foreach: listHelper.pages">
<li data-bind="css: { active: $data.number === $root.listHelper.currentPage(), disabled: $data.number === -1 }">
<a href="#" data-bind="text: $data.text, click: function() { $root.listHelper.changePage($data.number); }"></a>
</li>
</ul>
<ul>
<li data-bind="css: {disabled: listHelper.currentPage() === listHelper.lastPage()}">
<a href="#" data-bind="click: listHelper.nextPage">»</a>
</li>
</ul>
</div>
<h3>{{ _('Logging Levels') }}</h3>
<form class="form-horizontal">
<div class="row-fluid">
<div class="span8"><h5>{{ _('Name') }}</h5></div>
<div class="span2"><h5>{{ _('Level') }}</h5></div>
</div>
<div data-bind="foreach: configuredLoggersSorted">
<div class="row-fluid" style="margin-bottom: 5px">
<div class="span8">
<span data-bind="text: component"></span>
</div>
<div class="span3">
<select data-bind="value: level, event: { change: $parent.configuredLoggersHasChanged }" class="input-medium">
<option value="DEBUG">DEBUG</option>
<option value="INFO">INFO</option>
<option value="WARNING">WARNING</option>
<option value="ERROR">ERROR</option>
<option value="CRITICAL">CRITICAL</option>
</select>
</div>
<div class="span1">
<a title="{{ _('Remove') }}" class="btn btn-danger" data-bind="click: $parent.removeLogger"><i class="icon-trash"></i></a>
</div>
</div>
</div>
<div>
<div class="row-fluid" style="margin-bottom: 5px">
<div class="span8">
<select class="input-block-level" data-bind="options: availableLoggersSorted, value: availableLoggersName"></select>
</div>
<div class="span3">
<select class="input-medium" data-bind="value: availableLoggersLevel">
<option value="DEBUG">DEBUG</option>
<option value="INFO">INFO</option>
<option value="WARNING">WARNING</option>
<option value="ERROR">ERROR</option>
<option value="CRITICAL">CRITICAL</option>
</select>
</div>
<div class="span1">
<a title="{{ _('Add') }}" class="btn btn-primary" data-bind="click: $root.addLogger"><i class="icon-plus"></i></a>
</div>
</div>
</div>
</form>
@@ -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
@@ -1,11 +1,11 @@
<h3>{{ _('About OctoPi') }}</h3>
<h4>{{ _('The ready-to-go Raspberry Pi image with OctoPrint') }}</h4>
<h4>The ready-to-go Raspberry Pi image with OctoPrint</h4>
<p>Version <span class="plugin_octopi_support_version">{{ plugin_octopi_support_version }}</span></p>
<ul>
<li>Website: <a href="http://octoprint.org/download/" target="_blank" rel="noreferrer noopener">octoprint.org/download</a> &amp; <a href="https://octopi.octoprint.org" target="_blank" rel="noreferrer noopener">octopi.octoprint.org</a></li>
<li>Website: <a href="https://octoprint.org/download/" target="_blank" rel="noreferrer noopener">octoprint.org/download</a> &amp; <a href="https://octopi.octoprint.org" target="_blank" rel="noreferrer noopener">octopi.octoprint.org</a></li>
<li>Source Code: <a href="https://github.com/guysoft/OctoPi" target="_blank" rel="noreferrer noopener">github.com/guysoft/OctoPi</a></li>
</ul>
@@ -30,13 +30,3 @@
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html" target="_blank" rel="noreferrer noopener">www.gnu.org/licenses/gpl-3.0.en.html</a>.
</p>
{% if plugin_octopi_support_rpi_model != "unknown" %}
<h3>{{ _('About this Raspberry Pi') }}</h3>
<ul>
<li>Model: {{ plugin_octopi_support_rpi_model }}</li>
<li>Revision: {{ plugin_octopi_support_rpi_revision }}</li>
<li>Serial: {{ plugin_octopi_support_rpi_serial }}</li>
</ul>
{% endif %}
@@ -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,
@@ -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) ? "<strong>" + v + "</strong>" : v; }).join(", ");
var versions = _.map(notification.versions, function(v) { return (v == version) ? "<strong>" + v + "</strong>" : v; }).join(", ");
text += "<small>" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: versions}) + "</small>";
} else {
text += "<small>" + gettext("Affected versions: all") + "</small>";
@@ -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;
}
@@ -133,7 +133,7 @@
{{ pluginmanager_safemode() }}
{{ pluginmanager_offline() }}
<h4 style="position: relative">
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='https://plugins.octoprint.org') }}
<div class="dropdown pull-right">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<span class="fa fa-wrench"></span>
@@ -15,8 +15,8 @@ import time
import logging
import logging.handlers
import hashlib
import traceback
# noinspection PyCompatibility
from concurrent import futures
from . import version_checks, updaters, exceptions, util, cli
@@ -43,6 +43,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
DATA_FORMAT_VERSION = "v2"
# noinspection PyMissingConstructor
def __init__(self):
self._update_in_progress = False
self._configured_checks_mutex = threading.Lock()
@@ -319,30 +320,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if "notify_users" in data:
self._settings.set_boolean(["notify_users"], data["notify_users"])
checks = self._get_configured_checks()
if "octoprint" in checks:
check = checks["octoprint"]
update_type = check.get("type", None)
update_method = self._get_update_method("octoprint", check)
checkout_folder = check.get("checkout_folder", None)
update_folder = check.get("update_folder", None)
prerelease = check.get("prerelease", False)
prerelease_channel = check.get("prerelease_channel", None)
else:
update_type = update_method = checkout_folder = update_folder = prerelease_channel = None
prerelease = False
defaults = dict(
plugins=dict(softwareupdate=dict(
checks=dict(
octoprint=dict(
type=update_type,
method=update_method,
checkout_folder=checkout_folder,
update_folder=update_folder,
prerelease=prerelease,
prerelease_channel=prerelease_channel
)
octoprint=self.get_settings_defaults()["checks"]["octoprint"]
)
))
)
@@ -351,7 +332,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if "octoprint_checkout_folder" in data:
self._settings.set(["checks", "octoprint", "checkout_folder"], data["octoprint_checkout_folder"], defaults=defaults, force=True)
if update_folder and data["octoprint_checkout_folder"]:
if self._settings.get(["checks", "octoprint", "update_folder"]) and data["octoprint_checkout_folder"]:
self._settings.set(["checks", "octoprint", "update_folder"], None, defaults=defaults, force=True)
updated_octoprint_check_config = True
@@ -359,13 +340,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
octoprint_type = data["octoprint_type"]
if octoprint_type == "github_release":
self._settings.set(["checks", "octoprint", "type"], octoprint_type, defaults=defaults, force=True)
self._settings.set(["checks", "octoprint", "method"], "pip", defaults=defaults, force=True)
self._settings.set(["checks", "octoprint", "type"], octoprint_type, defaults=defaults)
self._settings.set(["checks", "octoprint", "method"], "pip", defaults=defaults)
updated_octoprint_check_config = True
elif octoprint_type == "git_commit":
self._settings.set(["checks", "octoprint", "type"], octoprint_type, defaults=defaults, force=True)
self._settings.set(["checks", "octoprint", "method"], "update_script", defaults=defaults, force=True)
self._settings.set(["checks", "octoprint", "type"], octoprint_type, defaults=defaults)
self._settings.set(["checks", "octoprint", "method"], "update_script", defaults=defaults)
updated_octoprint_check_config = True
if "octoprint_release_channel" in data:
@@ -1009,6 +990,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if target == "octoprint":
from flask_babel import gettext
from octoprint.util.version import is_released_octoprint_version, is_stable_octoprint_version
result["displayName"] = to_unicode(check.get("displayName"), errors="replace")
if result["displayName"] is None:
# displayName missing or set to None
@@ -1026,16 +1009,16 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
stable_branch = check["stable_branch"]["branch"]
if "prerelease_branches" in check:
release_branches += [x["branch"] for x in check["prerelease_branches"]]
result["released_version"] = not release_branches or BRANCH in release_branches
result["released_version"] = is_released_octoprint_version()
if check["type"] in self.COMMIT_TRACKING_TYPES:
result["current"] = REVISION if REVISION else "unknown"
else:
result["current"] = VERSION
if check["type"] == "github_release" and (check.get("prerelease", None) or BRANCH != stable_branch):
# we are tracking github releases and are either also tracking prerelease OR are currently installed
# from something that is not the stable (master) branch => we need to change some parameters
if check["type"] == "github_release" and (check.get("prerelease", None) or not is_stable_octoprint_version()):
# we are tracking github releases and are either also tracking prerelease OR are currently running
# a non stable version => we need to change some parameters
# we compare versions fully, not just the base so that we see a difference
# between RCs + stable for the same version release
@@ -1055,18 +1038,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
result["update_branch"] = check.get("update_branch", stable_branch)
if check.get("update_script", None):
# we force an exact version
# we force an exact version & python unequality check, to be able to downgrade
result["force_exact_version"] = True
if BRANCH != result.get("prerelease_channel"):
# we force python unequality check here because that will also allow us to
# downgrade on a prerelease channel change (rc/devel => rc/maintenance)
#
# we detect channel changes by comparing the current branch with the target
# branch of the release channel - unequality means we might have to handle
# a downgrade
result["release_compare"] = "python_unequal"
result["release_compare"] = "python_unequal"
elif check.get("pip", None):
# we force python unequality check for pip installs, to be able to downgrade
result["release_compare"] = "python_unequal"
@@ -14,7 +14,7 @@
};
OctoPrintSoftwareUpdateClient.prototype.checkEntries = function(entries, force, opts) {
if (arguments.length === 1 && _.isObject(arguments[0])) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
var params = arguments[0];
entries = params.entries;
force = params.force;
@@ -22,7 +22,7 @@
}
entries = entries || [];
if (typeof entries === "string") {
if (typeof entries == "string") {
entries = [entries];
}
@@ -37,7 +37,7 @@
};
OctoPrintSoftwareUpdateClient.prototype.check = function(force, opts) {
if (arguments.length === 1 && _.isObject(arguments[0])) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
var params = arguments[0];
force = params.force;
opts = params.opts;
@@ -47,7 +47,7 @@
};
OctoPrintSoftwareUpdateClient.prototype.update = function(entries, force, opts) {
if (arguments.length === 1 && _.isObject(arguments[0])) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
var params = arguments[0];
entries = params.entries;
force = params.force;
@@ -55,7 +55,7 @@
}
entries = entries || [];
if (typeof entries === "string") {
if (typeof entries == "string") {
entries = [entries];
}
@@ -67,7 +67,7 @@
};
OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) {
if (arguments.length === 1 && _.isObject(arguments[0])) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
var params = arguments[0];
force = params.force;
opts = params.opts;
@@ -521,7 +521,7 @@ $(function() {
self.updateInProgress = false;
self._showPopup({
title: gettext("Update not started!"),
text: gettext("The update could not be started. Is it already active? Please consult the log for details."),
text: gettext("The update could not be started. Is it already active? Please consult octoprint.log for details."),
type: "error",
hide: false,
buttons: {
@@ -545,7 +545,7 @@ $(function() {
});
self._updateClicked = false;
} else {
self.forceUpdate = (force === true);
self.forceUpdate = (force == true);
self.confirmationDialog.modal("show");
}
@@ -713,7 +713,7 @@ $(function() {
self.waitingForRestart = true;
self.restartTimeout = setTimeout(function() {
title = gettext("Restart failed");
text = gettext("The server apparently did not restart by itself, you'll have to do it manually. Please consult the log file on what went wrong.");
text = gettext("The server apparently did not restart by itself, you'll have to do it manually. Please consult octoprint.log on what went wrong.");
self._showPopup({
title: title,
@@ -756,9 +756,9 @@ $(function() {
}
case "restart_failed": {
restartType = messageData.restart_type;
text = gettext("Restarting OctoPrint failed, please restart it manually. You might also want to consult the log file on what went wrong here.");
text = gettext("Restarting OctoPrint failed, please restart it manually. You might also want to consult octoprint.log on what went wrong here.");
if (restartType === "environment") {
text = gettext("Rebooting the server failed, please reboot it manually. You might also want to consult the log file on what went wrong here.");
text = gettext("Rebooting the server failed, please reboot it manually. You might also want to consult octoprint.log on what went wrong here.");
}
title = gettext("Restart failed");
@@ -794,7 +794,7 @@ $(function() {
}
case "error": {
title = gettext("Update failed!");
text = gettext("The update did not finish successfully. Please consult the log for details.");
text = gettext("The update did not finish successfully. Please consult octoprint.log and plugin_softwareupdate_console.log for details.");
self._showPopup({
title: title,
text: text,
@@ -16,6 +16,8 @@ logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip.console")
_ALREADY_INSTALLED = "Requirement already satisfied (use --upgrade to upgrade)"
_POTENTIAL_EGG_PROBLEM_POSIX = "No such file or directory"
_POTENTIAL_EGG_PROBLEM_WINDOWS = "The system cannot find the file specified"
_pip_callers = dict()
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
@@ -42,6 +44,10 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
if "pip_command" in check:
pip_command = check["pip_command"]
pip_working_directory = None
if "pip_cwd" in check:
pip_working_directory = check["pip_cwd"]
if not online and not check.get("offline", False):
raise exceptions.CannotUpdateOffline()
@@ -58,6 +64,9 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
def _log_stderr(*lines):
_log(lines, prefix="!", stream="stderr")
def _log_message(*lines):
_log(lines, prefix="#", stream="message")
def _log(lines, prefix=None, stream=None):
if log_cb is None:
return
@@ -72,23 +81,43 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
logger.debug(u"Target: %s, executing pip install %s" % (target, install_arg))
pip_args = ["install", install_arg]
pip_kwargs = dict()
if pip_working_directory is not None:
pip_kwargs.update(cwd=pip_working_directory)
if "dependency_links" in check and check["dependency_links"]:
pip_args += ["--process-dependency-links"]
returncode, stdout, stderr = pip_caller.execute(*pip_args)
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
if returncode != 0:
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
# This could be caused by an issue with pip/setuptools: If something (target or dependency of target) was
# installed as an egg at an earlier date (e.g. thanks to just running python setup.py install), pip install
# will throw an error after updating that something to a newer (non-egg) version since it will still have
# the egg on its sys.path and expect to read data from it. Running the exact same command a second time
# solved this during hunt for a workaround, so this is what we'll now do if it indeed looks like this
# specific problem
def is_egg_problem(line):
return (_POTENTIAL_EGG_PROBLEM_POSIX in line or _POTENTIAL_EGG_PROBLEM_WINDOWS in line) and ".egg" in line
if any(map(lambda x: is_egg_problem(x), stderr)) or any(map(lambda x: is_egg_problem(x), stdout)):
_log_message(u"This looks like an error caused by a specific issue in upgrading Python \"eggs\"",
u"via current versions of pip.",
u"Performing a second install attempt as a work around.")
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
if returncode != 0:
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
else:
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
if not force and any(map(lambda x: x.strip().startswith(_ALREADY_INSTALLED) and (install_arg in x or install_arg in x.lower()), stdout)):
logger.debug(u"Looks like we were already installed in this version. Forcing a reinstall.")
_log_message(u"Looks like we were already installed in this version. Forcing a reinstall.")
force = True
if force:
logger.debug(u"Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg))
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
returncode, stdout, stderr = pip_caller.execute(*pip_args)
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
if returncode != 0:
raise exceptions.UpdateError("Error while executing pip install --force-reinstall", (stdout, stderr))
@@ -5,7 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from . import commandline, git_commit, github_commit, github_release, bitbucket_commit, python_checker
from . import commandline, git_commit, github_commit, github_release, bitbucket_commit, python_checker, never_current, always_current
def log_github_ratelimit(logger, r):
ratelimit = r.headers["X-RateLimit-Limit"] if "X-RateLimit-Limit" in r.headers else "?"
@@ -0,0 +1,13 @@
# 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"
def get_latest(target, check, online=True):
current_version = check.get("current_version", "1.0.0")
information = dict(local=dict(name=current_version, value=current_version),
remote=dict(name=current_version, value=current_version))
return information, True
@@ -0,0 +1,14 @@
# 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"
def get_latest(target, check, online=True):
local_version = check.get("local_version", "1.0.0")
remote_version = check.get("remote_version", "1.0.1")
information = dict(local=dict(name=local_version, value=local_version),
remote=dict(name=remote_version, value=remote_version))
return information, False
@@ -66,6 +66,8 @@ class VirtualPrinter(object):
self._prepared_errors = []
self._errors = settings().get(["devel", "virtualPrinter", "errors"], merged=True)
self.currentExtruder = 0
self.extruderCount = settings().getInt(["devel", "virtualPrinter", "numExtruders"])
self.pinnedExtruders = settings().get(["devel", "virtualPrinter", "pinnedExtruders"])
@@ -86,7 +88,7 @@ class VirtualPrinter(object):
self._lastX = 0.0
self._lastY = 0.0
self._lastZ = 0.0
self._lastE = 0.0
self._lastE = [0.0] * self.extruderCount
self._lastF = 200
self._unitModifier = 1
@@ -112,6 +114,7 @@ class VirtualPrinter(object):
self._sendWait = settings().getBoolean(["devel", "virtualPrinter", "sendWait"])
self._sendBusy = settings().getBoolean(["devel", "virtualPrinter", "sendBusy"])
self._waitInterval = settings().getFloat(["devel", "virtualPrinter", "waitInterval"])
self._busyInterval = settings().getFloat(["devel", "virtualPrinter", "busyInterval"])
self._echoOnM117 = settings().getBoolean(["devel", "virtualPrinter", "echoOnM117"])
@@ -146,8 +149,8 @@ class VirtualPrinter(object):
self._triggerResendAt100 = True
self._triggerResendWithTimeoutAt105 = True
self._triggeredResendWithTimeoutAt105 = False
self._triggerResendWithMissingLinenoAt110 = True
self._triggerResendWithChecksumMismatchAt115 = True
readThread = threading.Thread(target=self._processIncoming, name="octoprint.plugins.virtual_printer.wait_thread")
readThread.start()
@@ -227,7 +230,7 @@ class VirtualPrinter(object):
self.currentLine += 1
elif settings().getBoolean(["devel", "virtualPrinter", "forceChecksum"]):
self._send("Error: Missing checksum")
self._send(self._error("checksum_missing"))
continue
# track N = N + 1
@@ -261,7 +264,11 @@ class VirtualPrinter(object):
continue
elif linenumber == 110 and self._triggerResendWithMissingLinenoAt110 and not self._writingToSd:
self._triggerResendWithMissingLinenoAt110 = False
self._send("Error: No Line Number with checksum, Last Line: {}".format(self.lastN))
self._send(self._error("lineno_missing", self.lastN))
continue
elif linenumber == 115 and self._triggerResendWithChecksumMismatchAt115 and not self._writingToSd:
self._triggerResendWithChecksumMismatchAt115 = False
self._triggerResend(checksum=True)
continue
elif len(self._prepared_errors):
prepared = self._prepared_errors.pop(0)
@@ -355,7 +362,7 @@ class VirtualPrinter(object):
self._send("echo:changed F value")
return False
else:
self._send("Error: Unknown command F")
self._send(self._error("command_unknown", "F"))
return True
def _gcode_M104(self, data):
@@ -421,8 +428,25 @@ class VirtualPrinter(object):
filename = data.split(None, 1)[1].strip()
self._deleteSdFile(filename)
def _gcode_M113(self, data):
interval = int(re.search("S([0-9]+)", data).group(1))
if 0 <= interval <= 60:
self._busyInterval = interval
def _gcode_M114(self, data):
output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE, int(self._lastX*100), int(self._lastY*100), int(self._lastZ*100))
if settings().getBoolean(["devel", "virtualPrinter", "reprapfwM114"]):
output = "X:{} Y:{} Z:{} {}".format(self._lastX,
self._lastY,
self._lastZ,
" ".join(["E{}:{}".format(num, self._lastE[self.currentExtruder]) for num in range(self.extruderCount)]))
else:
output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX,
self._lastY,
self._lastZ,
self._lastE[self.currentExtruder],
int(self._lastX*100),
int(self._lastY*100),
int(self._lastZ*100))
if not self._okBeforeCommandOutput:
ok = self._ok()
if ok:
@@ -476,7 +500,7 @@ class VirtualPrinter(object):
if self._lastZ is not None:
self._lastZ *= 2.54
if self._lastE is not None:
self._lastE *= 2.54
self._lastE = [e * 2.54 if e is not None else None for e in self._lastE]
def _gcode_G21(self, data):
self._unitModifier = 1.0
@@ -487,7 +511,7 @@ class VirtualPrinter(object):
if self._lastZ is not None:
self._lastZ /= 2.54
if self._lastE is not None:
self._lastE /= 2.54
self._lastE = [e / 2.54 if e is not None else None for e in self._lastE]
def _gcode_G90(self, data):
self._relative = False
@@ -518,10 +542,10 @@ class VirtualPrinter(object):
elif matchS:
_timeout = float(matchS.group(1))
if self._sendBusy:
if self._sendBusy and self._busyInterval > 0:
until = time.time() + _timeout
while time.time() < until:
time.sleep(1.0)
time.sleep(self._busyInterval)
self._send("busy:processing")
else:
time.sleep(_timeout)
@@ -549,11 +573,11 @@ class VirtualPrinter(object):
if actual is None:
if checksum:
self._send("Error: Wrong checksum")
self._send(self._error("checksum_mismatch"))
else:
self._send("Error: Missing checksum")
self._send(self._error("checksum_missing"))
else:
self._send("Error: expected line %d got %d" % (expected, actual))
self._send(self._error("lineno_mismatch", expected, actual))
def request_resend():
self._send("Resend:%d" % expected)
@@ -636,11 +660,13 @@ class VirtualPrinter(object):
elif data == "trigger_missing_checksum":
self._prepared_errors.append(lambda cur, last, line: self._triggerResend(expected=last, checksum=False))
elif data == "trigger_missing_lineno":
self._prepared_errors.append(lambda cur, last, line: self._send("Error: No Line Number with checksum, Last Line: {}".format(last)))
self._prepared_errors.append(lambda cur, last, line: self._send(self._error("lineno_missing", last)))
elif data == "drop_connection":
self._debug_drop_connection = True
elif data == "mintemp_error":
self._send(self._error("mintemp"))
elif data == "maxtemp_error":
self._send("Error: MAXTEMP triggered!")
self._send(self._error("maxtemp"))
elif data == "go_awol":
self._send("// Going AWOL")
self._debug_awol = True
@@ -886,15 +912,16 @@ class VirtualPrinter(object):
if matchE is not None:
try:
e = float(matchE.group(1))
if self._relative or self._lastE is None:
lastE = self._lastE[self.currentExtruder]
if self._relative or lastE is None:
duration = max(duration, e * self._unitModifier / speedE * 60.0)
else:
duration = max(duration, (e - self._lastE) * self._unitModifier / speedE * 60.0)
duration = max(duration, (e - lastE) * self._unitModifier / speedE * 60.0)
if self._relative and self._lastE is not None:
self._lastE += e
if self._relative and lastE is not None:
self._lastE[self.currentExtruder] += e
else:
self._lastE = e
self._lastE[self.currentExtruder] = e
except:
pass
@@ -914,7 +941,7 @@ class VirtualPrinter(object):
matchE = re.search("E([0-9.]+)", line)
if matchX is None and matchY is None and matchZ is None and matchE is None:
self._lastX = self._lastY = self._lastZ = self._lastE = 0
self._lastX = self._lastY = self._lastZ = self._lastE[self.currentExtruder] = 0
else:
if matchX is not None:
try:
@@ -933,7 +960,7 @@ class VirtualPrinter(object):
pass
if matchE is not None:
try:
self._lastE = float(matchE.group(1))
self._lastE[self.currentExtruder] = float(matchE.group(1))
except:
pass
@@ -1014,19 +1041,26 @@ class VirtualPrinter(object):
def _waitForHeatup(self, heater, only_wait_if_higher):
delta = 1
delay = 1
last_busy = time.time()
try:
if heater.startswith("tool"):
toolNum = int(heater[len("tool"):])
while not self._killed and (self.temp[toolNum] < self.targetTemp[toolNum] - delta or (not only_wait_if_higher and self.temp[toolNum] > self.targetTemp[toolNum] + delta)):
self._simulateTemps(delta=delta)
self._output("T:%0.2f" % self.temp[toolNum])
time.sleep(delay)
test = lambda: self.temp[toolNum] < self.targetTemp[toolNum] - delta or (not only_wait_if_higher and self.temp[toolNum] > self.targetTemp[toolNum] + delta)
output = lambda: "T:%0.2f" % self.temp[toolNum]
elif heater == "bed":
while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or (not only_wait_if_higher and self.bedTemp > self.bedTargetTemp + delta)):
self._simulateTemps(delta=delta)
self._output("B:%0.2f" % self.bedTemp)
time.sleep(delay)
test = lambda: self.bedTemp < self.bedTargetTemp - delta or (not only_wait_if_higher and self.bedTemp > self.bedTargetTemp + delta)
output = lambda: "B:%0.2f" % self.bedTemp
else:
return
while not self._killed and test():
self._simulateTemps(delta=delta)
self._output(output())
if self._sendBusy and time.time() - last_busy >= self._busyInterval:
self._output("echo:busy: processing")
last_busy = time.time()
time.sleep(delay)
except AttributeError:
if self.outgoing is not None:
raise
@@ -1182,6 +1216,9 @@ class VirtualPrinter(object):
return ok.format(ok, lastN=self.lastN, buffer=self.buffered.maxsize - self.buffered.qsize())
def _error(self, error, *args, **kwargs):
return "Error: {}".format(self._errors.get(error).format(*args, **kwargs))
class CharCountingQueue(queue.Queue):
def __init__(self, maxsize, name=None):
+94 -41
View File
@@ -51,7 +51,7 @@ class PrinterInterface(object):
"""Regex for valid heater identifiers."""
@classmethod
def get_connection_options(cls):
def get_connection_options(cls, *args, **kwargs):
"""
Retrieves the available ports, baudrates, preferred port and baudrate for connecting to the printer.
@@ -75,7 +75,7 @@ class PrinterInterface(object):
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
}
def connect(self, port=None, baudrate=None, profile=None):
def connect(self, port=None, baudrate=None, profile=None, *args, **kwargs):
"""
Connects to the printer, using the specified serial ``port``, ``baudrate`` and printer ``profile``. If a
connection is already established, that connection will be closed prior to connecting anew with the provided
@@ -89,13 +89,13 @@ class PrinterInterface(object):
"""
pass
def disconnect(self):
def disconnect(self, *args, **kwargs):
"""
Disconnects from the printer. Does nothing if no connection is currently established.
"""
raise NotImplementedError()
def get_transport(self):
def get_transport(self, *args, **kwargs):
"""
Returns the communication layer's transport object, if a connection is currently established.
@@ -107,7 +107,34 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def fake_ack(self):
def job_on_hold(self, blocking=True, *args, **kwargs):
"""
Contextmanager that allows executing code while printing while making sure that no commands from the file
being printed are continued to be sent to the printer. Note that this will only work for local files,
NOT SD files.
Example:
.. code-block:: python
with printer.job_on_hold():
park_printhead()
take_snapshot()
send_printhead_back()
It should be used sparingly and only for very specific situations (such as parking the print head somewhere,
taking a snapshot from the webcam, then continuing). If you abuse this, you WILL cause print quality issues!
A lock is in place that ensures that the context can only actually be held by one thread at a time. If you
don't want to block on acquire, be sure to set ``blocking`` to ``False`` and catch the ``RuntimeException`` thrown
if the lock can't be acquired.
Args:
blocking (bool): Whether to block while attempting to acquire the lock (default) or not
"""
raise NotImplementedError()
def fake_ack(self, *args, **kwargs):
"""
Fakes an acknowledgment for the communication layer. If the communication between OctoPrint and the printer
gets stuck due to lost "ok" responses from the server due to communication issues, this can be used to get
@@ -115,17 +142,18 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def commands(self, commands):
def commands(self, commands, tags=None, *args, **kwargs):
"""
Sends the provided ``commands`` to the printer.
Arguments:
commands (str, list): The commands to send. Might be a single command provided just as a string or a list
of multiple commands to send in order.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def script(self, name, context=None):
def script(self, name, context=None, tags=None, *args, **kwargs):
"""
Sends the GCODE script ``name`` to the printer.
@@ -137,13 +165,14 @@ class PrinterInterface(object):
Arguments:
name (str): The name of the GCODE script to render.
context (dict): An optional context of additional template variables to provide to the renderer.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
Raises:
UnknownScriptException: There is no GCODE script with name ``name``
"""
raise NotImplementedError()
def jog(self, axes, relative=True, speed=None, *args, **kwargs):
def jog(self, axes, relative=True, speed=None, tags=None, *args, **kwargs):
"""
Jogs the specified printer ``axis`` by the specified ``amount`` in mm.
@@ -154,38 +183,42 @@ class PrinterInterface(object):
speed (int, bool or None): Speed at which to jog (F parameter). If set to ``False`` no speed will be set
specifically. If set to ``None`` (or left out) the minimum of all involved axes speeds from the printer
profile will be used.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def home(self, axes):
def home(self, axes, tags=None, *args, **kwargs):
"""
Homes the specified printer ``axes``.
Arguments:
axes (str, list): The axis or axes to home, each of which must converted to lower case must match one of
"x", "y", "z" and "e"
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def extrude(self, amount):
def extrude(self, amount, tags=None, *args, **kwargs):
"""
Extrude ``amount`` millimeters of material from the tool.
Arguments:
amount (int, float): The amount of material to extrude in mm
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def change_tool(self, tool):
def change_tool(self, tool, tags=None, *args, **kwargs):
"""
Switch the currently active ``tool`` (for which extrude commands will apply).
Arguments:
tool (str): The tool to switch to, matching the regex "tool[0-9]+" (e.g. "tool0", "tool1", ...)
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def set_temperature(self, heater, value):
def set_temperature(self, heater, value, tags=None, *args, **kwargs):
"""
Sets the target temperature on the specified ``heater`` to the given ``value`` in celsius.
@@ -194,10 +227,11 @@ class PrinterInterface(object):
temperature or something matching the regular expression "tool[0-9]+" (e.g. "tool0", "tool1", ...) for
the hotends of the printer
value (int, float): The temperature in celsius to set the target temperature to.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def set_temperature_offset(self, offsets=None):
def set_temperature_offset(self, offsets=None, tags=None, *args, **kwargs):
"""
Sets the temperature ``offsets`` to apply to target temperatures read from a GCODE file while printing.
@@ -205,30 +239,33 @@ class PrinterInterface(object):
offsets (dict): A dictionary specifying the offsets to apply. Keys must match the format for the ``heater``
parameter to :func:`set_temperature`, so "bed" for the offset for the bed target temperature and
"tool[0-9]+" for the offsets to the hotend target temperatures.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def feed_rate(self, factor):
def feed_rate(self, factor, tags=None, *args, **kwargs):
"""
Sets the ``factor`` for the printer's feed rate.
Arguments:
factor (int, float): The factor for the feed rate to send to the firmware. Percentage expressed as either an
int between 0 and 100 or a float between 0 and 1.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def flow_rate(self, factor):
def flow_rate(self, factor, tags=None, *args, **kwargs):
"""
Sets the ``factor`` for the printer's flow rate.
Arguments:
factor (int, float): The factor for the flow rate to send to the firmware. Percentage expressed as either an
int between 0 and 100 or a float between 0 and 1.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def can_modify_file(self, path, sd):
def can_modify_file(self, path, sd, *args, **kwargs):
"""
Determines whether the ``path`` (on the printer's SD if ``sd`` is True) may be modified (updated or deleted)
or not.
@@ -254,7 +291,7 @@ class PrinterInterface(object):
"""
return not (self.is_current_file(path, sd) and (self.is_printing() or self.is_paused()))
def is_current_file(self, path, sd):
def is_current_file(self, path, sd, *args, **kwargs):
"""
Returns whether the provided ``path`` (on the printer's SD if ``sd`` is True) is the currently selected
file for printing.
@@ -286,7 +323,7 @@ class PrinterInterface(object):
return False
def select_file(self, path, sd, printAfterSelect=False, pos=None):
def select_file(self, path, sd, printAfterSelect=False, pos=None, tags=None, *args, **kwargs):
"""
Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not.
Optionally can also directly start the print after selecting the file.
@@ -297,6 +334,7 @@ class PrinterInterface(object):
sd (boolean): Indicates whether the file is on the printer's SD card or not.
printAfterSelect (boolean): Indicates whether a print should be started
after the file is selected.
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
Raises:
InvalidFileType: if the file is not a machinecode file and hence cannot be printed
@@ -305,53 +343,68 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def unselect_file(self):
def unselect_file(self, *args, **kwargs):
"""
Unselects and currently selected file.
"""
raise NotImplementedError()
def start_print(self):
def start_print(self, tags=None, *args, **kwargs):
"""
Starts printing the currently selected file. If no file is currently selected, does nothing.
Arguments:
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def pause_print(self):
def pause_print(self, tags=None, *args, **kwargs):
"""
Pauses the current print job if it is currently running, does nothing otherwise.
Arguments:
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def resume_print(self):
def resume_print(self, tags=None, *args, **kwargs):
"""
Resumes the current print job if it is currently paused, does nothing otherwise.
Arguments:
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def toggle_pause_print(self):
def toggle_pause_print(self, tags=None, *args, **kwargs):
"""
Pauses the current print job if it is currently running or resumes it if it is currently paused.
Arguments:
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
if self.is_printing():
self.pause_print()
self.pause_print(tags=tags)
elif self.is_paused():
self.resume_print()
self.resume_print(tags=tags)
def cancel_print(self):
def cancel_print(self, tags=None, *args, **kwargs):
"""
Cancels the current print job.
Arguments:
tags (set of str): An optional set of tags to attach to the command(s) throughout their lifecycle
"""
raise NotImplementedError()
def get_state_string(self):
def get_state_string(self, *args, **kwargs):
"""
Returns:
(str) A human readable string corresponding to the current communication state.
"""
raise NotImplementedError()
def get_state_id(self):
def get_state_id(self, *args, **kwargs):
"""
Identifier of the current communication state.
@@ -376,35 +429,35 @@ class PrinterInterface(object):
(str) A unique identifier corresponding to the current communication state.
"""
def get_current_data(self):
def get_current_data(self, *args, **kwargs):
"""
Returns:
(dict) The current state data.
"""
raise NotImplementedError()
def get_current_job(self):
def get_current_job(self, *args, **kwargs):
"""
Returns:
(dict) The data of the current job.
"""
raise NotImplementedError()
def get_current_temperatures(self):
def get_current_temperatures(self, *args, **kwargs):
"""
Returns:
(dict) The current temperatures.
"""
raise NotImplementedError()
def get_temperature_history(self):
def get_temperature_history(self, *args, **kwargs):
"""
Returns:
(list) The temperature history.
"""
raise NotImplementedError()
def get_current_connection(self):
def get_current_connection(self, *args, **kwargs):
"""
Returns:
(tuple) The current connection information as a 4-tuple ``(connection_string, port, baudrate, printer_profile)``.
@@ -412,49 +465,49 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def is_closed_or_error(self):
def is_closed_or_error(self, *args, **kwargs):
"""
Returns:
(boolean) Whether the printer is currently disconnected and/or in an error state.
"""
raise NotImplementedError()
def is_operational(self):
def is_operational(self, *args, **kwargs):
"""
Returns:
(boolean) Whether the printer is currently connected and available.
"""
raise NotImplementedError()
def is_printing(self):
def is_printing(self, *args, **kwargs):
"""
Returns:
(boolean) Whether the printer is currently printing.
"""
raise NotImplementedError()
def is_paused(self):
def is_paused(self, *args, **kwargs):
"""
Returns:
(boolean) Whether the printer is currently paused.
"""
raise NotImplementedError()
def is_error(self):
def is_error(self, *args, **kwargs):
"""
Returns:
(boolean) Whether the printer is currently in an error state.
"""
raise NotImplementedError()
def is_ready(self):
def is_ready(self, *args, **kwargs):
"""
Returns:
(boolean) Whether the printer is currently operational and ready for new print jobs (not printing).
"""
raise NotImplementedError()
def register_callback(self, callback):
def register_callback(self, callback, *args, **kwargs):
"""
Registers a :class:`PrinterCallback` with the instance.
@@ -463,7 +516,7 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def unregister_callback(self, callback):
def unregister_callback(self, callback, *args, **kwargs):
"""
Unregisters a :class:`PrinterCallback` from the instance.
+82 -64
View File
@@ -126,12 +126,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
#~~ handling of PrinterCallbacks
def register_callback(self, callback):
def register_callback(self, callback, *args, **kwargs):
if not isinstance(callback, PrinterCallback):
self._logger.warn("Registering an object as printer callback which doesn't implement the PrinterCallback interface")
self._callbacks.append(callback)
def unregister_callback(self, callback):
def unregister_callback(self, callback, *args, **kwargs):
try:
self._callbacks.remove(callback)
except ValueError:
@@ -201,7 +201,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
#~~ PrinterInterface implementation
def connect(self, port=None, baudrate=None, profile=None):
def connect(self, port=None, baudrate=None, profile=None, *args, **kwargs):
"""
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
will be attempted.
@@ -220,7 +220,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._comm = comm.MachineCom(port, baudrate, callbackObject=self, printerProfileManager=self._printerProfileManager)
def disconnect(self):
def disconnect(self, *args, **kwargs):
"""
Closes the connection to the printer.
"""
@@ -230,7 +230,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
else:
eventManager().fire(Events.DISCONNECTED)
def get_transport(self):
def get_transport(self, *args, **kwargs):
if self._comm is None:
return None
@@ -238,13 +238,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return self._comm.getTransport()
getTransport = util.deprecated("getTransport has been renamed to get_transport", since="1.2.0-dev-590", includedoc="Replaced by :func:`get_transport`")
def fake_ack(self):
def job_on_hold(self, blocking=None, *args, **kwargs):
if self._comm is None:
raise RuntimeError("No connection to the printer")
return self._comm.job_on_hold(blocking=blocking)
def fake_ack(self, *args, **kwargs):
if self._comm is None:
return
self._comm.fakeOk()
def commands(self, commands):
def commands(self, commands, *args, **kwargs):
"""
Sends one or more gcode commands to the printer.
"""
@@ -255,16 +260,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
commands = [commands]
for command in commands:
self._comm.sendCommand(command)
self._comm.sendCommand(command, tags=kwargs.get("tags", set()) | {"trigger:printer.commands"})
def script(self, name, context=None, must_be_set=True):
def script(self, name, context=None, must_be_set=True, *args, **kwargs):
if self._comm is None:
return
if name is None or not name:
raise ValueError("name must be set")
result = self._comm.sendGcodeScript(name, replacements=context)
result = self._comm.sendGcodeScript(name,
replacements=context,
tags=kwargs.get("tags", set()) | {"trigger:printer.script"})
if not result and must_be_set:
raise UnknownScript(name)
@@ -303,9 +310,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
else:
commands = ["G90", command]
self.commands(commands)
self.commands(commands, tags=kwargs.get("tags", set()) | {"trigger:printer.jog"})
def home(self, axes):
def home(self, axes, *args, **kwargs):
if not isinstance(axes, (list, tuple)):
if isinstance(axes, (str, unicode)):
axes = [axes]
@@ -316,24 +323,26 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if len(axes) != len(validated_axes):
raise ValueError("axes contains invalid axes: {axes}".format(axes=axes))
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90"])
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90"],
tags=kwargs.get("tags", set) | {"trigger:printer.home"})
def extrude(self, amount):
def extrude(self, amount, *args, **kwargs):
if not isinstance(amount, (int, long, float)):
raise ValueError("amount must be a valid number: {amount}".format(amount=amount))
printer_profile = self._printerProfileManager.get_current_or_default()
extrusion_speed = printer_profile["axes"]["e"]["speed"]
self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"])
self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"],
tags=kwargs.get("tags", set()) | {"trigger:printer.extrude"})
def change_tool(self, tool):
def change_tool(self, tool, *args, **kwargs):
if not PrinterInterface.valid_tool_regex.match(tool):
raise ValueError("tool must match \"tool[0-9]+\": {tool}".format(tool=tool))
tool_num = int(tool[len("tool"):])
self.commands("T%d" % tool_num)
self.commands("T%d" % tool_num, tags=kwargs.get("tags", set()) | {"trigger:printer.change_tool"})
def set_temperature(self, heater, value):
def set_temperature(self, heater, value, *args, **kwargs):
if not PrinterInterface.valid_heater_regex.match(heater):
raise ValueError("heater must match \"tool[0-9]+\" or \"bed\": {heater}".format(heater=heater))
@@ -346,14 +355,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
shared_nozzle = printer_profile["extruder"]["sharedNozzle"]
if extruder_count > 1 and not shared_nozzle:
toolNum = int(heater[len("tool"):])
self.commands("M104 T{} S{}".format(toolNum, value))
self.commands("M104 T{} S{}".format(toolNum, value),
tags=kwargs.get("tags", set()) | {"trigger:printer.set_temperature"})
else:
self.commands("M104 S{}".format(value))
self.commands("M104 S{}".format(value),
tags=kwargs.get("tags", set()) | {"trigger:printer.set_temperature"})
elif heater == "bed":
self.commands("M140 S{}".format(value))
self.commands("M140 S{}".format(value),
tags=kwargs.get("tags", set()) | {"trigger:printer.set_temperature"})
def set_temperature_offset(self, offsets=None):
def set_temperature_offset(self, offsets=None, *args, **kwargs):
if offsets is None:
offsets = dict()
@@ -372,7 +384,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return
self._comm.setTemperatureOffset(offsets)
self._setOffsets(offsets)
self._setOffsets(self._comm.getOffsets())
def _convert_rate_value(self, factor, min=0, max=200):
if not isinstance(factor, (int, float, long)):
@@ -386,15 +398,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return factor
def feed_rate(self, factor):
def feed_rate(self, factor, *args, **kwargs):
factor = self._convert_rate_value(factor, min=50, max=200)
self.commands("M220 S%d" % factor)
self.commands("M220 S%d" % factor,
tags=kwargs.get("tags", set()) | {"trigger:printer.feed_rate"})
def flow_rate(self, factor):
def flow_rate(self, factor, *args, **kwargs):
factor = self._convert_rate_value(factor, min=75, max=125)
self.commands("M221 S%d" % factor)
self.commands("M221 S%d" % factor,
tags=kwargs.get("tags", set()) | {"trigger:printer.flow_rate"})
def select_file(self, path, sd, printAfterSelect=False, pos=None):
def select_file(self, path, sd, printAfterSelect=False, pos=None, *args, **kwargs):
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
self._logger.info("Cannot load file: printer not connected or currently busy")
return
@@ -413,11 +427,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._printAfterSelect = printAfterSelect
self._posAfterSelect = pos
self._comm.selectFile("/" + path if sd else path, sd)
self._comm.selectFile("/" + path if sd else path, sd,
tags=kwargs.get("tags", set()) | {"trigger:printer.select_file"})
self._updateProgressData()
self._setCurrentZ(None)
def unselect_file(self):
def unselect_file(self, *args, **kwargs):
if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()):
return
@@ -435,7 +450,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return self._comm.getFilePosition()
def start_print(self, pos=None):
def start_print(self, pos=None, *args, **kwargs):
"""
Starts the currently loaded print job.
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
@@ -468,9 +483,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._lastProgressReport = None
self._updateProgressData()
self._setCurrentZ(None)
self._comm.startPrint(pos=pos)
self._comm.startPrint(pos=pos,
tags=kwargs.get("tags", set()) | {"trigger:printer.start_print"})
def pause_print(self):
def pause_print(self, *args, **kwargs):
"""
Pause the current printjob.
"""
@@ -480,9 +496,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if self._comm.isPaused():
return
self._comm.setPause(True)
self._comm.setPause(True, tags=kwargs.get("tags", set()) | {"trigger:printer.pause_print"})
def resume_print(self):
def resume_print(self, *args, **kwargs):
"""
Resume the current printjob.
"""
@@ -492,9 +508,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if not self._comm.isPaused():
return
self._comm.setPause(False)
self._comm.setPause(False, tags=kwargs.get("tags", set()) | {"trigger:printer.resume_print"})
def cancel_print(self):
def cancel_print(self, *args, **kwargs):
"""
Cancel the current printjob.
"""
@@ -503,28 +519,28 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
# tell comm layer to cancel - will also trigger our cancelled handler
# for further processing
self._comm.cancelPrint()
self._comm.cancelPrint(tags=kwargs.get("tags", set()) | {"trigger:printer.cancel_print"})
def get_state_string(self, state=None):
def get_state_string(self, state=None, *args, **kwargs):
if self._comm is None:
return "Offline"
else:
return self._comm.getStateString(state=state)
def get_state_id(self, state=None):
def get_state_id(self, state=None, *args, **kwargs):
if self._comm is None:
return "OFFLINE"
else:
return self._comm.getStateId(state=state)
def get_current_data(self):
def get_current_data(self, *args, **kwargs):
return self._stateMonitor.get_current_data()
def get_current_job(self):
def get_current_job(self, *args, **kwargs):
currentData = self._stateMonitor.get_current_data()
return currentData["job"]
def get_current_temperatures(self):
def get_current_temperatures(self, *args, **kwargs):
if self._comm is not None:
offsets = self._comm.getOffsets()
else:
@@ -547,10 +563,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return result
def get_temperature_history(self):
def get_temperature_history(self, *args, **kwargs):
return self._temps
def get_current_connection(self):
def get_current_connection(self, *args, **kwargs):
if self._comm is None:
return "Closed", None, None, None
@@ -558,25 +574,25 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
printer_profile = self._printerProfileManager.get_current_or_default()
return self._comm.getStateString(), port, baudrate, printer_profile
def is_closed_or_error(self):
def is_closed_or_error(self, *args, **kwargs):
return self._comm is None or self._comm.isClosedOrError()
def is_operational(self):
def is_operational(self, *args, **kwargs):
return self._comm is not None and self._comm.isOperational()
def is_printing(self):
def is_printing(self, *args, **kwargs):
return self._comm is not None and self._comm.isPrinting()
def is_paused(self):
def is_paused(self, *args, **kwargs):
return self._comm is not None and self._comm.isPaused()
def is_error(self):
def is_error(self, *args, **kwargs):
return self._comm is not None and self._comm.isError()
def is_ready(self):
def is_ready(self, *args, **kwargs):
return self.is_operational() and not self.is_printing() and not self._comm.isStreaming()
def is_sd_ready(self):
def is_sd_ready(self, *args, **kwargs):
if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None:
return False
else:
@@ -584,12 +600,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
#~~ sd file handling
def get_sd_files(self):
def get_sd_files(self, *args, **kwargs):
if self._comm is None or not self._comm.isSdReady():
return []
return map(lambda x: (x[0][1:], x[1]), self._comm.getSdFiles())
def add_sd_file(self, filename, absolutePath, on_success=None, on_failure=None):
def add_sd_file(self, filename, absolutePath, on_success=None, on_failure=None, *args, **kwargs):
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
self._logger.error("No connection to printer or printer is busy")
return
@@ -609,26 +625,28 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
# probably something else added through a plugin, use it's basename as-is
remoteName = os.path.basename(filename)
self._timeEstimationData = TimeEstimationHelper()
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName, special=not valid_file_type(filename, "gcode"))
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName,
special=not valid_file_type(filename, "gcode"),
tags=kwargs.get("tags", set()) | {"trigger:printer.add_sd_file"})
return remoteName
def delete_sd_file(self, filename):
def delete_sd_file(self, filename, *args, **kwargs):
if not self._comm or not self._comm.isSdReady():
return
self._comm.deleteSdFile("/" + filename)
self._comm.deleteSdFile("/" + filename, tags=kwargs.get("tags", set()) | {"trigger:printer.delete_sd_file"})
def init_sd_card(self):
def init_sd_card(self, *args, **kwargs):
if not self._comm or self._comm.isSdReady():
return
self._comm.initSdCard()
self._comm.initSdCard(tags=kwargs.get("tags", set()) | {"trigger:printer.init_sd_card"})
def release_sd_card(self):
def release_sd_card(self, *args, **kwargs):
if not self._comm or not self._comm.isSdReady():
return
self._comm.releaseSdCard()
self._comm.releaseSdCard(tags=kwargs.get("tags", set()) | {"trigger:printer.release_sd_card"})
def refresh_sd_files(self, blocking=False):
def refresh_sd_files(self, blocking=False, *args, **kwargs):
"""
Refreshes the list of file stored on the SD card attached to printer (if available and printer communication
available). Optional blocking parameter allows making the method block (max 10s) until the file list has been
@@ -637,9 +655,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if not self._comm or not self._comm.isSdReady():
return
self._sdFilelistAvailable.clear()
self._comm.refreshSdFiles()
self._comm.refreshSdFiles(tags=kwargs.get("tags", set()) | {"trigger:printer.refresh_sd_files"})
if blocking:
self._sdFilelistAvailable.wait(10000)
self._sdFilelistAvailable.wait(kwargs.get("timeout", 10000))
#~~ state monitoring
+159 -47
View File
@@ -15,7 +15,7 @@ from flask_assets import Environment, Bundle
from babel import Locale
from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver
from collections import defaultdict
from collections import defaultdict, OrderedDict
from builtins import bytes, range
from past.builtins import basestring
@@ -165,6 +165,13 @@ def load_user(id):
return None
def load_user_from_request(request):
return util.get_user_for_authorization_header(request.headers.get('Authorization'))
def unauthorized_user():
from flask import abort
abort(403)
#~~ startup code
@@ -398,8 +405,37 @@ class Server(object):
"""Factory for injections for all OctoPrintPlugins"""
if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
return None
components_copy = dict(components)
if "printer" in components:
import wrapt
import functools
def tagwrap(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
tags = kwargs.get("tags", set()) | {"source:plugin",
"plugin:{}".format(name)}
kwargs["tags"] = tags
return f(*args, **kwargs)
setattr(wrapper, "__tagwrapped__", True)
return wrapper
class TaggedFuncsPrinter(wrapt.ObjectProxy):
def __getattribute__(self, attr):
__wrapped__ = super(TaggedFuncsPrinter, self).__getattribute__("__wrapped__")
item = getattr(__wrapped__, attr)
if callable(item) \
and ("tags" in item.__code__.co_varnames or "kwargs" in item.__code__.co_varnames) \
and not getattr(item, "__tagwrapped__", False):
return tagwrap(item)
else:
return item
components_copy["printer"] = TaggedFuncsPrinter(components["printer"])
props = dict()
props.update(components)
props.update(components_copy)
props.update(dict(
data_folder=os.path.join(self._settings.getBaseFolder("data"), name)
))
@@ -496,6 +532,12 @@ class Server(object):
loginManager.session_protection = "strong"
loginManager.user_callback = load_user
loginManager.unauthorized_callback = unauthorized_user
# login users authenticated by basic auth
if self._settings.get(["accessControl", "trustBasicAuthentication"]):
loginManager.request_callback = load_user_from_request
if userManager.enabled:
def anonymous_user_factory():
return users.AnonymousUser([groupManager.guest_group])
@@ -565,7 +607,7 @@ class Server(object):
server_routes = self._router.urls + [
# various downloads
# .mpg and .mp4 timelapses:
(r"/downloads/timelapse/([^/]*\.mp[g4])", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("timelapse")),
(r"/downloads/timelapse/([^/]*\.m(.*))", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("timelapse")),
timelapse_permission_validator,
download_handler_kwargs,
no_hidden_files_validator)),
@@ -589,7 +631,11 @@ class Server(object):
# online indicators - text file with "online" as content and a transparent gif
(r"/online.txt", util.tornado.StaticDataHandler, dict(data="online\n")),
(r"/online.gif", util.tornado.StaticDataHandler, dict(data=bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")),
content_type="image/gif"))
content_type="image/gif")),
# deprecated endpoints
(r"/api/logs", util.tornado.DeprecatedEndpointHandler, dict(url="/plugin/logging/logs")),
(r"/api/logs/(.*)", util.tornado.DeprecatedEndpointHandler, dict(url="/plugin/logging/logs/{0}")),
]
# fetch additional routes from plugins
@@ -676,7 +722,7 @@ class Server(object):
(port, baudrate) = self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"])
printer_profile = printerProfileManager.get_default()
connectionOptions = printer.__class__.get_connection_options()
if port in connectionOptions["ports"]:
if port in connectionOptions["ports"] or port == "AUTO":
printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")
except:
self._logger.exception("Something went wrong while attempting to automatically connect to the printer")
@@ -1167,12 +1213,14 @@ class Server(object):
self._logger.debug("Deleting {path}...".format(**locals()))
shutil.rmtree(path)
except:
self._logger.exception("Error while trying to delete {path}, leaving it alone".format(**locals()))
self._logger.exception("Error while trying to delete {path}, "
"leaving it alone".format(**locals()))
continue
# re-create path
self._logger.debug("Creating {path}...".format(**locals()))
error_text = "Error while trying to re-create {path}, that might cause errors with the webassets cache".format(**locals())
error_text = "Error while trying to re-create {path}, that might cause " \
"errors with the webassets cache".format(**locals())
try:
os.makedirs(path)
except OSError as e:
@@ -1182,13 +1230,16 @@ class Server(object):
import time
for n in range(3):
time.sleep(0.5)
self._logger.debug("Creating {path}: Retry #{retry} after {time}s".format(path=path, retry=n+1, time=(n + 1)*0.5))
self._logger.debug("Creating {path}: Retry #{retry} after {time}s".format(path=path,
retry=n+1,
time=(n + 1)*0.5))
try:
os.makedirs(path)
break
except:
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.exception("Ignored error while creating directory {path}".format(**locals()))
self._logger.exception("Ignored error while creating "
"directory {path}".format(**locals()))
pass
else:
# this will only get executed if we never did
@@ -1208,9 +1259,9 @@ class Server(object):
self._logger.info("Reset webasset folder {path}...".format(**locals()))
AdjustedEnvironment = type(Environment)(Environment.__name__, (Environment,), dict(
resolver_class=util.flask.PluginAssetResolver
))
AdjustedEnvironment = type(Environment)(Environment.__name__,
(Environment,),
dict(resolver_class=util.flask.PluginAssetResolver))
class CustomDirectoryEnvironment(AdjustedEnvironment):
@property
def directory(self):
@@ -1219,9 +1270,9 @@ class Server(object):
assets = CustomDirectoryEnvironment(app)
assets.debug = not self._settings.getBoolean(["devel", "webassets", "bundle"])
UpdaterType = type(util.flask.SettingsCheckUpdater)(util.flask.SettingsCheckUpdater.__name__, (util.flask.SettingsCheckUpdater,), dict(
updater=assets.updater
))
UpdaterType = type(util.flask.SettingsCheckUpdater)(util.flask.SettingsCheckUpdater.__name__,
(util.flask.SettingsCheckUpdater,),
dict(updater=assets.updater))
assets.updater = UpdaterType
enable_gcodeviewer = self._settings.getBoolean(["gcodeViewer", "enabled"])
@@ -1286,7 +1337,6 @@ class Server(object):
"js/app/client/files.js",
"js/app/client/job.js",
"js/app/client/languages.js",
"js/app/client/logs.js",
"js/app/client/printer.js",
"js/app/client/printerprofiles.js",
"js/app/client/settings.js",
@@ -1298,12 +1348,6 @@ class Server(object):
"js/app/client/wizard.js",
"js/app/client/access.js"
]
js_core = dynamic_core_assets["js"] + \
dynamic_plugin_assets["bundled"]["js"] + \
["js/app/dataupdater.js",
"js/app/helpers.js",
"js/app/main.js"]
js_plugins = dynamic_plugin_assets["external"]["js"]
css_libs = [
"css/bootstrap.min.css",
@@ -1317,75 +1361,143 @@ class Server(object):
"css/pnotify.buttons.min.css",
"css/pnotify.history.min.css"
]
css_core = list(dynamic_core_assets["css"]) + list(dynamic_plugin_assets["bundled"]["css"])
css_plugins = list(dynamic_plugin_assets["external"]["css"])
less_core = list(dynamic_core_assets["less"]) + list(dynamic_plugin_assets["bundled"]["less"])
less_plugins = list(dynamic_plugin_assets["external"]["less"])
# a couple of custom filters
from octoprint.server.util.webassets import LessImportRewrite, JsDelimiterBundler, JsPluginDelimiterBundler, \
SourceMapRewrite, SourceMapRemove
from octoprint.server.util.webassets import LessImportRewrite, JsDelimiterBundler, \
SourceMapRewrite, SourceMapRemove, JsPluginBundle
from webassets.filter import register_filter
register_filter(LessImportRewrite)
register_filter(SourceMapRewrite)
register_filter(SourceMapRemove)
register_filter(JsDelimiterBundler)
register_filter(JsPluginDelimiterBundler)
# JS
def all_assets_for_plugins(collection):
"""Gets all plugin assets for a dict of plugin->assets"""
result = []
for assets in collection.values():
result += assets
return result
# -- JS --------------------------------------------------------------------------------------------------------
js_filters = ["sourcemap_remove", "js_delimiter_bundler"]
js_plugin_filters = ["sourcemap_remove", "js_delimiter_bundler"] # TODO: replace with IIFE wrapper again, see #2200
js_plugin_filters = ["sourcemap_remove", "js_delimiter_bundler"]
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters=",".join(js_filters))
if self._settings.getBoolean(["feature", "legacyPluginAssets"]):
# TODO remove again in 1.3.8
def js_bundles_for_plugins(collection, filters=None):
"""Produces Bundle instances"""
result = OrderedDict()
for plugin, assets in collection.items():
if len(assets):
result[plugin] = Bundle(*assets, filters=filters)
return result
js_client_bundle = Bundle(*js_client, output="webassets/packed_client.js", filters=",".join(js_filters))
js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters=",".join(js_filters))
else:
def js_bundles_for_plugins(collection, filters=None):
"""Produces JsPluginBundle instances that output IIFE wrapped assets"""
result = OrderedDict()
for plugin, assets in collection.items():
if len(assets):
result[plugin] = JsPluginBundle(plugin, *assets, filters=filters)
return result
js_core = dynamic_core_assets["js"] + \
all_assets_for_plugins(dynamic_plugin_assets["bundled"]["js"]) + \
["js/app/dataupdater.js",
"js/app/helpers.js",
"js/app/main.js"]
js_plugins = js_bundles_for_plugins(dynamic_plugin_assets["external"]["js"],
filters="js_delimiter_bundler")
js_libs_bundle = Bundle(*js_libs,
output="webassets/packed_libs.js",
filters=",".join(js_filters))
js_client_bundle = Bundle(*js_client,
output="webassets/packed_client.js",
filters=",".join(js_filters))
js_core_bundle = Bundle(*js_core,
output="webassets/packed_core.js",
filters=",".join(js_filters))
if len(js_plugins) == 0:
js_plugins_bundle = Bundle(*[])
else:
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters=",".join(js_plugin_filters))
js_plugins_bundle = Bundle(*js_plugins.values(),
output="webassets/packed_plugins.js",
filters=",".join(js_plugin_filters))
js_app_bundle = Bundle(js_plugins_bundle, js_core_bundle, output="webassets/packed_app.js", filters=",".join(js_filters))
js_app_bundle = Bundle(js_plugins_bundle, js_core_bundle,
output="webassets/packed_app.js",
filters=",".join(js_filters))
# -- CSS -------------------------------------------------------------------------------------------------------
# CSS
css_filters = ["cssrewrite"]
css_libs_bundle = Bundle(*css_libs, output="webassets/packed_libs.css", filters=",".join(css_filters))
css_core = list(dynamic_core_assets["css"]) \
+ all_assets_for_plugins(dynamic_plugin_assets["bundled"]["css"])
css_plugins = list(all_assets_for_plugins(dynamic_plugin_assets["external"]["css"]))
css_libs_bundle = Bundle(*css_libs,
output="webassets/packed_libs.css",
filters=",".join(css_filters))
if len(css_core) == 0:
css_core_bundle = Bundle(*[])
else:
css_core_bundle = Bundle(*css_core, output="webassets/packed_core.css", filters=",".join(css_filters))
css_core_bundle = Bundle(*css_core,
output="webassets/packed_core.css",
filters=",".join(css_filters))
if len(css_plugins) == 0:
css_plugins_bundle = Bundle(*[])
else:
css_plugins_bundle = Bundle(*css_plugins, output="webassets/packed_plugins.css", filters=",".join(css_filters))
css_plugins_bundle = Bundle(*css_plugins,
output="webassets/packed_plugins.css",
filters=",".join(css_filters))
css_app_bundle = Bundle(css_core, css_plugins, output="webassets/packed_app.css", filters=",".join(css_filters))
css_app_bundle = Bundle(css_core, css_plugins,
output="webassets/packed_app.css",
filters=",".join(css_filters))
# -- LESS ------------------------------------------------------------------------------------------------------
# LESS
less_filters = ["cssrewrite", "less_importrewrite"]
less_core = list(dynamic_core_assets["less"]) \
+ all_assets_for_plugins(dynamic_plugin_assets["bundled"]["less"])
less_plugins = all_assets_for_plugins(dynamic_plugin_assets["external"]["less"])
if len(less_core) == 0:
less_core_bundle = Bundle(*[])
else:
less_core_bundle = Bundle(*less_core, output="webassets/packed_core.less", filters=",".join(less_filters))
less_core_bundle = Bundle(*less_core,
output="webassets/packed_core.less",
filters=",".join(less_filters))
if len(less_plugins) == 0:
less_plugins_bundle = Bundle(*[])
else:
less_plugins_bundle = Bundle(*less_plugins, output="webassets/packed_plugins.less", filters=",".join(less_filters))
less_plugins_bundle = Bundle(*less_plugins,
output="webassets/packed_plugins.less",
filters=",".join(less_filters))
less_app_bundle = Bundle(less_core, less_plugins, output="webassets/packed_app.less", filters=",".join(less_filters))
less_app_bundle = Bundle(less_core, less_plugins,
output="webassets/packed_app.less",
filters=",".join(less_filters))
# -- asset registration ----------------------------------------------------------------------------------------
# asset registration
assets.register("js_libs", js_libs_bundle)
assets.register("js_client", js_client_bundle)
assets.register("js_core", js_core_bundle)
for plugin, bundle in js_plugins.items():
# register our collected plugin bundles so that they are bound to the environment
assets.register("js_plugin_{}".format(plugin), bundle)
assets.register("js_plugins", js_plugins_bundle)
assets.register("js_app", js_app_bundle)
assets.register("css_libs", css_libs_bundle)
+5 -2
View File
@@ -16,7 +16,7 @@ import octoprint.server
import octoprint.plugin
from octoprint.server import NO_CONTENT
from octoprint.settings import settings as s, valid_boolean_trues
from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, corsRequestHandler, corsResponseHandler
from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, loginFromAuthorizationHeaderRequestHandler, corsRequestHandler, corsResponseHandler
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login
from octoprint.access.permissions import Permissions
@@ -33,7 +33,6 @@ from . import settings as api_settings
from . import timelapse as api_timelapse
from . import access as api_access
from . import users as api_users
from . import log as api_logs
from . import slicing as api_slicing
from . import printer_profiles as api_printer_profiles
from . import languages as api_languages
@@ -46,6 +45,7 @@ api.after_request(noCachingExceptGetResponseHandler)
api.before_request(corsRequestHandler)
api.before_request(enforceApiKeyRequestHandler)
api.before_request(loginFromAuthorizationHeaderRequestHandler)
api.before_request(loginFromApiKeyRequestHandler)
api.after_request(corsResponseHandler)
@@ -243,6 +243,9 @@ def _logout(user):
octoprint.server.userManager.logout_user(user)
#~~ Test utils
@api.route("/util/test", methods=["POST"])
@restricted_access
@Permissions.ADMIN.require(403)
+2 -2
View File
@@ -330,7 +330,7 @@ def uploadGcodeFile(target):
"""
if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "machinecode"):
return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint)
return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint, tags={"source:api", "api:files.sd"})
else:
selectAndOrPrint(filename, absFilename, destination)
return filename
@@ -758,7 +758,7 @@ def deleteGcodeFile(filename, target):
# delete it
if target == FileDestinations.SDCARD:
printer.delete_sd_file(filename)
printer.delete_sd_file(filename, tags={"source:api", "api:files.sd"})
else:
fileManager.remove_file(target, filename)
+8 -6
View File
@@ -32,25 +32,27 @@ def controlJob():
activePrintjob = printer.is_printing() or printer.is_paused()
tags = {"source:api", "api:job"}
with Permissions.PRINT.require(403):
if command == "start":
if activePrintjob:
return make_response("Printer already has an active print job, did you mean 'restart'?", 409)
printer.start_print()
printer.start_print(tags=tags)
elif command == "restart":
if not printer.is_paused():
return make_response("Printer does not have an active print job or is not paused", 409)
printer.start_print()
printer.start_print(tags=tags)
elif command == "pause":
if not activePrintjob:
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
action = data.get("action", "toggle")
if action == "toggle":
printer.toggle_pause_print()
printer.toggle_pause_print(tags=tags)
elif action == "pause":
printer.pause_print()
printer.pause_print(tags=tags)
elif action == "resume":
printer.resume_print()
printer.resume_print(tags=tags)
else:
return make_response("Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format(action), 400)
@@ -59,7 +61,7 @@ def controlJob():
if command == "cancel":
if not activePrintjob:
return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409)
printer.cancel_print()
printer.cancel_print(tags=tags)
return NO_CONTENT
-74
View File
@@ -1,74 +0,0 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__author__ = "Marc Hannappel Salandora"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
try:
from os import scandir
except ImportError:
from scandir import scandir
from flask import request, jsonify, url_for, make_response
from werkzeug.utils import secure_filename
from octoprint.settings import settings
from octoprint.server import NO_CONTENT
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
from octoprint.server.api import api
from octoprint.access.permissions import Permissions
@api.route("/logs", methods=["GET"])
@restricted_access
@Permissions.LOGS.require(403)
def getLogFiles():
import psutil
usage = psutil.disk_usage(settings().getBaseFolder("logs"))
files = _getLogFiles()
return jsonify(files=files, free=usage.free, total=usage.total)
@api.route("/logs/<path:filename>", methods=["GET"])
@restricted_access
@Permissions.LOGS.require(403)
def downloadLog(filename):
return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename)
@api.route("/logs/<path:filename>", methods=["DELETE"])
@restricted_access
@Permissions.LOGS.require(403)
def deleteLog(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
def _getLogFiles():
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(".downloadLog", filename=entry.name, _external=True),
"download": url_for("index", _external=True) + "downloads/logs/" + entry.name
}
})
return files
+23 -13
View File
@@ -79,6 +79,8 @@ def printerToolCommand():
validation_regex = re.compile("tool\d+")
tags = {"source:api", "api:printer.tool"}
##~~ tool selection
if command == "select":
tool = data["tool"]
@@ -87,7 +89,7 @@ def printerToolCommand():
if not tool.startswith("tool"):
return make_response("Invalid tool for selection: %s" % tool, 400)
printer.change_tool(tool)
printer.change_tool(tool, tags=tags)
##~~ temperature
elif command == "target":
@@ -104,7 +106,7 @@ def printerToolCommand():
# perform the actual temperature commands
for tool in validated_values.keys():
printer.set_temperature(tool, validated_values[tool])
printer.set_temperature(tool, validated_values[tool], tags=tags)
##~~ temperature offset
elif command == "offset":
@@ -133,14 +135,14 @@ def printerToolCommand():
amount = data["amount"]
if not isinstance(amount, (int, long, float)):
return make_response("Not a number for extrusion amount: %r" % amount, 400)
printer.extrude(amount)
printer.extrude(amount, tags=tags)
elif command == "flowrate":
factor = data["factor"]
if not isinstance(factor, (int, long, float)):
return make_response("Not a number for flow rate: %r" % factor, 400)
try:
printer.flow_rate(factor)
printer.flow_rate(factor, tags=tags)
except ValueError as e:
return make_response("Invalid value for flow rate: %s" % str(e), 400)
@@ -177,6 +179,8 @@ def printerBedCommand():
if response is not None:
return response
tags = {"source:api", "api:printer.bed"}
##~~ temperature
if command == "target":
target = data["target"]
@@ -186,7 +190,7 @@ def printerBedCommand():
return make_response("Not a number: %r" % target, 400)
# perform the actual temperature command
printer.set_temperature("bed", target)
printer.set_temperature("bed", target, tags=tags)
##~~ temperature offset
elif command == "offset":
@@ -240,6 +244,8 @@ def printerPrintheadCommand():
# do not jog when a print job is running or we don't have a connection
return make_response("Printer is not operational or currently printing", 409)
tags = {"source:api", "api:printer.printhead"}
valid_axes = ["x", "y", "z"]
##~~ jog command
if command == "jog":
@@ -256,7 +262,7 @@ def printerPrintheadCommand():
speed = data.get("speed", None)
# execute the jog commands
printer.jog(validated_values, relative=not absolute, speed=speed)
printer.jog(validated_values, relative=not absolute, speed=speed, tags=tags)
##~~ home command
elif command == "home":
@@ -268,14 +274,14 @@ def printerPrintheadCommand():
validated_values.append(axis)
# execute the home command
printer.home(validated_values)
printer.home(validated_values, tags=tags)
elif command == "feedrate":
factor = data["factor"]
if not isinstance(factor, (int, long, float)):
return make_response("Not a number for feed rate: %r" % factor, 400)
try:
printer.feed_rate(factor)
printer.feed_rate(factor, tags=tags)
except ValueError as e:
return make_response("Invalid value for feed rate: %s" % str(e), 400)
@@ -304,12 +310,14 @@ def printerSdCommand():
if response is not None:
return response
tags = {"source:api", "api:printer.sd"}
if command == "init":
printer.init_sd_card()
printer.init_sd_card(tags=tags)
elif command == "refresh":
printer.refresh_sd_files()
printer.refresh_sd_files(tags=tags)
elif command == "release":
printer.release_sd_card()
printer.release_sd_card(tags=tags)
return NO_CONTENT
@@ -355,6 +363,8 @@ def printerCommand():
if "parameters" in data:
parameters = data["parameters"]
tags = {"source:api", "api:printer.command"}
if "command" in data or "commands" in data:
if "command" in data:
commands = [data["command"]]
@@ -370,7 +380,7 @@ def printerCommand():
commandToSend = command % parameters
commandsToSend.append(commandToSend)
printer.commands(commandsToSend)
printer.commands(commandsToSend, tags=tags)
elif "script" in data:
script_name = data["script"]
@@ -379,7 +389,7 @@ def printerCommand():
context["context"] = data["context"]
try:
printer.script(script_name, context=context)
printer.script(script_name, context=context, tags=tags)
except UnknownScript:
return make_response("Unknown script: {script_name}".format(**locals()), 404)
+41 -27
View File
@@ -116,23 +116,14 @@ def getSettings():
"sizeThreshold": s.getInt(["gcodeViewer", "sizeThreshold"]),
"mobileSizeThreshold": s.getInt(["gcodeViewer", "mobileSizeThreshold"]),
"temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]),
"waitForStart": s.getBoolean(["feature", "waitForStartOnConnect"]),
"alwaysSendChecksum": s.getBoolean(["feature", "alwaysSendChecksum"]),
"neverSendChecksum": s.getBoolean(["feature", "neverSendChecksum"]),
"sdSupport": s.getBoolean(["feature", "sdSupport"]),
"sdRelativePath": s.getBoolean(["feature", "sdRelativePath"]),
"sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]),
"swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]),
"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]),
"externalHeatupDetection": s.getBoolean(["feature", "externalHeatupDetection"]),
"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
"pollWatched": s.getBoolean(["feature", "pollWatched"]),
"ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"]),
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]),
"firmwareDetection": s.getBoolean(["feature", "firmwareDetection"]),
"printCancelConfirmation": s.getBoolean(["feature", "printCancelConfirmation"]),
"blockWhileDwelling": s.getBoolean(["feature", "blockWhileDwelling"]),
"g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"])
"g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"]),
"autoUppercaseBlacklist": s.get(["feature", "autoUppercaseBlacklist"]),
"legacyPluginAssets": s.getBoolean(["feature", "legacyPluginAssets"])
},
"serial": {
"port": connectionOptions["portPreference"],
@@ -143,6 +134,7 @@ def getSettings():
"timeoutConnection": s.getFloat(["serial", "timeout", "connection"]),
"timeoutDetection": s.getFloat(["serial", "timeout", "detection"]),
"timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]),
"timeoutCommunicationBusy": s.getFloat(["serial", "timeout", "communicationBusy"]),
"timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]),
"timeoutTemperatureTargetSet": s.getFloat(["serial", "timeout", "temperatureTargetSet"]),
"timeoutTemperatureAutoreport": s.getFloat(["serial", "timeout", "temperatureAutoreport"]),
@@ -156,13 +148,25 @@ def getSettings():
"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]),
"autoUppercaseBlacklist": s.get(["serial", "autoUppercaseBlacklist"]),
"logPositionOnPause": s.getBoolean(["serial", "logPositionOnPause"]),
"logPositionOnCancel": s.getBoolean(["serial", "logPositionOnCancel"]),
"supportResendsWithoutOk": s.getBoolean(["serial", "supportResendsWithoutOk"]),
"waitForStart": s.getBoolean(["serial", "waitForStartOnConnect"]),
"alwaysSendChecksum": s.getBoolean(["serial", "alwaysSendChecksum"]),
"neverSendChecksum": s.getBoolean(["serial", "neverSendChecksum"]),
"sdRelativePath": s.getBoolean(["serial", "sdRelativePath"]),
"sdAlwaysAvailable": s.getBoolean(["serial", "sdAlwaysAvailable"]),
"swallowOkAfterResend": s.getBoolean(["serial", "swallowOkAfterResend"]),
"repetierTargetTemp": s.getBoolean(["serial", "repetierTargetTemp"]),
"externalHeatupDetection": s.getBoolean(["serial", "externalHeatupDetection"]),
"ignoreIdenticalResends": s.getBoolean(["serial", "ignoreIdenticalResends"]),
"firmwareDetection": s.getBoolean(["serial", "firmwareDetection"]),
"blockWhileDwelling": s.getBoolean(["serial", "blockWhileDwelling"]),
"maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]),
"maxTimeoutsPrinting": s.getInt(["serial", "maxCommunicationTimeouts", "printing"]),
"maxTimeoutsLong": s.getInt(["serial", "maxCommunicationTimeouts", "long"])
"maxTimeoutsLong": s.getInt(["serial", "maxCommunicationTimeouts", "long"]),
"capAutoreportTemp": s.getBoolean(["serial", "capabilities", "autoreport_temp"]),
"capBusyProtocol": s.getBoolean(["serial", "capabilities", "busy_protocol"])
},
"folder": {
"uploads": s.getBaseFolder("uploads"),
@@ -347,23 +351,14 @@ def _saveSettings(data):
if "sizeThreshold" in data["feature"]: s.setInt(["gcodeViewer", "sizeThreshold"], data["feature"]["sizeThreshold"])
if "mobileSizeThreshold" in data["feature"]: s.setInt(["gcodeViewer", "mobileSizeThreshold"], data["feature"]["mobileSizeThreshold"])
if "temperatureGraph" in data["feature"]: s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"])
if "waitForStart" in data["feature"]: s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"])
if "alwaysSendChecksum" in data["feature"]: s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"])
if "neverSendChecksum" in data["feature"]: s.setBoolean(["feature", "neverSendChecksum"], data["feature"]["neverSendChecksum"])
if "sdSupport" in data["feature"]: s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"])
if "sdRelativePath" in data["feature"]: s.setBoolean(["feature", "sdRelativePath"], data["feature"]["sdRelativePath"])
if "sdAlwaysAvailable" in data["feature"]: s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
if "swallowOkAfterResend" in data["feature"]: s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"])
if "repetierTargetTemp" in data["feature"]: s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
if "externalHeatupDetection" in data["feature"]: s.setBoolean(["feature", "externalHeatupDetection"], data["feature"]["externalHeatupDetection"])
if "keyboardControl" in data["feature"]: s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"])
if "ignoreIdenticalResends" in data["feature"]: s.setBoolean(["feature", "ignoreIdenticalResends"], data["feature"]["ignoreIdenticalResends"])
if "modelSizeDetection" in data["feature"]: s.setBoolean(["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"])
if "firmwareDetection" in data["feature"]: s.setBoolean(["feature", "firmwareDetection"], data["feature"]["firmwareDetection"])
if "printCancelConfirmation" in data["feature"]: s.setBoolean(["feature", "printCancelConfirmation"], data["feature"]["printCancelConfirmation"])
if "blockWhileDwelling" in data["feature"]: s.setBoolean(["feature", "blockWhileDwelling"], data["feature"]["blockWhileDwelling"])
if "g90InfluencesExtruder" in data["feature"]: s.setBoolean(["feature", "g90InfluencesExtruder"], data["feature"]["g90InfluencesExtruder"])
if "legacyPluginAssets" in data["feature"]: s.setBoolean(["feature", "legacyPluginAssets"], data["feature"]["legacyPluginAssets"])
if "autoUppercaseBlacklist" in data["feature"] and isinstance(data["feature"]["autoUppercaseBlacklist"], (list, tuple)): s.set(["feature", "autoUppercaseBlacklist"], data["feature"]["autoUppercaseBlacklist"])
if "serial" in data.keys():
if "autoconnect" in data["serial"]: s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
@@ -372,6 +367,7 @@ def _saveSettings(data):
if "timeoutConnection" in data["serial"]: s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"])
if "timeoutDetection" in data["serial"]: s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"])
if "timeoutCommunication" in data["serial"]: s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
if "timeoutCommunicationBusy" in data["serial"]: s.setFloat(["serial", "timeout", "communicationBusy"], data["serial"]["timeoutCommunicationBusy"])
if "timeoutTemperature" in data["serial"]: s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
if "timeoutTemperatureTargetSet" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"])
if "timeoutTemperatureAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureAutoreport"], data["serial"]["timeoutTemperatureAutoreport"])
@@ -384,13 +380,25 @@ def _saveSettings(data):
if "ignoreErrorsFromFirmware" in data["serial"]: s.setBoolean(["serial", "ignoreErrorsFromFirmware"], data["serial"]["ignoreErrorsFromFirmware"])
if "disconnectOnErrors" in data["serial"]: s.setBoolean(["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"])
if "triggerOkForM29" in data["serial"]: s.setBoolean(["serial", "triggerOkForM29"], data["serial"]["triggerOkForM29"])
if "autoUppercaseBlacklist" in data["serial"] and isinstance(data["serial"]["autoUppercaseBlacklist"], (list, tuple)): s.set(["serial", "autoUppercaseBlacklist"], data["serial"]["autoUppercaseBlacklist"])
if "supportResendsWithoutOk" in data["serial"]: s.setBoolean(["serial", "supportResendsWithoutOk"], data["serial"]["supportResendsWithoutOk"])
if "waitForStart" in data["serial"]: s.setBoolean(["serial", "waitForStartOnConnect"], data["serial"]["waitForStart"])
if "alwaysSendChecksum" in data["serial"]: s.setBoolean(["serial", "alwaysSendChecksum"], data["serial"]["alwaysSendChecksum"])
if "neverSendChecksum" in data["serial"]: s.setBoolean(["serial", "neverSendChecksum"], data["serial"]["neverSendChecksum"])
if "sdRelativePath" in data["serial"]: s.setBoolean(["serial", "sdRelativePath"], data["serial"]["sdRelativePath"])
if "sdAlwaysAvailable" in data["serial"]: s.setBoolean(["serial", "sdAlwaysAvailable"], data["serial"]["sdAlwaysAvailable"])
if "swallowOkAfterResend" in data["serial"]: s.setBoolean(["serial", "swallowOkAfterResend"], data["serial"]["swallowOkAfterResend"])
if "repetierTargetTemp" in data["serial"]: s.setBoolean(["serial", "repetierTargetTemp"], data["serial"]["repetierTargetTemp"])
if "externalHeatupDetection" in data["serial"]: s.setBoolean(["serial", "externalHeatupDetection"], data["serial"]["externalHeatupDetection"])
if "ignoreIdenticalResends" in data["serial"]: s.setBoolean(["serial", "ignoreIdenticalResends"], data["serial"]["ignoreIdenticalResends"])
if "firmwareDetection" in data["serial"]: s.setBoolean(["serial", "firmwareDetection"], data["serial"]["firmwareDetection"])
if "blockWhileDwelling" in data["serial"]: s.setBoolean(["serial", "blockWhileDwelling"], data["serial"]["blockWhileDwelling"])
if "logPositionOnPause" in data["serial"]: s.setBoolean(["serial", "logPositionOnPause"], data["serial"]["logPositionOnPause"])
if "logPositionOnCancel" in data["serial"]: s.setBoolean(["serial", "logPositionOnCancel"], data["serial"]["logPositionOnCancel"])
if "maxTimeoutsIdle" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "idle"], data["serial"]["maxTimeoutsIdle"])
if "maxTimeoutsPrinting" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "printing"], data["serial"]["maxTimeoutsPrinting"])
if "maxTimeoutsLong" in data["serial"]: s.setInt(["serial", "maxCommunicationTimeouts", "long"], data["serial"]["maxTimeoutsLong"])
if "capAutoreportTemp" in data["serial"]: s.setBoolean(["serial", "capabilities", "autoreport_temp"], data["serial"]["capAutoreportTemp"])
if "capBusyProtocol" in data["serial"]: s.setBoolean(["serial", "capabilities", "busy_protocol"], data["serial"]["capBusyProtocol"])
oldLog = s.getBoolean(["serial", "log"])
if "log" in data["serial"]: s.setBoolean(["serial", "log"], data["serial"]["log"])
@@ -412,7 +420,13 @@ def _saveSettings(data):
if "temperature" in data.keys():
if "profiles" in data["temperature"]: s.set(["temperature", "profiles"], data["temperature"]["profiles"])
if "cutoff" in data["temperature"]: s.setInt(["temperature", "cutoff"], data["temperature"]["cutoff"])
if "cutoff" in data["temperature"]:
try:
cutoff = int(data["temperature"]["cutoff"])
if cutoff > 1:
s.setInt(["temperature", "cutoff"], cutoff)
except ValueError:
pass
if "sendAutomatically" in data["temperature"]: s.setBoolean(["temperature", "sendAutomatically"], data["temperature"]["sendAutomatically"])
if "sendAutomaticallyAfter" in data["temperature"]: s.setInt(["temperature", "sendAutomaticallyAfter"], data["temperature"]["sendAutomaticallyAfter"], min=0, max=30)
+1 -1
View File
@@ -131,7 +131,7 @@ def downloadTimelapse(filename):
@restricted_access
@Permissions.TIMELAPSE_ADMIN.require(403)
def deleteTimelapse(filename):
if util.is_allowed_file(filename, ["mpg", "mpeg", "mp4"]):
if util.is_allowed_file(filename, ["mpg", "mpeg", "mp4", "m4v", "mkv"]):
timelapse_folder = settings().getBaseFolder("timelapse")
full_path = os.path.realpath(os.path.join(timelapse_folder, filename))
if full_path.startswith(timelapse_folder) and os.path.exists(full_path):
+73 -9
View File
@@ -5,6 +5,8 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import base64
from octoprint.settings import settings
import octoprint.timelapse
import octoprint.server
@@ -14,6 +16,9 @@ from octoprint.util import deprecated
from octoprint.plugin import plugin_manager
import flask as _flask
import flask_login
import flask_principal
import logging
from . import flask
@@ -41,11 +46,11 @@ def enforceApiKeyRequestHandler():
apikey = get_api_key(_flask.request)
if apikey is None and settings().getBoolean(["api", "keyEnforced"]):
return _flask.make_response("No API key provided", 401)
return _flask.make_response("No API key provided", 403)
if apikey != octoprint.server.UI_API_KEY and not settings().getBoolean(["api", "enabled"]):
# api disabled => 401
return _flask.make_response("API disabled", 401)
# api disabled => 403
return _flask.make_response("API disabled", 403)
apiKeyRequestHandler = deprecated("apiKeyRequestHandler has been renamed to enforceApiKeyRequestHandler")(enforceApiKeyRequestHandler)
@@ -69,11 +74,36 @@ def loginFromApiKeyRequestHandler():
return
user = get_user_for_apikey(apikey)
if user is not None and _flask.ext.login.login_user(user, remember=False):
_flask.ext.principal.identity_changed.send(_flask.current_app._get_current_object(),
identity=_flask.ext.principal.Identity(user.get_id()))
else:
return _flask.make_response("Invalid API key", 401)
if not loginUser(user):
return _flask.make_response("Invalid API key", 403)
def loginFromAuthorizationHeaderRequestHandler():
"""
``before_request`` handler for creating login sessions based on the Authorization header.
"""
authorization_header = get_authorization_header(_flask.request)
user = get_user_for_authorization_header(authorization_header)
loginUser(user)
def loginUser(user, remember=False):
"""
Logs the provided ``user`` into Flask Login and Principal if not None and active
Args:
user: the User to login. May be None in which case the login will fail
remember: Whether to set the ``remember`` flag on the Flask Login operation
Returns: (bool) True if the login succeeded, False otherwise
"""
if user is not None and user.is_active() and flask_login.login_user(user, remember=remember):
flask_principal.identity_changed.send(_flask.current_app._get_current_object(),
identity=flask_principal.Identity(user.get_id()))
return True
return False
def corsRequestHandler():
@@ -160,7 +190,6 @@ def get_user_for_apikey(apikey):
elif apikey == settings().get(["api", "key"]) or octoprint.server.appSessionManager.validate(apikey):
# master key or an app session key was used
return ApiUser(octoprint.server.groupManager.admin_group)
if octoprint.server.userManager.enabled:
user = octoprint.server.userManager.find_user(apikey=apikey)
if user is not None:
@@ -178,6 +207,36 @@ def get_user_for_apikey(apikey):
return None
def get_user_for_authorization_header(header):
if not settings().getBoolean(["accessControl", "trustBasicAuthentication"]):
return None
if header is None:
return None
if not header.startswith("Basic "):
# we currently only support Basic Authentication
return None
header = header.replace('Basic ', '', 1)
try:
header = base64.b64decode(header)
except TypeError:
return None
name, password = header.split(':', 1)
if not octoprint.server.userManager.enabled:
return None
user = octoprint.server.userManager.findUser(userid=name)
if settings().getBoolean(["accessControl", "checkBasicAuthenticationPassword"]) \
and not octoprint.server.userManager.checkPassword(name, password):
# password check enabled and password don't match
return None
return user
def get_api_key(request):
# Check Flask GET/POST arguments
if hasattr(request, "values") and "apikey" in request.values:
@@ -195,6 +254,11 @@ def get_api_key(request):
return None
def get_authorization_header(request):
# Tornado and Flask headers
return request.headers.get("Authorization")
def get_plugin_hash():
from octoprint.plugin import plugin_manager
+12 -6
View File
@@ -21,6 +21,7 @@ import threading
import logging
import netaddr
import os
import collections
from octoprint.settings import settings
from octoprint.util import deprecated
@@ -28,6 +29,8 @@ import octoprint.server
import octoprint.access.users
import octoprint.plugin
from octoprint.util import DefaultOrderedDict
from werkzeug.contrib.cache import BaseCache
from past.builtins import basestring
@@ -1342,7 +1345,6 @@ def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
'js/app/viewmodels/timelapse.js',
'js/app/viewmodels/uistate.js',
'js/app/viewmodels/users.js',
'js/app/viewmodels/log.js',
'js/app/viewmodels/usersettings.js',
'js/app/viewmodels/wizard.js',
'js/app/viewmodels/about.js'
@@ -1368,8 +1370,12 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
logger = logging.getLogger(__name__ + ".collect_plugin_assets")
supported_stylesheets = ("css", "less")
assets = dict(bundled=dict(js=[], css=[], less=[]),
external=dict(js=[], css=[], less=[]))
assets = dict(bundled=dict(js=DefaultOrderedDict(list),
css=DefaultOrderedDict(list),
less=DefaultOrderedDict(list)),
external=dict(js=DefaultOrderedDict(list),
css=DefaultOrderedDict(list),
less=DefaultOrderedDict(list)))
asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin)
for implementation in asset_plugins:
@@ -1395,13 +1401,13 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
for asset in all_assets["js"]:
if not asset_exists("js", asset):
continue
assets[asset_key]["js"].append('plugin/{name}/{asset}'.format(**locals()))
assets[asset_key]["js"][name].append('plugin/{name}/{asset}'.format(**locals()))
if preferred_stylesheet in all_assets:
for asset in all_assets[preferred_stylesheet]:
if not asset_exists(preferred_stylesheet, asset):
continue
assets[asset_key][preferred_stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
assets[asset_key][preferred_stylesheet][name].append('plugin/{name}/{asset}'.format(**locals()))
else:
for stylesheet in supported_stylesheets:
if not stylesheet in all_assets:
@@ -1410,7 +1416,7 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
for asset in all_assets[stylesheet]:
if not asset_exists(stylesheet, asset):
continue
assets[asset_key][stylesheet].append('plugin/{name}/{asset}'.format(**locals()))
assets[asset_key][stylesheet][name].append('plugin/{name}/{asset}'.format(**locals()))
break
return assets
+20
View File
@@ -1051,6 +1051,26 @@ class StaticDataHandler(RequestlessExceptionLoggingMixin, tornado.web.RequestHan
self.finish()
class DeprecatedEndpointHandler(tornado.web.RequestHandler):
def initialize(self, url):
self._url = url
self._logger = logging.getLogger(__name__)
def _handle_method(self, *args, **kwargs):
to_url = self._url.format(*args)
self._logger.info("Redirecting deprecated endpoint {} to {}".format(self.request.path, to_url))
self.redirect(to_url, permanent=True)
# make all http methods trigger _handle_method
get = _handle_method
post = _handle_method
put = _handle_method
patch = _handle_method
delete = _handle_method
head = _handle_method
options = _handle_method
class GlobalHeaderTransform(tornado.web.OutputTransform):
HEADERS = dict()
+45 -9
View File
@@ -12,6 +12,8 @@ try:
except:
import urlparse
from webassets.bundle import Bundle
from webassets.merge import MemoryHunk, BaseHunk
from webassets.filter import Filter
from webassets.filter.cssrewrite.base import PatternRewriter
import webassets.filter.cssrewrite.urlpath as urlpath
@@ -103,14 +105,48 @@ class JsDelimiterBundler(Filter):
out.write("\n;\n")
class JsPluginDelimiterBundler(Filter):
name = "js_plugin_delimiter_bundler"
options = {}
class ChainedHunk(BaseHunk):
def __init__(self, *hunks):
self._hunks = hunks
def input(self, _in, out, **kwargs):
source = kwargs.get("source", "n/a")
def mtime(self):
pass
out.write("// source: " + source + "\n")
out.write("(function () {\n try {\n ")
out.write(_in.read().replace('\n', '\n '))
out.write("\n } catch (error) {\n log.error(\"Error in bundled asset " + source + ":\", (error.stack || error));\n }\n})();\n")
def data(self):
result = u""
for hunk in self._hunks:
if isinstance(hunk, tuple) and len(hunk) == 2:
hunk, f = hunk
else:
f = lambda x: x
result += f(hunk.data())
return result
_PLUGIN_BUNDLE_WRAPPER_PREFIX = \
u"""// JS assets for plugin {plugin}
(function () {{
try {{
"""
_PLUGIN_BUNDLE_WRAPPER_SUFFIX = \
u"""
}} catch (error) {{
log.error("Error in JS assets for plugin {plugin}:", (error.stack || error));
}}
}})();
"""
class JsPluginBundle(Bundle):
def __init__(self, plugin, *args, **kwargs):
Bundle.__init__(self, *args, **kwargs)
self.plugin = plugin
def _merge_and_apply(self, ctx, output, force, parent_debug=None,
parent_filters=None, extra_filters=None,
disable_cache=None):
hunk = Bundle._merge_and_apply(self, ctx, output, force, parent_debug=parent_debug,
parent_filters=parent_filters, extra_filters=extra_filters,
disable_cache=disable_cache)
return ChainedHunk(MemoryHunk(_PLUGIN_BUNDLE_WRAPPER_PREFIX.format(plugin=self.plugin)),
(hunk, lambda x: x.replace("\n", "\n ")),
MemoryHunk(_PLUGIN_BUNDLE_WRAPPER_SUFFIX.format(plugin=self.plugin)))
+1 -2
View File
@@ -537,7 +537,7 @@ def _process_templates():
# sidebar
templates["sidebar"]["entries"]= dict(
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.CONNECTION)")),
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.CONNECTION)", template_header="sidebar/connection_header.jinja2")),
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-circle", styles_wrapper=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.STATUS)")),
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], template_header="sidebar/files_header.jinja2", styles_wrapper=["display: none;"],
data_bind="visible: loginState.hasPermissionKo(access.permissions.FILES_ACCESS)")
@@ -577,7 +577,6 @@ def _process_templates():
accesscontrol=(gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False)),
folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)),
appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)),
logs=(gettext("Logs"), dict(template="dialogs/settings/logs.jinja2", _div="settings_logs")),
server=(gettext("Server"), dict(template="dialogs/settings/server.jinja2", _div="settings_server", custom_bindings=False)),
)
+91 -25
View File
@@ -33,7 +33,9 @@ import uuid
import copy
import time
# noinspection PyCompatibility
from builtins import bytes
# noinspection PyCompatibility
from past.builtins import basestring
try:
@@ -41,7 +43,7 @@ try:
except ImportError:
from chainmap import ChainMap
from octoprint.util import atomic_write, is_hidden_path, dict_merge
from octoprint.util import atomic_write, is_hidden_path, dict_merge, CaseInsensitiveSet
_APPNAME = "OctoPrint"
@@ -92,6 +94,7 @@ default_settings = {
"detection": 0.5,
"connection": 10,
"communication": 30,
"communicationBusy": 3,
"temperature": 5,
"temperatureTargetSet": 2,
"temperatureAutoreport": 2,
@@ -111,10 +114,30 @@ default_settings = {
"disconnectOnErrors": True,
"ignoreErrorsFromFirmware": False,
"logResends": True,
"autoUppercaseBlacklist": ["M117"],
"supportResendsWithoutOk": False,
"logPositionOnPause": True,
"logPositionOnCancel": True,
"waitForStartOnConnect": False,
"alwaysSendChecksum": False,
"neverSendChecksum": False,
"sendChecksumWithUnknownCommands": False,
"unknownCommandsNeedAck": False,
"sdRelativePath": False,
"sdAlwaysAvailable": False,
"swallowOkAfterResend": True,
"repetierTargetTemp": False,
"externalHeatupDetection": True,
"supportWait": True,
"ignoreIdenticalResends": False,
"identicalResendsCountdown": 7,
"supportFAsCommand": False,
"firmwareDetection": True,
"blockWhileDwelling": False,
"capabilities": {
"autoreport_temp": True,
"busy_protocol": True
},
# command specific flags
"triggerOkForM29": True
@@ -157,7 +180,7 @@ default_settings = {
},
"pluginBlacklist": {
"enabled": None,
"url": "http://plugins.octoprint.org/blacklist.json",
"url": "https://plugins.octoprint.org/blacklist.json",
"ttl": 15 * 60 # 15 min
},
"diskspace": {
@@ -202,28 +225,14 @@ default_settings = {
},
"feature": {
"temperatureGraph": True,
"waitForStartOnConnect": False,
"alwaysSendChecksum": False,
"neverSendChecksum": False,
"sendChecksumWithUnknownCommands": False,
"unknownCommandsNeedAck": False,
"sdSupport": True,
"sdRelativePath": False,
"sdAlwaysAvailable": False,
"swallowOkAfterResend": True,
"repetierTargetTemp": False,
"externalHeatupDetection": True,
"supportWait": True,
"keyboardControl": True,
"pollWatched": False,
"ignoreIdenticalResends": False,
"identicalResendsCountdown": 7,
"supportFAsCommand": False,
"modelSizeDetection": True,
"firmwareDetection": True,
"printCancelConfirmation": True,
"blockWhileDwelling": False,
"g90InfluencesExtruder": False
"autoUppercaseBlacklist": ["M117"],
"g90InfluencesExtruder": False,
"legacyPluginAssets": False # TODO remove again in 1.3.8
},
"folder": {
"uploads": None,
@@ -270,7 +279,7 @@ default_settings = {
"settings": [
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
"section_features", "features", "webcam", "accesscontrol", "gcodevisualizer", "api",
"section_octoprint", "server", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate", "plugin_announcements"
"section_octoprint", "server", "folders", "appearance", "plugin_logging", "plugin_pluginmanager", "plugin_softwareupdate", "plugin_announcements"
],
"usersettings": ["access", "interface"],
"wizard": ["access"],
@@ -301,7 +310,9 @@ default_settings = {
"groupfile": None,
"autologinLocal": False,
"localNetworks": ["127.0.0.0/8"],
"autologinAs": None
"autologinAs": None,
"trustBasicAuthentication": False,
"checkBasicAuthenticationPassword": True
},
"slicing": {
"enabled": True,
@@ -368,6 +379,7 @@ default_settings = {
"repetierStyleResends": False,
"okBeforeCommandOutput": False,
"smoothieTemperatureReporting": False,
"reprapfwM114": False,
"extendedSdFileList": False,
"throttle": 0.01,
"sendWait": True,
@@ -381,6 +393,7 @@ default_settings = {
"firmwareName": "Virtual Marlin 1.0",
"sharedNozzle": False,
"sendBusy": False,
"busyInterval": 2.0,
"simulateReset": True,
"resetLines": ['start', 'Marlin: Virtual Marlin!', '\x80', 'SD card ok'],
"preparedOks": [],
@@ -390,13 +403,22 @@ default_settings = {
"capabilities": {
"AUTOREPORT_TEMP": True
},
"ambientTemperature": 21.3
"ambientTemperature": 21.3,
"errors": {
"checksum_mismatch": "Checksum mismatch",
"checksum_missing": "Missing checksum",
"lineno_mismatch": "expected line {} got {}",
"lineno_missing": "No Line Number with checksum, Last Line: {}",
"maxtemp": "MAXTEMP triggered!",
"mintemp": "MINTEMP triggered!",
"command_unknown": "Unknown command {}"
}
}
}
}
"""The default settings of the core application."""
valid_boolean_trues = [True, "true", "yes", "y", "1"]
valid_boolean_trues = CaseInsensitiveSet(True, "true", "yes", "y", "1", 1)
""" Values that are considered to be equivalent to the boolean ``True`` value, used for type conversion in various places."""
@@ -890,7 +912,8 @@ class Settings(object):
self._migrate_reverse_proxy_config,
self._migrate_printer_parameters,
self._migrate_gcode_scripts,
self._migrate_core_system_commands
self._migrate_core_system_commands,
self._migrate_serial_features
)
for migrate in migrators:
@@ -1154,6 +1177,49 @@ class Settings(object):
return changed
def _migrate_serial_features(self, config):
"""
Migrates feature flags identified as serial specific from the feature to the serial config tree and vice versa.
If a flag already exists in the target tree, only deletes the copy in the source tree.
"""
changed = False
FEATURE_TO_SERIAL = ("waitForStartOnConnect", "alwaysSendChecksum", "neverSendChecksum",
"sendChecksumWithUnknownCommands", "unknownCommandsNeedAck", "sdRelativePath",
"sdAlwaysAvailable", "swallowOkAfterResend", "repetierTargetTemp",
"externalHeatupDetection", "supportWait", "ignoreIdenticalResends",
"identicalResendsCountdown", "supportFAsCommand", "firmwareDetection",
"blockWhileDwelling")
SERIAL_TO_FEATURE = ("autoUppercaseBlacklist",)
def migrate_key(key, source, target):
if source in config and key in config[source]:
if config.get(target) is None:
# make sure we have a serial tree
config[target] = dict()
if key not in config[target]:
# only copy over if it's not there yet
config[target][key] = config[source][key]
# delete feature flag
del config[source][key]
return True
return False
for key in FEATURE_TO_SERIAL:
changed = migrate_key(key, "feature", "serial") or changed
for key in SERIAL_TO_FEATURE:
changed = migrate_key(key, "serial", "feature") or changed
if changed:
# let's make a backup of our current config, in case someone wants to roll back to an
# earlier version and needs a backup of their flags
backup_path = self.backup("serial_feature_migration")
self._logger.info("Made a copy of the current config at {} to allow recovery of serial feature flags".format(backup_path))
return changed
def backup(self, suffix, path=None):
import shutil
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
@@ -69,7 +69,7 @@ GCODE.renderer = (function(){
ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y);
drawGrid();
drawBoundingBox();
if(renderOptions['showNextLayer'] && layerNumStore < model.length - 1) {
if (renderOptions['showNextLayer'] && model && model.length && layerNumStore < model.length - 1) {
drawLayer(layerNumStore + 1, 0, GCODE.renderer.getLayerNumSegments(layerNumStore + 1), true);
}
if (renderOptions['showPreviousLayer'] && layerNumStore > 0) {
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

@@ -1,30 +0,0 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var url = "api/logs";
var OctoPrintLogsClient = function(base) {
this.base = base;
};
OctoPrintLogsClient.prototype.list = function(opts) {
return this.base.get(url, opts);
};
OctoPrintLogsClient.prototype.delete = function(file, opts) {
var fileUrl = url + "/" + file;
return this.base.delete(fileUrl, opts);
};
OctoPrintLogsClient.prototype.download = function(file, opts) {
var fileUrl = url + "/" + file;
return this.base.download(fileUrl, opts);
};
OctoPrintClient.registerComponent("logs", OctoPrintLogsClient);
return OctoPrintLogsClient;
});
+27 -25
View File
@@ -105,12 +105,12 @@ $(function() {
var userAgent = (navigator && navigator.userAgent || "").toLowerCase();
var vendor = (navigator && navigator.vendor || "").toLowerCase();
exports.browser.opera = userAgent.match(/opera|opr/) != null;
exports.browser.chrome = !exports.browser.opera && /google inc/.test(vendor) && userAgent.match(/chrome|crios/) != null;
exports.browser.firefox = userAgent.match(/firefox|fxios/) != null;
exports.browser.ie = userAgent.match(/msie|trident/) != null;
exports.browser.edge = userAgent.match(/edge/) != null;
exports.browser.safari = !exports.browser.chrome && !exports.browser.edge && !exports.browser.opera && userAgent.match(/safari/) != null;
exports.browser.opera = userAgent.match(/opera|opr/) !== null;
exports.browser.chrome = !exports.browser.opera && /google inc/.test(vendor) && userAgent.match(/chrome|crios/) !== null;
exports.browser.firefox = userAgent.match(/firefox|fxios/) !== null;
exports.browser.ie = userAgent.match(/msie|trident/) !== null;
exports.browser.edge = userAgent.match(/edge/) !== null;
exports.browser.safari = !exports.browser.chrome && !exports.browser.edge && !exports.browser.opera && userAgent.match(/safari/) !== null;
exports.browser.mobile = $.browser.mobile;
exports.browser.desktop = !exports.browser.mobile;
@@ -132,8 +132,7 @@ $(function() {
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
// http://stackoverflow.com/questions/12506897/is-safari-on-ios-6-caching-ajax-results
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if (options.type != "GET") {
var headers;
if (options.type !== "GET") {
if (options.hasOwnProperty("headers")) {
options.headers["Cache-Control"] = "no-cache";
} else {
@@ -199,7 +198,7 @@ $(function() {
return new PNotify(options);
}
var autoDisplay = options.auto_display != false;
var autoDisplay = options.auto_display !== false;
var params = $.extend(true, {}, options);
params.auto_display = false;
@@ -453,7 +452,7 @@ $(function() {
"z-index": 9999
}).off('click')
.on('click', function (e) {
if (e.target.tagName.toLowerCase() == "input")
if (e.target.tagName.toLowerCase() === "input")
return;
$(this).hide();
@@ -486,7 +485,7 @@ $(function() {
$.fn.lazyload = function() {
return this.each(function() {
if (this.tagName.toLowerCase() != "img") return;
if (this.tagName.toLowerCase() !== "img") return;
var src = this.getAttribute("data-src");
if (src) {
@@ -510,7 +509,7 @@ $(function() {
callViewModels(allViewModels, "onAfterTabChange", [current, previous]);
};
var tabs = $('#tabs a[data-toggle="tab"]');
var tabs = $('#tabs').find('a[data-toggle="tab"]');
tabs.on('show', function (e) {
var current = e.target.hash;
var previous = e.relatedTarget.hash;
@@ -521,11 +520,26 @@ $(function() {
var current = e.target.hash;
var previous = e.relatedTarget.hash;
onAfterTabChange(current, previous);
// make sure we also update the hash but stick to the current scroll position
var scrollmem = $('body').scrollTop() || $('html').scrollTop();
window.location.hash = current;
$('html,body').scrollTop(scrollmem);
});
onTabChange(OCTOPRINT_INITIAL_TAB);
onAfterTabChange(OCTOPRINT_INITIAL_TAB, undefined);
var changeTab = function() {
var hashtag = window.location.hash;
if (!hashtag) return;
var tab = $('#tabs').find('a[href="' + hashtag + '"]');
if (tab) {
tab.tab("show");
}
};
// Fix input element click problems on dropdowns
$(".dropdown input, .dropdown label").click(function(e) {
e.stopPropagation();
@@ -539,17 +553,6 @@ $(function() {
// reload overlay
$("#reloadui_overlay_reload").click(function() { location.reload(); });
var changeTab = function()
{
var hashtag = window.location.hash;
var tab = $('#tabs a[href="' + hashtag + '"]');
if (tab.length)
{
tab.tab("show");
onTabChange(hashtag);
}
};
//~~ final initialization - passive login, settings fetch, view model binding
if (!_.has(viewModelMap, "settingsViewModel")) {
@@ -673,8 +676,7 @@ $(function() {
changeTab();
});
if (window.location.hash !== "")
{
if (window.location.hash !== "") {
changeTab();
}
@@ -33,7 +33,7 @@ $(function() {
};
self.showTab = function(tab) {
$("a[href=#" + tab + "]", self.aboutTabs).tab("show");
$('a[href="#' + tab + '"]', self.aboutTabs).tab("show");
};
}
@@ -51,7 +51,7 @@ $(function() {
});
self.webcamRatioClass = ko.pureComputed(function() {
if (self.settings.webcam_streamRatio() === "4:3") {
if (self.settings.webcam_streamRatio() == "4:3") {
return "ratio43";
} else {
return "ratio169";
@@ -161,7 +161,7 @@ $(function() {
if (control.hasOwnProperty("children")) {
control.children = ko.observableArray(self._processControls(control.children));
if (!control.hasOwnProperty("layout") || !(control.layout === "vertical" || control.layout === "horizontal" || control.layout === "horizontal_grid")) {
if (!control.hasOwnProperty("layout") || !(control.layout == "vertical" || control.layout == "horizontal" || control.layout == "horizontal_grid")) {
control.layout = "vertical";
}
@@ -376,23 +376,23 @@ $(function() {
};
self._enableWebcam = function() {
if (OctoPrint.coreui.selectedTab !== "#control" || !OctoPrint.coreui.browserTabVisible) {
if (OctoPrint.coreui.selectedTab != "#control" || !OctoPrint.coreui.browserTabVisible) {
return;
}
if (self.webcamDisableTimeout !== undefined) {
if (self.webcamDisableTimeout != undefined) {
clearTimeout(self.webcamDisableTimeout);
}
var webcamImage = $("#webcam_image");
var currentSrc = webcamImage.attr("src");
// safari bug doesn't release the mjpeg stream, so we just set it up the once
if (OctoPrint.coreui.browser.safari && currentSrc !== undefined) {
if (OctoPrint.coreui.browser.safari && currentSrc != undefined) {
return;
}
var newSrc = self.settings.webcam_streamUrl();
if (currentSrc !== newSrc) {
if (currentSrc != newSrc) {
if (newSrc.lastIndexOf("?") > -1) {
newSrc += "&";
} else {
@@ -421,9 +421,9 @@ $(function() {
};
self.onTabChange = function (current, previous) {
if (current === "#control") {
if (current == "#control") {
self._enableWebcam();
} else if (previous === "#control") {
} else if (previous == "#control") {
self._disableWebcam();
}
};
+28 -28
View File
@@ -195,7 +195,7 @@ $(function() {
});
self._retrieveBedDimensions = function(currentProfileData) {
if (currentProfileData === undefined) {
if (currentProfileData == undefined) {
currentProfileData = self.settings.printerProfiles.currentProfileData();
}
@@ -203,7 +203,7 @@ $(function() {
var x = undefined, y = undefined, r = undefined, circular = false, centeredOrigin = false;
var formFactor = currentProfileData.volume.formFactor();
if (formFactor === "circular") {
if (formFactor == "circular") {
r = currentProfileData.volume.width() / 2;
circular = true;
centeredOrigin = true;
@@ -211,7 +211,7 @@ $(function() {
x = currentProfileData.volume.width();
y = currentProfileData.volume.depth();
if (currentProfileData.volume.origin) {
centeredOrigin = currentProfileData.volume.origin() === "center";
centeredOrigin = currentProfileData.volume.origin() == "center";
}
}
@@ -228,7 +228,7 @@ $(function() {
};
self._retrieveToolOffsets = function(currentProfileData) {
if (currentProfileData === undefined) {
if (currentProfileData == undefined) {
currentProfileData = self.settings.printerProfiles.currentProfileData();
}
@@ -247,7 +247,7 @@ $(function() {
};
self._retrieveAxesConfiguration = function(currentProfileData) {
if (currentProfileData === undefined) {
if (currentProfileData == undefined) {
currentProfileData = self.settings.printerProfiles.currentProfileData();
}
@@ -381,7 +381,7 @@ $(function() {
self.loadFile = function(path, date){
self.enableReload(false);
self.needsLoad = false;
if (self.status === "idle" && self.errorCount < 3) {
if (self.status == "idle" && self.errorCount < 3) {
self.status = "request";
OctoPrint.files.download("local", path)
.done(function(response, rstatus) {
@@ -409,10 +409,10 @@ $(function() {
GCODE.renderer.clear();
GCODE.gCodeReader.loadFile(par);
if (self.layerSlider !== undefined) {
if (self.layerSlider != undefined) {
self.layerSlider.slider("disable");
}
if (self.layerCommandSlider !== undefined) {
if (self.layerCommandSlider != undefined) {
self.layerCommandSlider.slider("disable");
}
};
@@ -437,10 +437,10 @@ $(function() {
GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd);
GCODE.ui.updateLayerInfo(cmdIndex.layer);
if (self.layerSlider !== undefined) {
if (self.layerSlider != undefined) {
self.layerSlider.slider("setValue", cmdIndex.layer);
}
if (self.layerCommandSlider !== undefined) {
if (self.layerCommandSlider != undefined) {
self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]);
}
};
@@ -462,17 +462,17 @@ $(function() {
self.currentlyPrinting = data.state.flags && (data.state.flags.printing || data.state.flags.paused);
if(self.loadedFilepath
&& self.loadedFilepath === data.job.file.path
&& self.loadedFileDate === data.job.file.date) {
&& self.loadedFilepath == data.job.file.path
&& self.loadedFileDate == data.job.file.date) {
if (OctoPrint.coreui.browserTabVisible && self.tabActive && self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) {
self._renderPercentage(data.progress.completion);
}
self.errorCount = 0
} else {
self.clear();
if (data.job.file.path && data.job.file.origin !== "sdcard"
&& self.status !== "request"
&& (!self.waitForApproval() || self.selectedFile.path() !== data.job.file.path || self.selectedFile.date() !== data.job.file.date)) {
if (data.job.file.path && data.job.file.origin != "sdcard"
&& self.status != "request"
&& (!self.waitForApproval() || self.selectedFile.path() != data.job.file.path || self.selectedFile.date() != data.job.file.date)) {
self.selectedFile.path(data.job.file.path);
self.selectedFile.date(data.job.file.date);
self.selectedFile.size(data.job.file.size);
@@ -512,7 +512,7 @@ $(function() {
self._onModelLoaded = function(model) {
if (!model) {
self.ui_modelInfo("");
if (self.layerSlider !== undefined) {
if (self.layerSlider != undefined) {
self.layerSlider.slider("disable");
self.layerSlider.slider("setMax", 1);
self.layerSlider.slider("setValue", 0);
@@ -532,7 +532,7 @@ $(function() {
self.ui_modelInfo(output.join("<br>"));
self.maxLayer = model.layersPrinted - 1;
if (self.layerSlider !== undefined) {
if (self.layerSlider != undefined) {
self.layerSlider.slider("enable");
self.layerSlider.slider("setMax", self.maxLayer);
self.layerSlider.slider("setValue", 0);
@@ -546,7 +546,7 @@ $(function() {
self._onLayerSelected = function(layer) {
if (!layer) {
self.ui_layerInfo("");
if (self.layerCommandSlider !== undefined) {
if (self.layerCommandSlider != undefined) {
self.layerCommandSlider.slider("disable");
self.layerCommandSlider.slider("setMax", 1);
self.layerCommandSlider.slider("setValue", [0, 1]);
@@ -560,8 +560,8 @@ $(function() {
output.push(gettext("Layer number") + ": " + (layer.number + 1));
output.push(gettext("Layer height") + " (mm): " + layer.height);
output.push(gettext("GCODE commands") + ": " + layer.commands);
if (layer.filament !== undefined) {
if (layer.filament.length === 1) {
if (layer.filament != undefined) {
if (layer.filament.length == 1) {
output.push(gettext("Filament") + ": " + layer.filament[0].toFixed(2) + "mm");
} else {
for (var i = 0; i < layer.filament.length; i++) {
@@ -573,7 +573,7 @@ $(function() {
self.ui_layerInfo(output.join("<br>"));
if (self.layerCommandSlider !== undefined) {
if (self.layerCommandSlider != undefined) {
self.layerCommandSlider.slider("enable");
self.layerCommandSlider.slider("setMax", layer.commands - 1);
self.layerCommandSlider.slider("setValue", [0, layer.commands - 1]);
@@ -588,11 +588,11 @@ $(function() {
if (!options) return;
for (var opt in options) {
if (opt === "zoomInOnModel" && options[opt] !== self.renderer_zoomOnModel()) {
if (opt == "zoomInOnModel" && options[opt] != self.renderer_zoomOnModel()) {
self.renderer_zoomOnModel(false);
} else if (opt === "centerViewport" && options[opt] !== self.renderer_centerViewport()) {
} else if (opt == "centerViewport" && options[opt] != self.renderer_centerViewport()) {
self.renderer_centerViewport(false);
} else if (opt === "moveModel" && options[opt] !== self.renderer_centerModel()) {
} else if (opt == "moveModel" && options[opt] != self.renderer_centerModel()) {
self.renderer_centerModel(false);
}
}
@@ -602,7 +602,7 @@ $(function() {
if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false);
var value = event.value;
if (self.currentLayer !== undefined && self.currentLayer === value) return;
if (self.currentLayer !== undefined && self.currentLayer == value) return;
self.currentLayer = value;
GCODE.ui.changeSelectedLayer(value);
@@ -642,7 +642,7 @@ $(function() {
if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false);
var tuple = event.value;
if (self.currentCommand !== undefined && self.currentCommand[0] === tuple[0] && self.currentCommand[1] === tuple[1]) return;
if (self.currentCommand !== undefined && self.currentCommand[0] == tuple[0] && self.currentCommand[1] == tuple[1]) return;
self.currentCommand = tuple;
GCODE.ui.changeSelectedCommands(self.layerSlider.slider("getValue"), tuple[0], tuple[1]);
@@ -657,14 +657,14 @@ $(function() {
};
self.onTabChange = function(current, previous) {
self.tabActive = current === "#gcode";
self.tabActive = current == "#gcode";
if (self.tabActive && self.needsLoad) {
self.loadFile(self.selectedFile.path(), self.selectedFile.date());
}
};
self.shiftLayer = function(value){
if (value !== self.currentLayer) {
if (value != self.currentLayer) {
self.layerSlider.slider('setValue', value);
value = self.layerSlider.slider('getValue');
//This sets the scroll bar to the appropriate position.
@@ -1,73 +0,0 @@
$(function() {
function LogViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.access = parameters[1];
// 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() {
if (!self.loginState.hasPermission(self.access.permissions.LOGS))
return;
OctoPrint.logs.list()
.done(self.fromResponse);
};
self.fromResponse = function(response) {
var files = response.files;
if (files === undefined)
return;
self.listHelper.updateItems(files);
};
self.removeFile = function(filename) {
if (!self.loginState.hasPermission(self.access.permissions.LOGS))
return;
OctoPrint.logs.delete(filename)
.done(self.requestData);
};
self.onSettingsShown = function() {
self.requestData();
};
}
OCTOPRINT_VIEWMODELS.push({
construct: LogViewModel,
dependencies: ["loginStateViewModel", "accessViewModel"],
elements: ["#logs"]
});
});
@@ -114,7 +114,7 @@ $(function() {
self.login = function(u, p, r, notifications) {
var username = u || self.loginUser();
var password = p || self.loginPass();
var remember = (r !== undefined ? r : self.loginRemember());
var remember = (r != undefined ? r : self.loginRemember());
notifications = notifications !== false;
return OctoPrint.browser.login(username, password, remember)
@@ -51,7 +51,7 @@ $(function() {
self.volumeOrigin = ko.observable();
self.volumeFormFactor.subscribe(function(value) {
if (value === "circular") {
if (value == "circular") {
self.volumeOrigin("center");
}
});
@@ -123,10 +123,10 @@ $(function() {
data = placeholder;
}
var validCharacters = (data && (data === self._sanitize(data)));
var validCharacters = (data && (data == self._sanitize(data)));
var existingProfile = self.profiles.getItem(function(item) {return item.id === data});
return !data || !validCharacters || (self.isNew() && existingProfile !== undefined);
var existingProfile = self.profiles.getItem(function(item) {return item.id == data});
return !data || !validCharacters || (self.isNew() && existingProfile != undefined);
});
self.identifierInvalidText = ko.pureComputed(function() {
@@ -136,7 +136,7 @@ $(function() {
if (!self.identifier() && !self.identifierPlaceholder()) {
return gettext("Identifier must be set");
} else if (self.identifier() !== self._sanitize(self.identifier())) {
} else if (self.identifier() != self._sanitize(self.identifier())) {
return gettext("Invalid characters, only a-z, A-Z, 0-9, -, ., _, ( and ) are allowed")
} else {
return gettext("A profile with such an identifier already exists");
@@ -170,9 +170,9 @@ $(function() {
};
var keys = [];
if (formFactor === "rectangular") {
if (formFactor == "rectangular") {
keys = ["lowerleft", "center"];
} else if (formFactor === "circular") {
} else if (formFactor == "circular") {
keys = ["center"];
}
@@ -312,7 +312,7 @@ $(function() {
}
}
if (profile.volume.formFactor === "circular") {
if (profile.volume.formFactor == "circular") {
profile.volume.depth = profile.volume.width;
}
@@ -320,7 +320,7 @@ $(function() {
};
self.defaultBoundingBox = function(width, depth, height, origin) {
if (origin === "center") {
if (origin == "center") {
var halfWidth = width / 2.0;
var halfDepth = depth / 2.0;
@@ -526,7 +526,7 @@ $(function() {
})
.fail(function(xhr) {
var text;
if (xhr.status === 409) {
if (xhr.status == 409) {
text = gettext("Cannot delete the default profile or the currently active profile.");
} else {
text = gettext("There was unexpected error while removing the printer profile, please consult the logs.");
@@ -541,7 +541,7 @@ $(function() {
};
self.updateProfile = function(profile, callback) {
if (profile === undefined) {
if (profile == undefined) {
profile = self.editor.toProfileData();
}
@@ -41,7 +41,7 @@ $(function() {
});
self.enableTranslationUpload = ko.pureComputed(function() {
var name = self.translationUploadFilename();
return name !== undefined && name.trim() !== "" && !self.invalidTranslationArchive();
return name !== undefined && name.trim() != "" && !self.invalidTranslationArchive();
});
self.translations = new ItemListHelper(
@@ -138,22 +138,14 @@ $(function() {
self.feature_sizeThreshold_str = sizeObservable(self.feature_sizeThreshold);
self.feature_mobileSizeThreshold_str = sizeObservable(self.feature_mobileSizeThreshold);
self.feature_temperatureGraph = ko.observable(undefined);
self.feature_waitForStart = ko.observable(undefined);
self.feature_sendChecksum = ko.observable("print");
self.feature_sdSupport = ko.observable(undefined);
self.feature_sdRelativePath = ko.observable(undefined);
self.feature_sdAlwaysAvailable = ko.observable(undefined);
self.feature_swallowOkAfterResend = ko.observable(undefined);
self.feature_repetierTargetTemp = ko.observable(undefined);
self.feature_disableExternalHeatupDetection = ko.observable(undefined);
self.feature_keyboardControl = ko.observable(undefined);
self.feature_pollWatched = ko.observable(undefined);
self.feature_ignoreIdenticalResends = ko.observable(undefined);
self.feature_modelSizeDetection = ko.observable(undefined);
self.feature_firmwareDetection = ko.observable(undefined);
self.feature_printCancelConfirmation = ko.observable(undefined);
self.feature_blockWhileDwelling = ko.observable(undefined);
self.feature_g90InfluencesExtruder = ko.observable(undefined);
self.feature_autoUppercaseBlacklist = ko.observable(undefined);
self.feature_legacyPluginAssets = ko.observable(undefined);
self.serial_port = ko.observable();
self.serial_baudrate = ko.observable();
@@ -163,6 +155,7 @@ $(function() {
self.serial_timeoutConnection = ko.observable(undefined);
self.serial_timeoutDetection = ko.observable(undefined);
self.serial_timeoutCommunication = ko.observable(undefined);
self.serial_timeoutCommunicationBusy = ko.observable(undefined);
self.serial_timeoutTemperature = ko.observable(undefined);
self.serial_timeoutTemperatureTargetSet = ko.observable(undefined);
self.serial_timeoutTemperatureAutoreport = ko.observable(undefined);
@@ -176,13 +169,24 @@ $(function() {
self.serial_ignoreErrorsFromFirmware = ko.observable(undefined);
self.serial_disconnectOnErrors = ko.observable(undefined);
self.serial_triggerOkForM29 = ko.observable(undefined);
self.serial_autoUppercaseBlacklist = ko.observable(undefined);
self.serial_waitForStart = ko.observable(undefined);
self.serial_sendChecksum = ko.observable("print");
self.serial_sdRelativePath = ko.observable(undefined);
self.serial_sdAlwaysAvailable = ko.observable(undefined);
self.serial_swallowOkAfterResend = ko.observable(undefined);
self.serial_repetierTargetTemp = ko.observable(undefined);
self.serial_disableExternalHeatupDetection = ko.observable(undefined);
self.serial_ignoreIdenticalResends = ko.observable(undefined);
self.serial_firmwareDetection = ko.observable(undefined);
self.serial_blockWhileDwelling = ko.observable(undefined);
self.serial_supportResendsWithoutOk = ko.observable(undefined);
self.serial_logPositionOnPause = ko.observable(undefined);
self.serial_logPositionOnCancel = ko.observable(undefined);
self.serial_maxTimeoutsIdle = ko.observable(undefined);
self.serial_maxTimeoutsPrinting = ko.observable(undefined);
self.serial_maxTimeoutsLong = ko.observable(undefined);
self.serial_capAutoreportTemp = ko.observable(undefined);
self.serial_capBusyProtocol = ko.observable(undefined);
self.folder_uploads = ko.observable(undefined);
self.folder_timelapse = ko.observable(undefined);
@@ -248,6 +252,25 @@ $(function() {
self.server_onlineCheckBroken(false);
};
self.observableCopies = {
"feature_waitForStart": "serial_waitForStart",
"feature_sendChecksum": "serial_sendChecksum",
"feature_sdRelativePath": "serial_sdRelativePath",
"feature_sdAlwaysAvailable": "serial_sdAlwaysAvailable",
"feature_swallowOkAfterResend": "serial_swallowOkAfterResend",
"feature_repetierTargetTemp": "serial_repetierTargetTemp",
"feature_disableExternalHeatupDetection": "serial_disableExternalHeatupDetection",
"feature_ignoreIdenticalResends": "serial_ignoreIdenticalResends",
"feature_firmwareDetection": "serial_firmwareDetection",
"feature_blockWhileDwelling": "serial_blockWhileDwelling",
"serial_": "feature_"
};
_.each(self.observableCopies, function(value, key) {
if (self.hasOwnProperty(value)) {
self[key] = self[value];
}
});
self.addTemperatureProfile = function() {
self.temperature_profiles.push({name: "New", extruder:0, bed:0});
};
@@ -418,7 +441,7 @@ $(function() {
autoUpload: false,
headers: OctoPrint.getRequestHeaders(),
add: function(e, data) {
if (data.files.length === 0) {
if (data.files.length == 0) {
return false;
}
@@ -447,14 +470,14 @@ $(function() {
self.settingsDialog.on('show', function(event) {
OctoPrint.coreui.settingsOpen = true;
if (event.target.id === "settings_dialog") {
if (event.target.id == "settings_dialog") {
self.requestTranslationData();
callViewModels(allViewModels, "onSettingsShown");
}
});
self.settingsDialog.on('hidden', function(event) {
OctoPrint.coreui.settingsOpen = false;
if (event.target.id === "settings_dialog") {
if (event.target.id == "settings_dialog") {
callViewModels(allViewModels, "onSettingsHidden");
}
});
@@ -528,11 +551,11 @@ $(function() {
self.requestData = function(local) {
// handle old parameter format
var callback = undefined;
if (arguments.length === 2 || _.isFunction(local)) {
if (arguments.length == 2 || _.isFunction(local)) {
var exc = new Error();
log.warn("The callback parameter of SettingsViewModel.requestData is deprecated, the method now returns a promise, please use that instead. Stacktrace:", (exc.stack || exc.stacktrace || "<n/a>"));
if (arguments.length === 2) {
if (arguments.length == 2) {
callback = arguments[0];
local = arguments[1];
} else {
@@ -629,8 +652,8 @@ $(function() {
var translations = [];
_.each(translationsByLocale, function(item) {
item["packs"].sort(function(a, b) {
if (a.identifier === "_core") return -1;
if (b.identifier === "_core") return 1;
if (a.identifier == "_core") return -1;
if (b.identifier == "_core") return 1;
if (a.display < b.display) return -1;
if (a.display > b.display) return 1;
@@ -643,7 +666,7 @@ $(function() {
};
self.languagePackDisplay = function(item) {
return item.display + ((item.english !== undefined) ? ' (' + item.english + ')' : '');
return item.display + ((item.english != undefined) ? ' (' + item.english + ')' : '');
};
self.languagePacksAvailable = ko.pureComputed(function() {
@@ -660,23 +683,23 @@ $(function() {
*/
self.getLocalData = function() {
var data = {};
if (self.settings !== undefined) {
if (self.settings != undefined) {
data = ko.mapping.toJS(self.settings);
}
// some special read functions for various observables
var specialMappings = {
feature: {
externalHeatupDetection: function() { return !self.feature_disableExternalHeatupDetection()},
alwaysSendChecksum: function() { return self.feature_sendChecksum() === "always"},
neverSendChecksum: function() { return self.feature_sendChecksum() === "never"}
autoUppercaseBlacklist: function() { return splitTextToArray(self.feature_autoUppercaseBlacklist(), ",", true) }
},
serial: {
additionalPorts : function() { return commentableLinesToArray(self.serial_additionalPorts()) },
additionalBaudrates: function() { return _.map(splitTextToArray(self.serial_additionalBaudrates(), ",", true, function(item) { return !isNaN(parseInt(item)); }), function(item) { return parseInt(item); }) },
longRunningCommands: function() { return splitTextToArray(self.serial_longRunningCommands(), ",", true) },
checksumRequiringCommands: function() { return splitTextToArray(self.serial_checksumRequiringCommands(), ",", true) },
autoUppercaseBlacklist: function() { return splitTextToArray(self.serial_autoUppercaseBlacklist(), ",", true) }
externalHeatupDetection: function() { return !self.serial_disableExternalHeatupDetection()},
alwaysSendChecksum: function() { return self.serial_sendChecksum() == "always"},
neverSendChecksum: function() { return self.serial_sendChecksum() == "never"}
},
scripts: {
gcode: function() {
@@ -710,17 +733,22 @@ $(function() {
// process all key-value-pairs here
_.forOwn(data, function(value, key) {
var observable = key;
if (keyPrefix !== undefined) {
if (keyPrefix != undefined) {
observable = keyPrefix + "_" + observable;
}
if (self.observableCopies.hasOwnProperty(observable)) {
// only a copy, skip
return;
}
if (mapping && mapping[key] && _.isFunction(mapping[key])) {
result[key] = mapping[key]();
flag = true;
} else if (_.isPlainObject(value)) {
// value is another object, we'll dive deeper
var subresult = mapFromObservables(value, (mapping && mapping[key]) ? mapping[key] : undefined, observable);
if (subresult !== undefined) {
if (subresult != undefined) {
// we only set something on our result if we got something back
result[key] = subresult;
flag = true;
@@ -779,16 +807,16 @@ $(function() {
}
},
feature: {
externalHeatupDetection: function(value) { self.feature_disableExternalHeatupDetection(!value) },
alwaysSendChecksum: function(value) { if (value) { self.feature_sendChecksum("always")}},
neverSendChecksum: function(value) { if (value) { self.feature_sendChecksum("never")}}
autoUppercaseBlacklist: function(value) { self.feature_autoUppercaseBlacklist(value.join(", "))}
},
serial: {
additionalPorts : function(value) { self.serial_additionalPorts(value.join("\n"))},
additionalBaudrates: function(value) { self.serial_additionalBaudrates(value.join(", "))},
longRunningCommands: function(value) { self.serial_longRunningCommands(value.join(", "))},
checksumRequiringCommands: function(value) { self.serial_checksumRequiringCommands(value.join(", "))},
autoUppercaseBlacklist: function(value) { self.serial_autoUppercaseBlacklist(value.join(", "))}
externalHeatupDetection: function(value) { self.serial_disableExternalHeatupDetection(!value) },
alwaysSendChecksum: function(value) { if (value) { self.serial_sendChecksum("always")}},
neverSendChecksum: function(value) { if (value) { self.serial_sendChecksum("never")}}
},
terminalFilters: function(value) { self.terminalFilters($.extend(true, [], value)) },
temperature: {
@@ -804,10 +832,15 @@ $(function() {
// process all key-value-pairs here
_.forOwn(data, function(value, key) {
var observable = key;
if (keyPrefix !== undefined) {
if (keyPrefix != undefined) {
observable = keyPrefix + "_" + observable;
}
if (self.observableCopies.hasOwnProperty(observable)) {
// only a copy, skip
return;
}
var haveLocalVersion = local && local.hasOwnProperty(key);
if (mapping && mapping[key] && _.isFunction(mapping[key]) && !haveLocalVersion) {
@@ -835,16 +868,16 @@ $(function() {
} else {
options = {
success: successCallback,
sending: (setAsSending === true)
sending: (setAsSending == true)
}
}
self.settingsDialog.trigger("beforeSave");
self.sawUpdateEventWhileSending = false;
self.sending(data === undefined || options.sending || false);
self.sending(data == undefined || options.sending || false);
if (data === undefined) {
if (data == undefined) {
// we also only send data that actually changed when no data is specified
data = getOnlyChangedData(self.getLocalData(), self.lastReceivedSettings);
}
@@ -920,16 +953,21 @@ $(function() {
self._resetScrollPosition = function() {
$('#settings_dialog_content', self.settingsDialog).scrollTop(0);
// also reset any contained tabs/pills/lists to first pane
$('#settings_dialog_content ul.nav-pills a[data-toggle="tab"]:first', self.settingsDialog).tab("show");
$('#settings_dialog_content ul.nav-list a[data-toggle="tab"]:first', self.settingsDialog).tab("show");
$('#settings_dialog_content ul.nav-tabs a[data-toggle="tab"]:first', self.settingsDialog).tab("show");
};
self.selectTab = function(tab) {
if (tab !== undefined) {
if (tab != undefined) {
if (!_.startsWith(tab, "#")) {
tab = "#" + tab;
}
$('ul.nav-list a[href="' + tab + '"]', self.settingsDialog).tab("show");
} else {
$('ul.nav-list a:first', self.settingsDialog).tab("show");
$('ul.nav-list a[data-toggle="tab"]:first', self.settingsDialog).tab("show");
}
};
@@ -41,10 +41,10 @@ $(function() {
};
self.profilesForSlicer = function(key) {
if (key === undefined) {
if (key == undefined) {
key = self.slicer();
}
if (key === undefined || !self.data.hasOwnProperty(key)) {
if (key == undefined || !self.data.hasOwnProperty(key)) {
return;
}
var slicer = self.data[key];
@@ -53,7 +53,7 @@ $(function() {
self.profiles.removeAll();
_.each(_.values(slicer.profiles), function(profile) {
var name = profile.displayName;
if (name === undefined) {
if (name == undefined) {
name = profile.key;
}
@@ -77,7 +77,7 @@ $(function() {
};
self.metadataForSlicer = function(key) {
if (key === undefined || !self.data.hasOwnProperty(key)) {
if (key == undefined || !self.data.hasOwnProperty(key)) {
return;
}
@@ -100,7 +100,7 @@ $(function() {
var containsSlicer = function(key) {
return _.any(slicers, function(slicer) {
return slicer.key === key;
return slicer.key == key;
});
};
@@ -134,7 +134,7 @@ $(function() {
}
var filename = file;
if (filename.lastIndexOf("/") !== 0) {
if (filename.lastIndexOf("/") != 0) {
path = path || filename.substr(0, filename.lastIndexOf("/"));
filename = filename.substr(filename.lastIndexOf("/") + 1);
}
@@ -173,10 +173,10 @@ $(function() {
};
self.enableSliceButton = ko.pureComputed(function() {
return self.destinationFilename() !== undefined
&& self.destinationFilename().trim() !== ""
&& self.slicer() !== undefined
&& self.profile() !== undefined
return self.destinationFilename() != undefined
&& self.destinationFilename().trim() != ""
&& self.slicer() != undefined
&& self.profile() != undefined
&& (!(self.printerState.isPrinting() || self.printerState.isPaused()) || !self.slicerSameDevice());
});
@@ -227,7 +227,7 @@ $(function() {
self.slicers.removeAll();
_.each(_.values(data), function(slicer) {
var name = slicer.displayName;
if (name === undefined) {
if (name == undefined) {
name = slicer.key;
}
@@ -276,13 +276,13 @@ $(function() {
destination: destinationFilename
};
if (self.path !== undefined) {
if (self.path != undefined) {
data["path"] = self.path;
}
if (self.afterSlicing() === "print") {
if (self.afterSlicing() == "print") {
data["print"] = true;
} else if (self.afterSlicing() === "select") {
} else if (self.afterSlicing() == "select") {
data["select"] = true;
}
@@ -334,7 +334,12 @@ $(function() {
yaxis: {
min: 0,
max: Math.max(Math.max.apply(null, plotInfo.max) * 1.1, 310),
ticks: 10
ticks: 10,
tickFormatter: function(val, axis) {
if (val === undefined || val === 0)
return "";
return val + "°C";
}
},
xaxis: {
mode: "time",
@@ -352,7 +357,8 @@ $(function() {
// convert to minutes
var diffInMins = Math.round(diff / (60 * 1000));
if (diffInMins === 0) {
return gettext("just now");
// don't write anything for "just now"
return "";
} else if (diffInMins < 0) {
// we can't look into the future
return "";
@@ -58,7 +58,7 @@ $(function() {
var regex = self.filterRegex();
var lineVisible = function(entry) {
return regex === undefined || !entry.line.match(regex);
return regex == undefined || !entry.line.match(regex);
};
var filtered = false;
@@ -91,7 +91,7 @@ $(function() {
var regex = self.filterRegex();
var lineVisible = function(entry) {
return regex === undefined || !entry.line.match(regex);
return regex == undefined || !entry.line.match(regex);
};
var lines = self.log();
@@ -126,7 +126,7 @@ $(function() {
});
self.blacklist=[];
self.settings.serial_autoUppercaseBlacklist.subscribe(function(newValue) {
self.settings.feature_autoUppercaseBlacklist.subscribe(function(newValue) {
self.blacklist = splitTextToArray(newValue, ",", true);
});
@@ -205,7 +205,7 @@ $(function() {
if (!self.terminalLogDuringPrinting() && self.isPrinting()) {
var last = self.plainLogLines()[self.plainLogLines().length - 1];
var disabled = "--- client too slow, log output disabled while printing ---";
if (last !== disabled) {
if (last != disabled) {
self.plainLogLines.push(disabled);
}
return;
@@ -226,7 +226,7 @@ $(function() {
}
var newLog = self.log().concat(_.map(newData, function(line) { return self._toInternalFormat(line) }));
if (newData.length !== data.length) {
if (newData.length != data.length) {
var cutoff = "--- too many lines to buffer, cut off ---";
newLog.push(self._toInternalFormat(cutoff, "cut"));
}
@@ -246,7 +246,7 @@ $(function() {
};
self._toInternalFormat = function(line, type) {
if (type === undefined) {
if (type == undefined) {
type = "line";
}
return {line: escapeUnprintableCharacters(line), type: type}
@@ -264,7 +264,7 @@ $(function() {
self.updateFilterRegex = function() {
var filterRegexStr = self.activeFilters().join("|").trim();
if (filterRegexStr === "") {
if (filterRegexStr == "") {
self.filterRegex(undefined);
} else {
self.filterRegex(new RegExp(filterRegexStr));
@@ -278,6 +278,17 @@ $(function() {
}
};
self.terminalScrollEvent = _.throttle(function () {
if (self.autoscrollEnabled()) {
var container = self.fancyFunctionality() ? $("#terminal-output") : $("#terminal-output-lowfi");
var maxScroll = container[0].scrollHeight - container[0].offsetHeight;
if (container.scrollTop() <= maxScroll ) {
self.autoscrollEnabled(false);
}
}
}, 250);
self.gotoTerminalCommand = function() {
// skip if user highlights text.
var sel = getSelection().toString();
@@ -290,6 +301,10 @@ $(function() {
self.toggleAutoscroll = function() {
self.autoscrollEnabled(!self.autoscrollEnabled());
if (self.autoscrollEnabled()) {
self.updateOutput();
}
};
self.selectAll = function() {
@@ -307,7 +322,15 @@ $(function() {
};
self.copyAll = function() {
copyToClipboard(self.plainLogLines().join("\n"));
var lines;
if (self.fancyFunctionality()) {
lines = _.map(self.log(), "line");
} else {
lines = self.plainLogLines();
}
copyToClipboard(lines.join("\n"));
};
// command matching regex
@@ -357,10 +380,10 @@ $(function() {
self.handleKeyDown = function(event) {
var keyCode = event.keyCode;
if (keyCode === 38 || keyCode === 40) {
if (keyCode === 38 && self.cmdHistory.length > 0 && self.cmdHistoryIdx > 0) {
if (keyCode == 38 || keyCode == 40) {
if (keyCode == 38 && self.cmdHistory.length > 0 && self.cmdHistoryIdx > 0) {
self.cmdHistoryIdx--;
} else if (keyCode === 40 && self.cmdHistoryIdx < self.cmdHistory.length - 1) {
} else if (keyCode == 40 && self.cmdHistoryIdx < self.cmdHistory.length - 1) {
self.cmdHistoryIdx++;
}
@@ -379,7 +402,7 @@ $(function() {
};
self.handleKeyUp = function(event) {
if (event.keyCode === 13) {
if (event.keyCode == 13) {
self.sendCommand();
}
@@ -388,7 +411,7 @@ $(function() {
};
self.onAfterTabChange = function(current, previous) {
self.tabActive = current === "#term";
self.tabActive = current == "#term";
self.updateOutput();
};
@@ -25,7 +25,7 @@ $(function() {
self.access_apikey(undefined);
self.interface_language("_default");
if (newUser !== undefined) {
if (newUser != undefined) {
self.access_apikey(newUser.apikey);
if (newUser.settings.hasOwnProperty("interface") && newUser.settings.interface.hasOwnProperty("language")) {
self.interface_language(newUser.settings.interface.language);
@@ -34,13 +34,13 @@ $(function() {
});
self.passwordMismatch = ko.pureComputed(function() {
return self.access_password() !== self.access_repeatedPassword();
return self.access_password() != self.access_repeatedPassword();
});
self.show = function(user) {
if (!CONFIG_ACCESS_CONTROL) return;
if (user === undefined) {
if (user == undefined) {
user = self.loginState.currentUser();
}
@@ -72,13 +72,13 @@ $(function() {
return false;
},
onTabShow: function(tab, navigation, index) {
if (index < 0 || tab.length === 0) {
if (index < 0 || tab.length == 0) {
return true;
}
var total = self.wizardDialog.bootstrapWizard("navigationLength");
if (index === total) {
if (index == total) {
self.wizardDialog.find(".button-next").hide();
self.wizardDialog.find(".button-finish").show().removeClass("disabled");
} else {
@@ -87,17 +87,17 @@ $(function() {
}
var active = tab[0].id;
if (active !== undefined) {
if (active != undefined) {
callViewModels(allViewModels, "onAfterWizardTabChange", [active]);
}
},
onTabChange: function(tab, navigation, index, nextTabIndex, nextTab) {
var current, next;
if (index === undefined || index < 0 ||
nextTabIndex === undefined || nextTabIndex < 0 ||
index === nextTabIndex ||
tab.length === 0 || nextTab.length === 0) {
if (index == undefined || index < 0 ||
nextTabIndex == undefined || nextTabIndex < 0 ||
index == nextTabIndex ||
tab.length == 0 || nextTab.length == 0) {
// let's ignore that nonsense
return;
}
@@ -105,7 +105,7 @@ $(function() {
current = tab[0].id;
next = nextTab[0].id;
if (current !== undefined && next !== undefined) {
if (current != undefined && next != undefined) {
var result = true;
callViewModels(allViewModels, "onBeforeWizardTabChange", function(method) {
// we want to continue evaluating even if result becomes false
@@ -145,7 +145,7 @@ $(function() {
// first, or it won't happen after the reload flag has been
// set once due to the || making further evaluation unnecessary
// then
reload = (method() === "reload") || reload;
reload = (method() == "reload") || reload;
});
self.finishWizard()
.done(function() {
-21
View File
@@ -404,27 +404,6 @@ table {
margin-top: 0 !important;
}
// log files
&.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;
.actioncol;
}
// Printer profiles
&.settings_printerProfiles_profiles_name {
text-overflow: ellipsis;
@@ -5,14 +5,14 @@
<p>Version <span class="version">{{ display_version }}</span></p>
<ul>
<li>Website: <a href="http://octoprint.org" target="_blank" rel="noreferrer noopener">octoprint.org</a></li>
<li>Website: <a href="https://octoprint.org" target="_blank" rel="noreferrer noopener">octoprint.org</a></li>
<li>Source Code: <a href="https://github.com/foosel/OctoPrint" target="_blank" rel="noreferrer noopener">github.com/foosel/OctoPrint</a></li>
<li>Documentation: <a href="http://docs.octoprint.org" target="_blank" rel="noreferrer noopener">docs.octoprint.org</a></li>
</ul>
<p>
<strong>Development of OctoPrint wouldn't be possible without <a href="javascript:void(0)" data-bind="click: function() { showTab('{{ templates.about.entries.supporters[1]._div }}'); }">its supporters</a>.</strong><br>
If you enjoy OctoPrint, please consider <a href="http://octoprint.org/support-octoprint/" target="_blank" rel="noreferrer noopener">supporting its ongoing development</a>.
If you enjoy OctoPrint, please consider <a href="https://octoprint.org/support-octoprint/?utm_source=octoprint&utm_medium=about_dialog" target="_blank" rel="noreferrer noopener">supporting its ongoing development</a>.
</p>
<p>
@@ -1,4 +1,18 @@
<form class="form-horizontal">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_legacyPluginAssets" id="settings-legacyPluginAssets"> {{ _('Enable legacy plugin asset bundling') }} <span class="label label-info">Compatibility</span>
<span class="help-block">{% trans url="https://octoprint.org/blog/2017/12/01/heads-up-plugin-authors/" %}
Enable this, save and restart your server if you are running into issues with plugins with OctoPrint
1.3.6 or later that used to work with OctoPrint up to version 1.3.5. See <a href="{{ url }}">here</a>
for details on why this is happening. Note that this legacy flag will be removed in a future
OctoPrint version (currently planned for 1.3.8), so urge the authors of affected plugins to push
an update with a fix.
{% endtrans %}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
@@ -34,87 +48,19 @@
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_waitForStart" id="settings-featureWaitForStart"> {{ _('Wait for <code>start</code> on connect') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_g90InfluencesExtruder" id="settings-g90InfluencesExtruder"> {{ _('<code>G90</code>/<code>G91</code> overrides relative extruder mode') }} <span class="label">{{ _('Smoothieware') }}</span>
<span class="help-block">{{ _('This is used by the GCODE analysis in the backend and the viewer in the frontend to interpret your sliced files correctly.') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="control-group" title="{{ _('Commands to not completely auto uppercase in the terminal tab') }}">
<label class="control-label" for="settings-featureAutoUppercaseBlacklist">{{ _('Terminal Auto Uppercase Blacklist') }}</label>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_firmwareDetection" id="settings-firmwareDetection"> {{ _('Enable automatic firmware detection') }}
<span class="help-inline">{% trans %}
If enabled, OctoPrint will try to figure out your printer's firmware automatically and adjust some communication parameters based on that.
If that doesn't work out, or you want more granular control, uncheck this and the parameters in question will become visible for you to adjust.
{% endtrans %}</span>
</label>
</div>
</div>
<div data-bind="visible: !feature_firmwareDetection()">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdRelativePath" id="settings-sdRelativePath"> {{ _('Select SD files by relative path') }} <span class="label">{{ _('RepRap Firmware') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_sdAlwaysAvailable" id="settings-featureSdAlwaysAvailable"> {{ _('Always assume SD card is present') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_ignoreIdenticalResends" id="settings-ignoreIdenticalResends"> {{ _('Ignore consecutive resend requests for the same line') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_repetierTargetTemp" id="settings-featureRepetierTargetTemp"> {{ _('Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_disableExternalHeatupDetection" id="settings-featureExternalHeatupDetection"> {{ _('Disable detection of external heatups') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_blockWhileDwelling" id="settings-featureBlockWhileDwelling"> {{ _('Actively pause communication during <code>G4</code> dwell command') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Send a checksum with the command')}}</label>
<div class="controls">
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="print" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumPrint"> {{ _('When printing') }}
</label>
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="always" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumAlways"> {{ _('Always') }} <span class="label">{{ _('Repetier') }}</span>
</label>
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="never" data-bind="checked: feature_sendChecksum" id="settings-featureSendChecksumNever"> {{ _('Never') }}
</label>
</div>
<input type="text" class="input-block-level" id="settings-featureAutoUppercaseBlacklist" data-bind="value: feature_autoUppercaseBlacklist">
<span class="help-block">{{ _('Use this to specify the commands that should not have their parameters automatically uppercased in the terminal tab. Just the G or M code, comma separated.') }}</span>
</div>
</div>
</form>
@@ -1,46 +0,0 @@
<div id="logs">
<h1>{{ _('Logs') }}</h1>
<div class="pull-right">
<small>
{{ _('Sort by') }}: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('modification'); }">{{ _('Modification date') }} ({{ _('descending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">{{ _('Size') }} ({{ _('descending') }})</a>
</small>
</div>
<table class="table table-striped table-hover table-condensed table-hover" id="log_files">
<thead>
<tr>
<th class="settings_logs_name">{{ _('Name') }}</th>
<th class="settings_logs_size">{{ _('Size') }}</th>
<th class="settings_logs_date">{{ _('Date') }}</th>
<th class="settings_logs_action">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: listHelper.paginatedItems">
<tr data-bind="attr: {title: name}">
<td class="settings_logs_name" data-bind="text: name"></td>
<td class="settings_logs_size" data-bind="text: formatSize(size)"></td>
<td class="settings_logs_date" data-bind="text: formatDate(date)"></td>
<td class="settings_logs_action">
<a href="#" class="fa fa-trash-o" data-bind="click: function() { if ($root.loginState.hasPermission($root.access.permissions.LOGS)) { $parent.removeFile($data.name); } else { return; } }, css: {disabled: !$root.loginState.hasPermissionKo($root.access.permissions.LOGS)()}"></a>&nbsp;|&nbsp;<a href="#" class="fa fa-download" data-bind="attr: {href: refs.download}"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: listHelper.currentPage() === 0}">
<a href="#" data-bind="click: listHelper.prevPage">«</a>
</li>
</ul>
<ul data-bind="foreach: listHelper.pages">
<li data-bind="css: { active: $data.number === $root.listHelper.currentPage(), disabled: $data.number === -1 }">
<a href="#" data-bind="text: $data.text, click: function() { $root.listHelper.changePage($data.number); }"></a>
</li>
</ul>
<ul>
<li data-bind="css: {disabled: listHelper.currentPage() === listHelper.lastPage()}">
<a href="#" data-bind="click: listHelper.nextPage">»</a>
</li>
</ul>
</div>
</div>
@@ -1,197 +1,341 @@
<form class="form-horizontal">
<div class="control-group" title="{{ _('Serial port to connect to, setting this to AUTO will make OctoPrint try to automatically find the right setting') }}">
<label class="control-label" for="settings-serialPort">{{ _('Serial Port') }}</label>
<div class="controls">
<select id="settings-serialPort" data-bind="options: serial_portOptions, optionsCaption: 'AUTO', value: serial_port"></select>
</div>
</div>
<div class="control-group" title="{{ _('Serial baud rate to connect with, setting this to AUTO will make OctoPrint try to automatically find the right setting') }}">
<label class="control-label" for="settings-baudrate">{{ _('Baudrate') }}</label>
<div class="controls">
<select id="settings-baudrate" data-bind="options: serial_baudrateOptions, optionsCaption: 'AUTO', value: serial_baudrate"></select>
</div>
</div>
<div class="control-group" title="{{ _('Makes OctoPrint try to connect to the printer automatically during start up') }}">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_autoconnect" id="settings-serialAutoconnect"> {{ _('Auto-connect to printer on server start') }}
</label>
</div>
</div>
<div class="control-group" title="{{ _('Interval in which to poll for the temperature information from the printer') }}">
<label class="control-label" for="settings-serialTimeoutTemperature">{{ _('Temperature interval (polling)') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="1" class="input-mini text-right" data-bind="value: serial_timeoutTemperature" id="settings-serialTimeoutTemperature">
<span class="add-on">s</span>
</div>
<span class="help-inline">{{ _('When printing or idle')}}</span>
</div>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="1" class="input-mini text-right" data-bind="value: serial_timeoutTemperatureTargetSet" id="settings-serialTimeoutTemperatureTargetSet">
<span class="add-on">s</span>
</div>
<span class="help-inline">{{ _('When a target temperature is set')}}</span>
</div>
</div>
<div class="control-group" title="{{ _('Temperature report interval to request from autoreport capable firmwares. A value of 0 disables autoreporting by the firmware and forces polling.') }}">
<label class="control-label">{{ _('Temperature interval (autoreport)') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutTemperatureAutoreport" id="settings-serialTimeoutTemperatureAutoreport">
<span class="add-on">s</span>
</div>
<span class="help-inline">{{ _('Autoreport interval to request from firmware')}}</span>
</div>
</div>
<div class="control-group" title="{{ _('Interval in which to poll for the SD printing status information from the printer while printing') }}">
<label class="control-label" for="settings-serialTimeoutSdStatus">{{ _('SD status interval') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutSdStatus" id="settings-serialTimeoutSdStatus">
<span class="add-on">s</span>
</div>
</div>
</div>
<div class="control-group" title="{{ _('Time after which the communication with your printer will be considered timed out if nothing was sent by your printer (and an attempt to get it talking again will be done). Increase this if your printer takes longer than this for some moves.') }}">
<label class="control-label" for="settings-serialTimeoutCommunication">{{ _('Communication timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutCommunication" id="settings-serialTimeoutCommunication">
<span class="add-on">s</span>
</div>
</div>
</div>
<div class="control-group" title="{{ _('Time after which a connection attempt to the printer will be considered as having failed') }}">
<label class="control-label" for="settings-serialTimeoutConnection">{{ _('Connection timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutConnection" id="settings-serialTimeoutConnection">
<span class="add-on">s</span>
</div>
</div>
</div>
<div class="control-group" title="{{ _('Time after which to consider an auto detection attempt to have failed if no successful connection is detected') }}">
<label class="control-label" for="settings-serialTimeoutDetection">{{ _('Autodetection timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutDetection" id="settings-serialTimeoutDetection">
<span class="add-on">s</span>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_log" id="settings-serialLog"> {{ _('Log communication to serial.log (might negatively impact performance)') }} <span class="label label-important">{{ _('Warning') }}</span>
</label>
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-serialAdditionalPorts">{{ _('Additional serial ports') }}</label>
<div class="controls">
<textarea rows="4" class="block" id="settings-serialAdditionalPorts" data-bind="value: serial_additionalPorts"></textarea>
<span class="help-inline">{{ _('Use this to define additional <a href="%%(glob_url)s">glob patterns</a> matching serial ports to list for connecting against, e.g. <code>/dev/ttyAMA*</code>. One entry per line.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-serialAdditionalBaudrates">{{ _('Additional baud rates') }}</label>
<div class="controls">
<input type="text" class="input-block-level" id="settings-serialAdditionalBaudrates" data-bind="value: serial_additionalBaudrates">
<span class="help-inline">{{ _('Use this to define additional serial port baud rates to list for connecting with, e.g. <code>123456</code>. Comma separated.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}</span>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_disconnectOnErrors" id="settings-disconnectOnErrors"> {{ _('Not only cancel ongoing prints but also disconnect on unhandled errors from the firmware.') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_ignoreErrorsFromFirmware" id="settings-ignoreErrorsFromFirmware"> {{ _('Ignore any unhandled errors from the firmware. Only use this if your firmware sends stuff prefixed with "Error" that is not an actual error. Might mask printer issues, be careful!') }} <span class="label label-important">{{ _('Warning') }}</span>
</label>
</div>
</div>
<ul class="nav nav-pills">
<li class="active"><a href="#settings_serial_general" data-toggle="tab">{{ _('General') }}</a></li>
<li><a href="#settings_serial_timeouts" data-toggle="tab">{{ _('Intervals &amp; timeouts') }}</a></li>
<li><a href="#settings_serial_protocol" data-toggle="tab">{{ _('Firmware &amp; protocol') }}</a></li>
<li><a href="#settings_serial_behaviour" data-toggle="tab">{{ _('Behaviour') }}</a></li>
</ul>
<div>
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', container: '#settings_serialConnection .hide' }"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<div class="control-group" title="{{ _('Command to send to the firmware on first handshake attempt.') }}">
<label class="control-label" for="settings-serialHelloCommand">{{ _('"Hello" command') }}</label>
<div class="controls">
<input type="text" class="input-block-level" id="settings-serialHelloCommand" data-bind="value: serial_helloCommand">
<span class="help-inline">{{ _('Use this to specify a different command than the default <code>M110</code> to send to the printer on initial connection to trigger a communication handshake.') }}</span>
<div class="tab-content">
<div id="settings_serial_general" class="tab-pane active">
<fieldset>
<legend>{{ _('Connection') }}</legend>
<div class="control-group" title="{{ _('Serial port to connect to, setting this to AUTO will make OctoPrint try to automatically find the right setting') }}">
<label class="control-label" for="settings-serialPort">{{ _('Serial Port') }}</label>
<div class="controls">
<select id="settings-serialPort" data-bind="options: serial_portOptions, optionsCaption: 'AUTO', value: serial_port"></select>
</div>
</div>
</div>
<div class="control-group" title="{{ _('Commands that are know to run long and hence should suppress communication timeouts from being triggered.') }}">
<label class="control-label" for="settings-serialLongRunningCommands">{{ _('Long running commands') }}</label>
<div class="controls">
<input type="text" class="input-block-level" id="settings-serialLongRunningCommands" data-bind="value: serial_longRunningCommands">
<span class="help-inline">{{ _('Use this to specify the commands known to take a long time to complete without output from your printer and hence might cause timeout issues. Just the G or M code, comma separated.') }}</span>
<div class="control-group" title="{{ _('Serial baud rate to connect with, setting this to AUTO will make OctoPrint try to automatically find the right setting') }}">
<label class="control-label" for="settings-baudrate">{{ _('Baudrate') }}</label>
<div class="controls">
<select id="settings-baudrate" data-bind="options: serial_baudrateOptions, optionsCaption: 'AUTO', value: serial_baudrate"></select>
</div>
</div>
</div>
<div class="control-group" title="{{ _('Commands that always require a line number and checksum to be sent with them.') }}">
<label class="control-label" for="settings-checksumRequiringCommands">{{ _('Commands that always require a checksum') }}</label>
<div class="controls">
<input type="text" class="input-block-level" id="settings-checksumRequiringCommands" data-bind="value: serial_checksumRequiringCommands">
<span class="help-inline">{{ _('Use this to specify which commands <strong>always</strong> need to be sent with a checksum. Comma separated list.') }}</span>
<div class="control-group" title="{{ _('Makes OctoPrint try to connect to the printer automatically during start up') }}">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_autoconnect" id="settings-serialAutoconnect"> {{ _('Auto-connect to printer on server start') }}
</label>
</div>
</div>
</div>
<div class="control-group" title="{{ _('Commands to not completely auto uppercase in the terminal tab') }}">
<label class="control-label" for="settings-serialAutoUppercaseBlacklist">{{ _('Terminal Auto Uppercase Blacklist') }}</label>
<div class="controls">
<input type="text" class="input-block-level" id="settings-serialAutoUppercaseBlacklist" data-bind="value: serial_autoUppercaseBlacklist">
<span class="help-inline">{{ _('Use this to specify the commands that should not have their parameters automatically uppercased in the terminal tab. Just the G or M code, comma separated.') }}</span>
<div class="control-group">
<label class="control-label" for="settings-serialAdditionalPorts">{{ _('Additional serial ports') }}</label>
<div class="controls">
<textarea rows="4" class="block" id="settings-serialAdditionalPorts" data-bind="value: serial_additionalPorts"></textarea>
<span class="help-inline">{{ _('Use this to define additional <a href="%%(glob_url)s">glob patterns</a> matching serial ports to list for connecting against, e.g. <code>/dev/ttyAMA*</code>. One entry per line.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}</span>
</div>
</div>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_triggerOkForM29" id="settings-triggerOkForM29"> {{ _('Generate additional <code>ok</code> for <code>M29</code>') }} <span class="label">{{ _('Most Marlin < v1.1.0') }}</span>
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_supportResendsWithoutOk" id="settings-supportResendsWithoutOk"> {{ _('Simulate an additional <code>ok</code> for resend requests') }}
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_logPositionOnPause" id="settings-logPositionOnPause"> {{ _('Log position on pause') }} <span class="label label-important">{{ _('Warning') }}</span>
<span class="help-block">{{ _('If you disabled this, the <code>pause_position</code> placeholders in your pause/resume GCODE scripts will stay unpopulated! However, pausing speed might improve slightly.') }}</span>
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_logPositionOnCancel" id="settings-logPositionOnCancel"> {{ _('Log position on cancel') }} <span class="label label-important">{{ _('Warning') }}</span>
<span class="help-block">{{ _('If you disabled this, the <code>cancel_position</code> placeholders in your cancel GCODE script and the corresponding data in the print recovery data will stay unpopulated! However, cancelling speed might improve slightly.') }}</span>
</label>
</div>
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while idle. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
<label class="control-label" for="settings-serialMaxTimeoutsIdle">{{ _('Max. consecutive timeouts while idle') }}</label>
<div class="controls">
<input type="number" min="0" class="input-mini text-right" id="settings-serialMaxTimeoutsIdle" data-bind="value: serial_maxTimeoutsIdle">
<span class="help-block">{{ _('Set to 0 to disable consecutive timeout detection and handling.') }}</span>
<div class="control-group">
<label class="control-label" for="settings-serialAdditionalBaudrates">{{ _('Additional baud rates') }}</label>
<div class="controls">
<input type="text" class="input-block-level" id="settings-serialAdditionalBaudrates" data-bind="value: serial_additionalBaudrates">
<span class="help-inline">{{ _('Use this to define additional serial port baud rates to list for connecting with, e.g. <code>123456</code>. Comma separated.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}</span>
</div>
</div>
</div>
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while printing. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
<label class="control-label" for="settings-serialMaxTimeoutsPrinting">{{ _('Max. consecutive timeouts while printing') }}</label>
<div class="controls">
<input type="number" min="0" class="input-mini text-right" id="settings-serialMaxTimeoutsPrinting" data-bind="value: serial_maxTimeoutsPrinting">
<span class="help-block">{{ _('Set to 0 to disable consecutive timeout detection and handling.') }}</span>
</fieldset>
<fieldset>
<legend>{{ _('Serial logging') }}</legend>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_log" id="settings-serialLog"> {{ _('Log communication to <code>serial.log</code>') }} <span class="label label-important">{{ _('Warning') }}</span>
<span class="help-block">{{ _('While this can negatively impact performance, a <code>serial.log</code> can be incredibly useful for debugging any issues observed in the communication between OctoPrint and your printer.') }}</span>
</label>
</div>
</div>
</div>
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while a long running command is active. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
<label class="control-label" for="settings-serialMaxTimeoutsLong">{{ _('Max. consecutive timeouts during long running commands') }}</label>
<div class="controls">
<input type="number" min="0" class="input-mini text-right" id="settings-serialMaxTimeoutsLong" data-bind="value: serial_maxTimeoutsLong">
<span class="help-block">{{ _('Set to 0 to disable consecutive timeout detection and handling.') }}</span>
</fieldset>
</div>
<div id="settings_serial_timeouts" class="tab-pane">
<fieldset id="settings_serial_timeouts_intervals">
<legend>{{ _('Query intervals') }}</legend>
<div class="control-group" title="{{ _('Interval in which to poll for the temperature information from the printer') }}">
<label class="control-label" for="settings-serialTimeoutTemperature">{{ _('Temperature interval (polling)') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="1" class="input-mini text-right" data-bind="value: serial_timeoutTemperature" id="settings-serialTimeoutTemperature">
<span class="add-on">s</span>
</div>
<span class="help-inline">{{ _('When printing or idle')}}</span>
</div>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="1" class="input-mini text-right" data-bind="value: serial_timeoutTemperatureTargetSet" id="settings-serialTimeoutTemperatureTargetSet">
<span class="add-on">s</span>
</div>
<span class="help-inline">{{ _('When a target temperature is set')}}</span>
</div>
</div>
</div>
<div class="control-group" title="{{ _('Temperature report interval to request from autoreport capable firmwares. A value of 0 disables autoreporting by the firmware and forces polling.') }}">
<label class="control-label">{{ _('Temperature interval (autoreport)') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutTemperatureAutoreport" id="settings-serialTimeoutTemperatureAutoreport">
<span class="add-on">s</span>
</div>
<span class="help-inline">{{ _('Autoreport interval to request from firmware')}}</span>
</div>
</div>
<div class="control-group" title="{{ _('Interval in which to poll for the SD printing status information from the printer while printing') }}">
<label class="control-label" for="settings-serialTimeoutSdStatus">{{ _('SD status interval') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutSdStatus" id="settings-serialTimeoutSdStatus">
<span class="add-on">s</span>
</div>
</div>
</div>
</fieldset>
<fieldset id="settings_serial_timeouts_timeouts">
<legend>{{ _('Timeouts') }}</legend>
<div class="control-group" title="{{ _('Time after which the communication with your printer will be considered timed out if nothing was sent by your printer (and an attempt to get it talking again will be done). Increase this if your printer takes longer than this for some moves.') }}">
<label class="control-label" for="settings-serialTimeoutCommunication">{{ _('Communication timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutCommunication" id="settings-serialTimeoutCommunication">
<span class="add-on">s</span>
</div>
<span class="help-inline">{{ _('<code>busy</code> protocol support not detected')}}</span>
</div>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutCommunicationBusy" id="settings-serialTimeoutCommunicationBusy">
<span class="add-on">s</span>
</div>
<span class="help-inline">{{ _('<code>busy</code> protocol support detected')}}</span>
</div>
</div>
<div class="control-group" title="{{ _('Time after which a connection attempt to the printer will be considered as having failed') }}">
<label class="control-label" for="settings-serialTimeoutConnection">{{ _('Connection timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutConnection" id="settings-serialTimeoutConnection">
<span class="add-on">s</span>
</div>
</div>
</div>
<div class="control-group" title="{{ _('Time after which to consider an auto detection attempt to have failed if no successful connection is detected') }}">
<label class="control-label" for="settings-serialTimeoutDetection">{{ _('Autodetection timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutDetection" id="settings-serialTimeoutDetection">
<span class="add-on">s</span>
</div>
</div>
</div>
<div>
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', container: '#settings_serial_timeouts_timeouts .hide' }"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while idle. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
<label class="control-label" for="settings-serialMaxTimeoutsIdle">{{ _('Max. consecutive timeouts while idle') }}</label>
<div class="controls">
<input type="number" min="0" class="input-mini text-right" id="settings-serialMaxTimeoutsIdle" data-bind="value: serial_maxTimeoutsIdle">
<span class="help-block">{{ _('Set to 0 to disable consecutive timeout detection and handling.') }}</span>
</div>
</div>
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while printing. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
<label class="control-label" for="settings-serialMaxTimeoutsPrinting">{{ _('Max. consecutive timeouts while printing') }}</label>
<div class="controls">
<input type="number" min="0" class="input-mini text-right" id="settings-serialMaxTimeoutsPrinting" data-bind="value: serial_maxTimeoutsPrinting">
<span class="help-block">{{ _('Set to 0 to disable consecutive timeout detection and handling.') }}</span>
</div>
</div>
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while a long running command is active. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
<label class="control-label" for="settings-serialMaxTimeoutsLong">{{ _('Max. consecutive timeouts during long running commands') }}</label>
<div class="controls">
<input type="number" min="0" class="input-mini text-right" id="settings-serialMaxTimeoutsLong" data-bind="value: serial_maxTimeoutsLong">
<span class="help-block">{{ _('Set to 0 to disable consecutive timeout detection and handling.') }}</span>
</div>
</div>
</div>
</div>
</fieldset>
</div>
<div id="settings_serial_protocol" class="tab-pane">
<fieldset id="settings_serial_protocol_firmware">
<legend>{{ _('Firmware specific settings') }}</legend>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_firmwareDetection" id="settings-serialFirmwareDetection"> {{ _('Enable automatic firmware detection') }}
<span class="help-block">{% trans %}
If enabled, OctoPrint will try to figure out your printer's firmware automatically and adjust some communication parameters based on that.
If that doesn't work out, or you want more granular control, uncheck this and the parameters in question will become visible for you to adjust.
{% endtrans %}</span>
</label>
</div>
</div>
<div data-bind="visible: !serial_firmwareDetection()">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_sdRelativePath" id="settings-serialSdRelativePath"> {{ _('Select SD files by relative path') }} <span class="label">{{ _('RepRap Firmware') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_sdAlwaysAvailable" id="settings-serialSdAlwaysAvailable"> {{ _('Always assume SD card is present') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_ignoreIdenticalResends" id="settings-serialIgnoreIdenticalResends"> {{ _('Ignore consecutive resend requests for the same line') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_repetierTargetTemp" id="settings-serialRepetierTargetTemp"> {{ _('Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_disableExternalHeatupDetection" id="settings-serialExternalHeatupDetection"> {{ _('Disable detection of external heatups') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_blockWhileDwelling" id="settings-serialBlockWhileDwelling"> {{ _('Actively pause communication during <code>G4</code> dwell command') }} <span class="label">{{ _('Repetier') }}</span>
</label>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Send a checksum with the command')}}</label>
<div class="controls">
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="print" data-bind="checked: serial_sendChecksum" id="settings-serialSendChecksumPrint"> {{ _('When printing') }}
</label>
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="always" data-bind="checked: serial_sendChecksum" id="settings-serialSendChecksumAlways"> {{ _('Always') }} <span class="label">{{ _('Repetier') }}</span>
</label>
<label class="radio">
<input type="radio" name="sendChecksumGroup" value="never" data-bind="checked: serial_sendChecksum" id="settings-serialSendChecksumNever"> {{ _('Never') }}
</label>
</div>
</div>
</div>
<div>
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', container: '#settings_serial_protocol_firmware .hide' }"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_capAutoreportTemp" id="settings-serialCapAutoreportTemp"> {{ _('Support temperature autoreporting by firmware, if detected') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_capBusyProtocol" id="settings-serialCapBusyProtocol"> {{ _('Support <code>busy</code> protocol, if detected') }}
</label>
</div>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_triggerOkForM29" id="settings-serialTriggerOkForM29"> {{ _('Simulate <code>ok</code> for <code>M29</code>') }}
<span class="help-block">{{ _('Most Marlin forks that were derived from Marlin versions < v1.1.0 do not send an acknowledging <code>ok</code> for a <code>M29</code>. Check this if you run into communication stalls following streaming of a file to your printer\'s SD.') }}</span>
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_supportResendsWithoutOk" id="settings-serialSupportResendsWithoutOk"> {{ _('Simulate <code>ok</code> for resend requests') }}
<span class="help-block">{{ _('Some Marlin forks do not send an acknowledging <code>ok</code> with their resend requests. Check this if you run into communication stalls following resend requests due to that.') }}</span>
</label>
</div>
</div>
</div>
</fieldset>
<fieldset id="settings_serial_protocol_finetuning">
<legend>{{ _('Protocol fine tuning') }}</legend>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_waitForStart" id="settings-serialWaitForStart"> {{ _('Wait for <code>start</code> on connect') }}
<span class="help-block">{{ _('Try checking this if you run into connection timeouts due to your printer taking too long to respond to OctoPrint\' handshake attempts on connect.') }}</span>
</label>
</div>
</div>
<div>
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', container: '#settings_serial_protocol_finetuning .hide' }"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<div class="control-group" title="{{ _('Command to send to the firmware on first handshake attempt.') }}">
<label class="control-label" for="settings-serialHelloCommand">{{ _('"Hello" command') }}</label>
<div class="controls">
<input type="text" class="input-block-level" id="settings-serialHelloCommand" data-bind="value: serial_helloCommand">
<span class="help-inline">{{ _('Use this to specify a different command than the default <code>M110</code> to send to the printer on initial connection to trigger a communication handshake.') }}</span>
</div>
</div>
<div class="control-group" title="{{ _('Commands that are know to run long and hence should suppress communication timeouts from being triggered.') }}">
<label class="control-label" for="settings-serialLongRunningCommands">{{ _('Long running commands') }}</label>
<div class="controls">
<input type="text" class="input-block-level" id="settings-serialLongRunningCommands" data-bind="value: serial_longRunningCommands">
<span class="help-inline">{{ _('Use this to specify the commands known to take a long time to complete without output from your printer and hence might cause timeout issues. Just the G or M code, comma separated.') }}</span>
</div>
</div>
<div class="control-group" title="{{ _('Commands that always require a line number and checksum to be sent with them.') }}">
<label class="control-label" for="settings-checksumRequiringCommands">{{ _('Commands that always require a checksum') }}</label>
<div class="controls">
<input type="text" class="input-block-level" id="settings-checksumRequiringCommands" data-bind="value: serial_checksumRequiringCommands">
<span class="help-inline">{{ _('Use this to specify which commands <strong>always</strong> need to be sent with a checksum. Comma separated list.') }}</span>
</div>
</div>
</div>
</div>
</fieldset>
</div>
<div id="settings_serial_behaviour" class="tab-pane">
<fieldset>
<legend>{{ _('Error handling') }}</legend>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_disconnectOnErrors" id="settings-serialDisconnectOnErrors"> {{ _('Not only cancel ongoing prints but also disconnect on unhandled errors from the firmware.') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_ignoreErrorsFromFirmware" id="settings-serialIgnoreErrorsFromFirmware"> {{ _('Ignore any unhandled errors from the firmware. Only use this if your firmware sends stuff prefixed with "Error" that is not an actual error. Might mask printer issues, be careful!') }} <span class="label label-important">{{ _('Warning') }}</span>
</label>
</div>
</div>
</fieldset>
<fieldset>
<legend>{{ _('Event based position logging') }}</legend>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_logPositionOnPause" id="settings-serialLogPositionOnPause"> {{ _('Log position on pause') }} <span class="label label-important">{{ _('Warning') }}</span>
<span class="help-block">{{ _('If you disable this, the <code>pause_position</code> placeholders in your pause/resume GCODE scripts will stay unpopulated! However, pausing speed might improve slightly.') }}</span>
</label>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_logPositionOnCancel" id="settings-serialLogPositionOnCancel"> {{ _('Log position on cancel') }} <span class="label label-important">{{ _('Warning') }}</span>
<span class="help-block">{{ _('If you disable this, the <code>cancel_position</code> placeholders in your cancel GCODE script and the corresponding data in the print recovery data will stay unpopulated! However, cancelling speed might improve slightly.') }}</span>
</label>
</div>
</fieldset>
</div>
</div>
</form>
@@ -4,7 +4,7 @@
<label class="control-label">{{ _('Graph cutoff') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" class="input-mini text-right" data-bind="value: temperature_cutoff">
<input type="number" min="1" class="input-mini text-right" data-bind="value: temperature_cutoff">
<span class="add-on">min</span>
</div>
<span class="help-block">{{ _('Needs a restart of OctoPrint to become active.') }}</span>
@@ -6,18 +6,20 @@
<h4>{{ _('On your printer\'s safety') }}</h4>
<i class="fa fa-exclamation-triangle fa-4x fa-pull-left text-error"></i>
<p>{% trans %}
Even with OctoPrint attached you should <strong class="text-error">never leave
your printer run completely unattended</strong>. The electronics in our consumer printers can and sometimes sadly do
catch fire, so stay or have someone else stay close enough to physically intervene in case of such catastrophic
failure.
your printer running completely unattended</strong>. The electronics in our consumer printers can and
sometimes sadly do catch fire, so stay or have someone else stay close enough to physically intervene
in case of such catastrophic failure.
{% endtrans %}</p>
<h4>{{ _('If you enjoy OctoPrint...') }}</h4>
<p>{% trans url='http://octoprint.org/support-octoprint/' %}
<span style="display: inline-block; float: left; font-size: 4em; margin-right: .3em"><img src="{{ url_for('static', filename='img/tentacle-56x56.png') }}"></span>
<p>{% trans url='https://octoprint.org/support-octoprint/?utm_source=octoprint&utm_medium=first_run_wizard' %}
Please consider to <strong><a href="{{ url }}" target="_blank">support OctoPrint's ongoing development</a></strong>,
which is only possible thanks to funding by users like you! You can also find this link in the "About" dialog.
which can only continue with funding by users like you! You can also find this link in the "About" dialog.<br>
<strong>Thank you!</strong>
{% endtrans %}</p>
@@ -4,6 +4,6 @@
Thank you for installing OctoPrint!
{% endtrans %}</p>
<p>{% trans %}
This wizard will guide you through the final steps to get your OctoPrint instance all setup and ready to go. We'll
This wizard will guide you through the final steps to get your OctoPrint instance all set up and ready to go. We'll
get you printing in no time!
{% endtrans %}</p>
+1 -1
View File
@@ -115,7 +115,7 @@
<li><small>{{ _('OctoPrint') }} <span class="version">{{ display_version|e }}</span></small></li>
</ul>
<ul id="footer_links" class="pull-right">
<li><a href="http://octoprint.org" target="_blank" rel="noreferrer noopener"><i class="fa fa-home"></i> {{ _('Homepage') }}</a></li>
<li><a href="https://octoprint.org" target="_blank" rel="noreferrer noopener"><i class="fa fa-home"></i> {{ _('Homepage') }}</a></li>
<li><a href="https://github.com/foosel/OctoPrint/" target="_blank" rel="noreferrer noopener"><i class="fa fa-github"></i> {{ _('Source') }}</a></li>
<li><a href="http://docs.octoprint.org" target="_blank" rel="noreferrer noopener"><i class="fa fa-book"></i> {{ _('Docs') }}</a></li>
<li><a href="https://github.com/foosel/OctoPrint/issues" target="_blank" rel="noreferrer noopener"><i class="fa fa-flag"></i> {{ _('Issues') }}</a></li>
@@ -0,0 +1,5 @@
<div class="refresh-trigger accordion-heading-button btn-group">
<a href="#" data-bind="click: function() { $root.requestData(); }" title="{{ _('Refresh connection options') }}">
<i class="fa fa-refresh"></i>
</a>
</div>
@@ -27,7 +27,7 @@
<div data-bind="visible: !sharedNozzle()" style="display: none">
<div class="control-group">
<div class="controls">
{{ _('Please specify the nozzle offsets of the extruders relative to the first nozzle T0.') }}
{{ _('Please specify the nozzle offsets of the extruders relative to the first nozzle T0 <strong>if you haven\'t already done so in your firmware</strong>. Otherwise leave them at (0,0).') }}
</div>
</div>
@@ -3,3 +3,8 @@
the use of a centralized plugin version blacklist to automatically disable such plugins before they can interfere
with normal operation.
{% endtrans %}</p>
<p>{% trans url="https://plugins.octoprint.org/blacklist/" %}
By default, OctoPrint will use the blacklist hosted at <code>plugins.octoprint.org/blacklist.json</code> which you
can also take a look at in a more human readable format <a href="{{ url }}" target="_blank">here</a>.
{% endtrans %}</p>
+1 -1
View File
@@ -73,7 +73,7 @@
<div class="distance">
<div class="btn-group" data-toggle="buttons-radio" id="jog_distance">
<!-- ko foreach: distances -->
<button type="button" class="btn distance" data-bind="text: $data, click: function() { $root.distance($data) }, css: { active: $root.distance() === $data }, attr: { id: 'control-distance' + $root.stripDistanceDecimal($data) }"></button>
<button type="button" class="btn distance" data-bind="enable: $root.isOperational() && !$root.isPrinting(), text: $data, click: function() { $root.distance($data) }, css: { active: $root.distance() === $data }, attr: { id: 'control-distance' + $root.stripDistanceDecimal($data) }"></button>
<!-- /ko -->
</div>
</div>
+1 -1
View File
@@ -1,5 +1,5 @@
<div class="terminal">
<pre id="terminal-output" class="pre-scrollable pre-output" data-bind="foreach: displayedLines, visible: fancyFunctionality(), click: function(){ gotoTerminalCommand(); }"><span data-bind="text: line, css: {muted: type == 'filtered' || type == 'cut'}"></span></pre>
<pre id="terminal-output" class="pre-scrollable pre-output" data-bind="foreach: displayedLines, visible: fancyFunctionality(), click: function(){ gotoTerminalCommand(); }, event: { scroll: terminalScrollEvent }"><span data-bind="text: line, css: {muted: type == 'filtered' || type == 'cut'}"></span></pre>
<pre id="terminal-output-lowfi" style="display: none" class="pre-scrollable" data-bind="text: plainLogOutput, visible: !fancyFunctionality()"></pre>
<div id="terminal-sendpanel" style="display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.CONTROL)">
<div class="input-block-level input-append">
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff. Show more