Merge branch 'devel' into dev/commRefactoringNG
# Conflicts: # src/octoprint/plugins/virtual_printer/virtual.py # src/octoprint/printer/standard.py
This commit is contained in:
commit
0768e3e72b
112 files changed
+5703
-3610
No files matched your search
+7
-7
@@ -18,16 +18,16 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.11
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.12
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev
|
||||
fix/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev
|
||||
improve/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev
|
||||
maintenance 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
|
||||
fix/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
|
||||
improve/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.10rc5
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.11rc4
|
||||
# so is regressionfix/...
|
||||
staging/maintenance 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b pep440-dev
|
||||
regressionfix/.* 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b pep440-dev
|
||||
staging/maintenance 1.3.11rc4 af3285854995fb5b910fd2ce869e26c02d57bbc2 pep440-dev
|
||||
regressionfix/.* 1.3.11rc4 af3285854995fb5b910fd2ce869e26c02d57bbc2 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
|
||||
@@ -101,6 +101,10 @@ date of first contribution):
|
||||
* [Matthias Urlichs](https://github.com/smurfix)
|
||||
* [Daniel Joyce](https://github.com/DanielJoyce)
|
||||
* [Andy Qua](https://github.com/AndyQ)
|
||||
* [Fabio Santos](https://github.com/Fabi0San)
|
||||
* [Jack Wilsdon](https://github.com/jackwilsdon)
|
||||
* [Ryan Finnie](https://github.com/rfinnie)
|
||||
* [Timur Duehr](https://github.com/tduehr)
|
||||
|
||||
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
|
||||
|
||||
+148
@@ -1,5 +1,153 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.3.11 (2019-05-14)
|
||||
|
||||
### Heads-up: 1.3.11 unbundles the Cura plugin
|
||||
|
||||
If you rely on the Cura Plugin for your workflow that so far was bundled with OctoPrint, be sure to install the [Cura Legacy plugin](https://github.com/OctoPrint/OctoPrint-CuraLegacy) that's now also [available on the plugin repository](https://plugins.octoprint.org/plugins/curalegacy/).
|
||||
|
||||
Once installed the Cura Legacy plugin will import the settings and profiles from the former bundled Cura plugin automatically on first start.
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#1938](https://github.com/foosel/OctoPrint/issues/1938) - Allow slicing parallel to printing on machines with more than one core.
|
||||
* [#2462](https://github.com/foosel/OctoPrint/issues/2462) - Also scan and process watched folder on startup, not just during runtime.
|
||||
* [#2900](https://github.com/foosel/OctoPrint/pull/2900) - Add new hook `octoprint.printer.sdcardupload` to allow plugins to override default way to upload files to the printer's SD card.
|
||||
* [#2904](https://github.com/foosel/OctoPrint/issues/2904) - Added new command line switches `-4` and `-6` to restrict binding of the server to IPv4 or v6 respectively.
|
||||
* [#2905](https://github.com/foosel/OctoPrint/issues/2905) - Use maximum of communication & temperature timeout as serial timeout to avoid issues if the user has set a longer temperature reporting interval than (busy) communication timeout.
|
||||
* [#2945](https://github.com/foosel/OctoPrint/issues/2945) - Adjust default regex for filtering temperature requests and responses to not filter some `M115` responses as well. New regex is `(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+((P|B|N)\d+\s+)*)?(B|T\d*):\d+)`. If you modified your terminal filters you'll have to update that manually.
|
||||
* [#2947](https://github.com/foosel/OctoPrint/issues/2947) - Printer safety check plugin: Disable warning for Monoprice Select Mini V2 with firmware v4.1+.
|
||||
* [#2953](https://github.com/foosel/OctoPrint/issues/2953) - GCODE Viewer: Bring back the total number of printed layers.
|
||||
* [#2962](https://github.com/foosel/OctoPrint/issues/2962) - Logging: deletion confirmation and bulk delete for log file management.
|
||||
* [#2965](https://github.com/foosel/OctoPrint/issues/2965) - Add new hook `octoprint.events.register_custom_events` to allow plugins to cleanly add custom events by plugins.
|
||||
* [#2970](https://github.com/foosel/OctoPrint/issues/2970) - Add configurable list of commands that should never be sent to the printer, and a configurable list of commands on which OctoPrint should pause the current print job. Allows more granular configuration of behaviour of `M0`, `M1` and `M25`.
|
||||
* [#2974](https://github.com/foosel/OctoPrint/issues/2974) - Dedicated checkboxes to enable/disable webcam & timelapse functionality instead of relying on empty URLs.
|
||||
* [#2976](https://github.com/foosel/OctoPrint/issues/2976) - Correctly identify v6 representations of v4 networks for auto login. Also correctly identify `::1` as local network.
|
||||
* [#2978](https://github.com/foosel/OctoPrint/pull/2978) - Use module name instead of plugin identifier when loading plugins from entry points. Also load bundled plugins under `octoprint.plugins.*` instead of their identifier.
|
||||
* [#2982](https://github.com/foosel/OctoPrint/issues/2982) - Log user activity of who started/paused/resumed/cancelled the current print. Include `owner` of a print job in event data and log.
|
||||
* [#2983](https://github.com/foosel/OctoPrint/issues/2983) - Add clear button to filter box in file list.
|
||||
* [#2986](https://github.com/foosel/OctoPrint/pull/2986) - Forcelogin plugin: Make login page responsive.
|
||||
* [#2988](https://github.com/foosel/OctoPrint/issues/2988) - Add `--disable-pip-version-check` to pip calls to stop pip's tendency to confuse people with it's update nag messages.
|
||||
* [#2997](https://github.com/foosel/OctoPrint/issues/2997) - Forcelogin plugin: Accept authentication through API key and/or authorization headers.
|
||||
* [#3010](https://github.com/foosel/OctoPrint/pull/3010) - Add usage information for all folders to the API.
|
||||
* [#3014](https://github.com/foosel/OctoPrint/issues/3014) - Hardening against corrupt language packs.
|
||||
* [#3023](https://github.com/foosel/OctoPrint/issues/3023) - Hardening against corrupt preemptive caching configurations.
|
||||
* [#3030](https://github.com/foosel/OctoPrint/issues/3030) - Backup plugin: Change name of generated backup file to have an `octoprint-` prefix. See also [#3039](https://github.com/foosel/OctoPrint/pull/3039).
|
||||
* [#3033](https://github.com/foosel/OctoPrint/issues/3033) - Open serial port in exclusive mode. See also [#3036](https://github.com/foosel/OctoPrint/pull/3036).
|
||||
* [#3038](https://github.com/foosel/OctoPrint/issues/3038) - Detect Klipper firmware and adjust serial communication settings accordingly.
|
||||
* [#3040](https://github.com/foosel/OctoPrint/issues/3040) - Add setting to disable fuzzy estimation display in the UI.
|
||||
* [#3049](https://github.com/foosel/OctoPrint/issues/3049) - Workaround for broken PEP440 non-compliant Python version numbers under Debian. See also [#3054](https://github.com/foosel/OctoPrint/pull/3054).
|
||||
* [#3051](https://github.com/foosel/OctoPrint/pull/3051) - Always show unfuzzy total print time and print left in a tooltip.
|
||||
* [#3055](https://github.com/foosel/OctoPrint/pull/3055) - GCODE Viewer: Add ability to preview the current layer to be drawn.
|
||||
* [#3057](https://github.com/foosel/OctoPrint/issues/3057) - Performance improvements in file management operations & more aggressive cleanup of stale metadata.
|
||||
* [#3066](https://github.com/foosel/OctoPrint/pull/3066) - Docs: Add missing documentation about state in `jobs` endpoint on API.
|
||||
* [#3072](https://github.com/foosel/OctoPrint/pull/3072) - Hide temperature tab for machines with neither heated bed nor extruders.
|
||||
* [#3073](https://github.com/foosel/OctoPrint/pull/3073) - Hide tool section in "Control" tab for machines with no extruders.
|
||||
* [#3074](https://github.com/foosel/OctoPrint/issues/3074) - Updated several dependencies to newer versions.
|
||||
* Add elapsed time and reason for failure to `PrintFailed` event.
|
||||
* Add `trigger_event` parameter to `Settings.save` and `PluginSettings.save` to trigger `SettingsUpdated` event on save of settings.
|
||||
* Simplify configuration change handling of wizards.
|
||||
* Minimum Python version is now 2.7.9.
|
||||
* Create a backup of working `config.yaml` after successful startup.
|
||||
* Detect incomplete startups and set safe mode flag for next startup.
|
||||
* Always show actual temperature as received from printer instead of "off" for very low temperatures. That way people will hopefully no longer blame OctoPrint for MINTEMP errors triggered by their firmware because it "can't handle temperatures under 10°C".
|
||||
* Add full version string `OctoPrint <version>` to API.
|
||||
* Add systemd unit file.
|
||||
* Deprecate appkey API in favor of new bundled Application Keys Plugin. AFAIK was never used by anyone anyhow.
|
||||
* Take bundle status into account for plugin sorting, bundled plugins should always win before not bundled plugins if no sorting key is provided.
|
||||
* Load generic templates after JavaScript assets, making it possible to reference already loaded libraries in any injected generic templates.
|
||||
* Hardening against callback errors in decorators on default view.
|
||||
* Unbundled the Cura plugin. It lives on as "Cura Legacy" at [OctoPrint/OctoPrint-CuraLegacy](https://github.com/OctoPrint/OctoPrint-CuraLegacy) and will also be available on the plugin repository.
|
||||
* Hardening against invalid SD status reports.
|
||||
* Cleanup now obsolete `metadata.yaml` files.
|
||||
* Use `monotonic_time` for relative times everywhere.
|
||||
* Support for heated chamber firmware capabilities.
|
||||
* Remove `UI_API_KEY` and API disabling. With the inclusion of the ForceLogin plugin that doesn't serve a real purpose anymore in most cases, and it was only ever more of a rate limiting feature than an actual security measure anyhow. Plus it lead to a ton of false security alarms.
|
||||
* More resilience against broken configurations.
|
||||
* More resilience against platform startup issues during environment detection.
|
||||
* Don't confuse users with current `pip`'s "Python 2.7 is EOL" messages
|
||||
* Define empty `UI_API_KEY` for backwards compatibility with third party plugins
|
||||
* Add config flag `server.ignoredIncompleteStartup` to override incomplete startup detection
|
||||
* Hardening against errors triggered during print time estimation
|
||||
* Introduce setting to disable exclusive claim on serial port. There might be issues with this out there in the field, so having the option to disable it is a good thing.
|
||||
* Docs: Improve docs of connection API to avoid issues as encountered in [#3043](https://github.com/foosel/OctoPrint/issues/3043).
|
||||
* Action Command Prompt plugin: Set `M876` as default command as discussed in [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982).
|
||||
* Action Command Prompt plugin: Add `M876` to `EMERGENCY_PARSER` compliant commands, if configured accordingly. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982).
|
||||
* Action Command Prompt plugin: Signal support for action command prompts to firmware via `M876 P1`, if configured accordingly. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982).
|
||||
* Action Command Prompt plugin: Properly handle `PROMPT_SUPPORT` capability report from firmware and configure action command prompt support accordingly. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982).
|
||||
* Error Tracking plugin: New plugin utilizing [sentry.io](https://sentry.io) to track any kind of errors thrown in either backend or the default UI. Will ship disabled by default, has to be enabled by the user. Release Candidates will prompt users to enable it in order to improve on error detection during RC phase.
|
||||
* Error Tracking: Severely restrict what gets tracked:
|
||||
* we are only interested in handled core exceptions or unhandled exceptions
|
||||
* we are not interested at all in `SerialException`
|
||||
* Error Tracking: Further restriction of what gets tracked
|
||||
* Forcelogin plugin: Set sorting key to 0 to increase likelihood of coming before alternative UIs.
|
||||
* Forcelogin plugin: Add favicon meta tags.
|
||||
* Plugin Manager plugin, Softwareupdate plugin: Use scrollables instead of pagination.
|
||||
* Printer Safety Check plugin: Add version restriction to Anycubic check.
|
||||
* Tracking plugin: Add elapsed time and reason for failure to `print_failed` event.
|
||||
* Tracking plugin: Add elapsed time to `print_cancelled` event.
|
||||
* Tracking plugin: Track firmware/communication errors.
|
||||
* Tracking plugin: Track printer safety warnings.
|
||||
* Tracking plugin: Track uptime of OctoPrint in `ping` event.
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* [#1881](https://github.com/foosel/OctoPrint/issues/1881) - Another attempt at fixing the hard to intentionally reproduce issue where all API endpoints start returning `403` responses. Caching headers have been adjusted and API key handling has been changed, which might fix things.
|
||||
* [#2859](https://github.com/foosel/OctoPrint/issues/2859) - Fix for used port and baudrate to not be properly reflected on the UI.
|
||||
* [#2916](https://github.com/foosel/OctoPrint/issues/2916) - Possible workaround for a rare issue with the bundled Tornado dependency when running OctoPrint under Windows.
|
||||
* [#2954](https://github.com/foosel/OctoPrint/issues/2954) - Backup plugin: Fix an issue with calculation of available free space.
|
||||
* [#2955](https://github.com/foosel/OctoPrint/issues/2955) - Fix handling of `action:resume` or `action:resumed` received during `PAUSING` and handling of `action:pause` or `action:paused` received during `RESUMING`. Fix `PAUSING` state not allowing a resume to proceed. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982).
|
||||
* [#2959](https://github.com/foosel/OctoPrint/issues/2959) - Enforce max height smaller than available viewport for notifications so that they cannot scroll out of the screen.
|
||||
* [#2967](https://github.com/foosel/OctoPrint/issues/2967) - Tracking plugin: Fix exception caused on printer events when tracking is disabled and no UUID is thus set.
|
||||
* [#2971](https://github.com/foosel/OctoPrint/issues/2971) - Forcelogin plugin: Fix "remember me" not working as advertised. See also [#2973](https://github.com/foosel/OctoPrint/pull/2973).
|
||||
* [#2992](https://github.com/foosel/OctoPrint/issues/2992) - Backup plugin: Use `shutil.move` instead of `os.rename` and thus avoid issues with certain filesystem configurations. See also [#2993](https://github.com/foosel/OctoPrint/pull/2993).
|
||||
* [#2996](https://github.com/foosel/OctoPrint/issues/2996) - Use non-blocking writes on serial communication to avoid `select` blocking issues under certain conditions. See also [#3004](https://github.com/foosel/OctoPrint/pull/3004).
|
||||
* [#3001](https://github.com/foosel/OctoPrint/issues/3001) - Fix a race condition in SD printing detection.
|
||||
* [#3012](https://github.com/foosel/OctoPrint/issues/3012) - Fix a unicode vs ASCII bug in translating plugins.
|
||||
* [#3024](https://github.com/foosel/OctoPrint/issues/3024) - Fix inconsistent behaviour of CORS support on the API regarding static routes and the socket.
|
||||
* [#3029](https://github.com/foosel/OctoPrint/issues/3029) & [#3045](https://github.com/foosel/OctoPrint/pull/3045) & [#3061](https://github.com/foosel/OctoPrint/issues/3061) - Fix issues in the German translation
|
||||
* [#3053](https://github.com/foosel/OctoPrint/pull/3053) - GCODE Viewer: Fix an issue with multi extruder files where only a higher extruder index is actually used and all prior ones are undefined.
|
||||
* [#3080](https://github.com/foosel/OctoPrint/issues/3080) - Virtual Printer plugin: Fix tracking of negative movements and homing.
|
||||
* [#3071](https://github.com/foosel/OctoPrint/issues/3071) - Application Keys plugin: Fix appkeys not working when access control is disabled.
|
||||
* [#3088](https://github.com/foosel/OctoPrint/issues/3088) (regression) - Fix 500 error on index rendering in case of plugins that use unicode in plugin vars.
|
||||
* [#3089](https://github.com/foosel/OctoPrint/issues/3089) (regression) - Fix missing `_chamberTemp` definition
|
||||
* [#3090](https://github.com/foosel/OctoPrint/issues/3090) (regression) - Fix missing method causing an exception on `/api/printer/tool` endpoint
|
||||
* [#3091](https://github.com/foosel/OctoPrint/issues/3091) (regression) - Printer Safety Check: Fix unicode errors in certain communication scenarios.
|
||||
* [#3092](https://github.com/foosel/OctoPrint/issues/3092) - Fix invalid tool parameter detection on `/api/printer/tool` endpoint.
|
||||
* [#3098](https://github.com/foosel/OctoPrint/issues/3098) - Backup: Exclude temporary timelapse files as well if timelapses are excluded from backup.
|
||||
* [#3105](https://github.com/foosel/OctoPrint/issues/3105) (regression) - Virtual printer: Fix an encoding issue
|
||||
* [#3108](https://github.com/foosel/OctoPrint/issues/3108) (regression) - Fix bug in port detection
|
||||
* [#3111](https://github.com/foosel/OctoPrint/issues/3111) (regression) - Refresh port list after disconnect to detect vanishing ports
|
||||
* [#3115](https://github.com/foosel/OctoPrint/issues/3115) (regression) - Fix extra newlines in `serial.log` and empty lines on terminal
|
||||
* [#3116](https://github.com/foosel/OctoPrint/issues/3116) - Fix potential division by zero
|
||||
* Fix a typo in an error message during startup.
|
||||
* `paused` action command must not trigger *any* local processing. See also [MarlinFirmware/Marlin#12982](https://github.com/MarlinFirmware/Marlin/pull/12982).
|
||||
* Only use page size from local storage in `ItemListHelper` if configured.
|
||||
* Fix caching headers on main view.
|
||||
* Fix missing default value for `self._errorValue` in comm layer.
|
||||
* Don't read return code on async system commands, it won't work.
|
||||
* Fix wrong textual representation of `STARTING` state
|
||||
* Fix some potential encoding errors in the comm layer
|
||||
* Fix for the file list in the UI not getting refreshed after an SD list refresh from the printer.
|
||||
* Docs: Fix documentation for firmware info & capability plugin hooks.
|
||||
* Docs: Fix a formatting issue in the event docs, making it seem like events were deprecated when it was only payload entries that are deprecated.
|
||||
* Forcelogin plugin: Never handle the UI if ACL is disabled.
|
||||
* Tracking plugin: Fix tracking not starting fully if enabled during runtime.
|
||||
* Tracking plugin: Fix handling of missing print time. See also [#3063](https://github.com/foosel/OctoPrint/issues/3063).
|
||||
|
||||
### Special thanks to all the contributors!
|
||||
|
||||
Special thanks to everyone who contributed to this release, especially [@agrif](https://github.com/agrif), [@akraus53](https://github.com/akraus53), [@AndyQ](https://github.com/AndyQ), [@CapnBry](https://github.com/CapnBry), [@DanielJoyce](https://github.com/DanielJoyce), [@devildant](https://github.com/devildant), [@Fabi0San](https://github.com/Fabi0San), [@fake-name](https://github.com/fake-name), [@fieldOfView](https://github.com/fieldOfView), [@gloomyandy](https://github.com/gloomyandy), [@HarlemSquirrel](https://github.com/HarlemSquirrel), [@hgross](https://github.com/hgross), [@jubaleth](https://github.com/foosel/OctoPrint/commits?author=jubaleth), [@melgish](https://github.com/melgish), [@rgriebl](https://github.com/rgriebl) and [@tedder](https://github.com/tedder) for their PRs.
|
||||
|
||||
### More information
|
||||
|
||||
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.10...1.3.11)
|
||||
* Release Candidates:
|
||||
* [1.3.11rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.11rc1)
|
||||
* [1.3.11rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.11rc2)
|
||||
* [1.3.11rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.11rc3)
|
||||
* A big **Thank you!** to everyone who reported back on these release candidates this time: [@arhi](https://github.com/arhi), [@b-morgan](https://github.com/b-morgan), [@CRCinAU](https://github.com/CRCinAU), [@devildant](https://github.com/devildant), [@evanquinnalaska](https://github.com/evanquinnalaska), [@FormerLurker](https://github.com/FormerLurker), [@gege2b](https://github.com/gege2b), [@isbric](https://github.com/isbric), [@JohnOCFII](https://github.com/JohnOCFII), [@kazibole](https://github.com/kazibole), [@nionio6915](https://github.com/nionio6915), [@reloxx13](https://github.com/reloxx13), [@schnello](https://github.com/schnello), [@trunzoc](https://github.com/trunzoc), [@vfrdirk](https://github.com/vfrdirk) & [@zeroflow](https://github.com/zeroflow)
|
||||
|
||||
## 1.3.10 (2018-12-10)
|
||||
|
||||
### Heads-up for plugin authors regarding the `sarge` dependency
|
||||
|
||||
@@ -142,5 +142,8 @@ be edited from OctoPrint's settings dialog.
|
||||
|
||||
## Special Thanks
|
||||
|
||||
Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/).
|
||||
Profiling is done with the help of [PyVmMonitor](http://www.pyvmmonitor.com).
|
||||
Cross-browser testing services are kindly provided by [BrowserStack](https://www.browserstack.com/).
|
||||
|
||||
Profiling is done with the help of [PyVmMonitor](https://www.pyvmmonitor.com).
|
||||
|
||||
Error tracking is powered and sponsored by [Sentry](https://sentry.io).
|
||||
+9
-9
@@ -9,6 +9,7 @@ thanks to everyone who contributed!
|
||||
* Andre Bubel
|
||||
* Andrew Moorby
|
||||
* Arnljot Arntsen
|
||||
* Bjorn Breckenridge
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Christian Petropolis
|
||||
@@ -16,42 +17,41 @@ thanks to everyone who contributed!
|
||||
* COLLE+McVOY
|
||||
* D Brian Kimmel
|
||||
* DeltaMaker 3D Printers
|
||||
* Dorian Gray
|
||||
* E3D BigBox
|
||||
* Eric Betts
|
||||
* Eric Slape
|
||||
* Ernesto Martinez
|
||||
* Frank Sander
|
||||
* Franziska Kunsmann
|
||||
* George Robles
|
||||
* Jared Go
|
||||
* jean-claude migneault
|
||||
* Jeff Renfer
|
||||
* Jefferson Hunt
|
||||
* Jeremiah Avery
|
||||
* Joseph Payne
|
||||
* Josh Daniels
|
||||
* Joshua Wills
|
||||
* Justin Kaufman
|
||||
* Kaile Riser
|
||||
* Kale Stedman
|
||||
* Kazuhiro Ogura
|
||||
* LA 3D Printer Repair
|
||||
* Lewis Newby
|
||||
* LulzBot®
|
||||
* Makespace Madrid
|
||||
* Mark Walker
|
||||
* Michael Aumock
|
||||
* Miles Flavel
|
||||
* Mosaic Manufacturing
|
||||
* OMER MEHMET SUTAS
|
||||
* Patrick McGinnis
|
||||
* Prof Yuh Wen Chen
|
||||
* Randy C. Will
|
||||
* Robert Gusek
|
||||
* Roger Strolz
|
||||
* Samer Najia
|
||||
* Shawn Lewis
|
||||
* Simon Hallam
|
||||
* Stefan Krister
|
||||
* Sven Mueller
|
||||
* Thomas Hatley
|
||||
* Timothy D Hoogland
|
||||
* TEVO 3D Printers
|
||||
* Trent Shumay
|
||||
* Ulrich Kempken
|
||||
|
||||
and 1446 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 1544 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
@@ -37,7 +37,6 @@
|
||||
* [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3
|
||||
* [chainmap](https://bitbucket.org/jeunice/chainmap): Python
|
||||
* [Click](http://click.pocoo.org/): BSD
|
||||
* [dateutil](https://dateutil.readthedocs.io/): BSD
|
||||
* [emoji](https://github.com/carpedm20/emoji/): BSD
|
||||
* [feedparser](https://github.com/kurtmckee/feedparser): BSD
|
||||
* [Flask](http://flask.pocoo.org/): BSD
|
||||
|
||||
+21
-10
@@ -11,9 +11,9 @@ General information
|
||||
Authorization
|
||||
=============
|
||||
|
||||
OctoPrint's API expects an API key to be supplied with each request. This API key can be either the globally
|
||||
configured one, a user specific one if "Access Control" is enabled or an app and user specific one as generated
|
||||
by the authorization workflow implemented by the bundled :ref:`Application Keys Plugin <sec-bundledplugins-appkeys>` (since 1.3.10).
|
||||
If :ref:`Access Control <sec-features-access_control>` is enabled OctoPrint's API expects an API key to be supplied with each request. This API
|
||||
key can be either the globally configured one, a user specific one or an app and user specific one as generated by the
|
||||
authorization workflow implemented by the bundled :ref:`Application Keys Plugin <sec-bundledplugins-appkeys>` (since 1.3.10).
|
||||
|
||||
Clients are advised to implement the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` first and
|
||||
fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used.
|
||||
@@ -26,8 +26,6 @@ The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`403`.
|
||||
|
||||
For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g.
|
||||
|
||||
.. sourcecode:: http
|
||||
@@ -37,6 +35,24 @@ For testing purposes it is also possible to supply the API key via a query param
|
||||
|
||||
Please be advised that clients should use the header field variant if at all possible.
|
||||
|
||||
If the key is missing or invalid, OctoPrint will treat the request as it would any unauthenticated anonymous request to the endpoint.
|
||||
Consequently, if the bundled :ref:`ForceLogin plugin <sec-bundledplugins-forcelogin>` is active (which is the default), that means
|
||||
that any requests without or with an invalid API key targeting other API endpoints than :ref:`Login <sec-api-general-login>`
|
||||
will be denied with a :http:statuscode:`403`.
|
||||
|
||||
.. warning::
|
||||
|
||||
If :ref:`Access Control <sec-features-access_control>` is disabled, OctoPrint will treat any unauthenticated anonymous requests and thus also requests
|
||||
with an invalid or outright missing API key as requests with full admin rights!
|
||||
|
||||
.. note::
|
||||
|
||||
The API key requirements changed in 1.3.11. Up to that version, even if Access Control was disabled, all requests needed to
|
||||
be supplied with an API Key. To make the webinterface work under these circumstances, an unauthenticated anonymous API key was injected into the
|
||||
HTML page and also available on the :ref:`Push API <sec-api-push>`. The presence and ready availability of this unauthenticated
|
||||
anonymous "UI API key" caused confusion and false alarm among users and didn't contribute to the security of the platform in a
|
||||
meaningful way, so it was finally abandoned in 1.3.11.
|
||||
|
||||
.. _fig-api-general-globalapikey:
|
||||
.. figure:: ../images/settings-global-api-key.png
|
||||
:align: center
|
||||
@@ -58,11 +74,6 @@ Please be advised that clients should use the header field variant if at all pos
|
||||
|
||||
The API key options in the "Change password" dialog. Users can generate and revoke their custom API key here.
|
||||
|
||||
.. note::
|
||||
OctoPrint's web interface uses a custom API key that is freshly generated on every server start. This key is not
|
||||
intended to be used by any other client and would not be very useful in any case, since it basically represents
|
||||
a completely anonymous client.
|
||||
|
||||
.. _sec-api-general-contenttype:
|
||||
|
||||
Content Type
|
||||
|
||||
+156
-3
@@ -22,6 +22,11 @@ Bed
|
||||
corresponding resource returns temperature information including an optional history. Note that Bed commands
|
||||
are only available if the currently selected printer profile has a heated bed.
|
||||
See :ref:`sec-api-printer-bedcommand`.
|
||||
Chamber
|
||||
Chamber commands allow setting the temperature and temperature offset for the printer's heated chamber. Querying
|
||||
the corresponding resource returns temperature information including an option history. Note that Chamber commands
|
||||
are only available if the currently selected printer profile has a heated chamber.
|
||||
See :ref:`sec-api-printer-chambercommand`.
|
||||
SD card
|
||||
SD commands allow initialization, refresh and release of the printer's SD card (if available). Querying the
|
||||
corresponding resource returns the current SD card state.
|
||||
@@ -623,12 +628,12 @@ Issue a bed command
|
||||
are:
|
||||
|
||||
target
|
||||
Sets the given target temperature on the printer's tools. Additional parameters:
|
||||
Sets the given target temperature on the printer's bed. Additional parameters:
|
||||
|
||||
* ``target``: Target temperature to set.
|
||||
|
||||
offset
|
||||
Sets the given temperature offset on the printer's tools. Additional parameters:
|
||||
Sets the given temperature offset on the printer's bed. Additional parameters:
|
||||
|
||||
* ``offset``: Offset to set.
|
||||
|
||||
@@ -710,7 +715,7 @@ Retrieve the current bed state
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
.. note::
|
||||
If you want both tool and bed temperature information at the same time, take a look at
|
||||
If you want tool, bed and chamber temperature information at the same time, take a look at
|
||||
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
|
||||
|
||||
**Example**
|
||||
@@ -760,6 +765,154 @@ Retrieve the current bed state
|
||||
:statuscode 409: If the printer is not operational or the selected printer profile
|
||||
does not have a heated bed.
|
||||
|
||||
.. _sec-api-printer-chambercommand:
|
||||
|
||||
Issue a chamber command
|
||||
=======================
|
||||
|
||||
.. http:post:: /api/printer/bed
|
||||
|
||||
Chamber commands allow setting the temperature and temperature offsets for the printer's heated chamber. Available commands
|
||||
are:
|
||||
|
||||
target
|
||||
Sets the given target temperature on the printer's chamber. Additional parameters:
|
||||
|
||||
* ``target``: Target temperature to set.
|
||||
|
||||
offset
|
||||
Sets the given temperature offset on the printer's chamber. Additional parameters:
|
||||
|
||||
* ``offset``: Offset to set.
|
||||
|
||||
All of these commands may only be sent if the printer is currently operational. Otherwise a :http:statuscode:`409`
|
||||
is returned.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
If no heated chambed is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
Requires user rights.
|
||||
|
||||
**Example Target Temperature Request**
|
||||
|
||||
Set the target temperature for the printer's heated chamber to 50°C.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/chamber HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "target",
|
||||
"target": 50
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Offset Temperature Request**
|
||||
|
||||
Set the temperature offset for the heated chamber to -5°C.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/chamber HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "offset",
|
||||
"offset": -5
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``target`` or ``offset``.
|
||||
:json object target: ``target`` command: The target temperature to set.
|
||||
:json object offset: ``offset`` command: The offset temperature to set.
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: If ``target`` or ``offset`` is not a valid number or outside of the supported range, or if the
|
||||
request is otherwise invalid.
|
||||
:statuscode 409: If the printer is not operational or the selected printer profile
|
||||
does not have a heated chamber.
|
||||
|
||||
.. _sec-api-printer-chamberstate:
|
||||
|
||||
Retrieve the current chamber state
|
||||
==================================
|
||||
|
||||
.. http:get:: /api/printer/chamber
|
||||
|
||||
Retrieves the current temperature data (actual, target and offset) plus optionally a (limited) history (actual, target,
|
||||
timestamp) for the printer's heated chamber.
|
||||
|
||||
It's also possible to retrieve the temperature history by supplying the ``history`` query parameter set to ``true``. The
|
||||
amount of returned history data points can be limited using the ``limit`` query parameter.
|
||||
|
||||
Returns a :http:statuscode:`200` with a Temperature Response in the body upon success.
|
||||
|
||||
If no heated chamber is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
.. note::
|
||||
If you want tool, bed and chamber temperature information at the same time, take a look at
|
||||
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
|
||||
|
||||
**Example**
|
||||
|
||||
Query the chamber temperature data and also include the temperature history but limit it to two entries.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/printer/chamber?history=true&limit=2 HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"chamber": {
|
||||
"actual": 50.221,
|
||||
"target": 70.0,
|
||||
"offset": 5
|
||||
},
|
||||
"history": [
|
||||
{
|
||||
"time": 1395651928,
|
||||
"chamber": {
|
||||
"actual": 50.221,
|
||||
"target": 70.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"time": 1395651926,
|
||||
"chamber": {
|
||||
"actual": 49.1123,
|
||||
"target": 70.0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
:query history: If set to ``true`` (or: ``yes``, ``y``, ``1``), history information will be included in the response
|
||||
too. If no ``limit`` parameter is given, all available temperature history data will be returned.
|
||||
:query limit: If set to an integer (``n``), only the last ``n`` data points from the printer's temperature history
|
||||
will be returned. Will be ignored if ``history`` is not enabled.
|
||||
:statuscode 200: No error
|
||||
:statuscode 409: If the printer is not operational or the selected printer profile
|
||||
does not have a heated chamber.
|
||||
|
||||
.. _sec-api-printer-sdcommand:
|
||||
|
||||
Issue an SD command
|
||||
|
||||
@@ -52,6 +52,7 @@ Retrieve all printer profiles
|
||||
"height": 200
|
||||
},
|
||||
"heatedBed": true,
|
||||
"heatedChamber": false,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -93,6 +94,7 @@ Retrieve all printer profiles
|
||||
"height": 200
|
||||
},
|
||||
"heatedBed": true,
|
||||
"heatedChamber": true,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -184,6 +186,7 @@ Add a new printer profile
|
||||
"height": 200
|
||||
},
|
||||
"heatedBed": true,
|
||||
"heatedChamber": false,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -267,6 +270,7 @@ Add a new printer profile
|
||||
"height": 300
|
||||
},
|
||||
"heatedBed": false,
|
||||
"heatedChamber": false,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -352,6 +356,7 @@ Update an existing printer profile
|
||||
"height": 200
|
||||
},
|
||||
"heatedBed": true,
|
||||
"heatedChamber": false,
|
||||
"axes": {
|
||||
"x": {
|
||||
"speed": 6000,
|
||||
@@ -578,6 +583,10 @@ Profile
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether the printer has a heated bed (``true``) or not (``false``)
|
||||
* - ``heatedChamber``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether the printer has a heated chamber (``true``) or not (``false``)
|
||||
* - ``axes``
|
||||
- 0..1
|
||||
- Object
|
||||
|
||||
@@ -62,6 +62,18 @@ Use the following settings to enable access control:
|
||||
# header and login the user without further checks. Use with caution.
|
||||
checkBasicAuthenticationPassword: true
|
||||
|
||||
# Whether to trust remote user headers. If you have setup authentication in front of
|
||||
# OctoPrint and the user names you use there match OctoPrint accounts, by setting this to true users will
|
||||
# be logged into OctoPrint as the user provided in the header. Your should ONLY ENABLE THIS if your
|
||||
# OctoPrint instance is only accessible through a connection locked down through an authenticating reverse proxy!
|
||||
trustRemoteUser: false
|
||||
|
||||
# Header used by the reverse proxy to convey the authenticated user.
|
||||
remoteUserHeader: REMOTE_USER
|
||||
|
||||
# If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint.
|
||||
addRemoteUsers: false
|
||||
|
||||
.. _sec-configuration-config_yaml-api:
|
||||
|
||||
API
|
||||
@@ -323,6 +335,9 @@ The following settings are only relevant to you if you want to do OctoPrint deve
|
||||
# Whether the simulated printer should also simulate a heated bed or not
|
||||
hasBed: true
|
||||
|
||||
# Whether the simulated printer should also simulate a heated chamber or not
|
||||
hasChamber: false
|
||||
|
||||
# If enabled, reports the set target temperatures as separate messages from the firmware
|
||||
#
|
||||
# True: > M109 S220.0
|
||||
@@ -815,6 +830,19 @@ Use the following settings to configure the serial connection to the printer:
|
||||
additionalBaudrates:
|
||||
- 123456
|
||||
|
||||
# Commands which should not be sent to the printer, e.g. because they are known to block serial
|
||||
# communication until physical interaction with the printer as is the case on most firmwares with
|
||||
# the default M0 and M1.
|
||||
blockedCommands:
|
||||
- M0
|
||||
- M1
|
||||
|
||||
# Commands which should cause OctoPrint to pause any ongoing prints.
|
||||
pausingCommands:
|
||||
- M0
|
||||
- M1
|
||||
- M25
|
||||
|
||||
# Commands which are known to take a long time to be acknowledged by the firmware. E.g.
|
||||
# homing, dwelling, auto leveling etc. Defaults to the below commands.
|
||||
longRunningCommands:
|
||||
@@ -941,6 +969,13 @@ Use the following settings to configure the server:
|
||||
# reset the setting to false
|
||||
startOnceInSafeMode: false
|
||||
|
||||
# Signals to OctoPrint that the last startup was incomplete. OctoPrint will then startup
|
||||
# in safe mode
|
||||
incompleteStartup: false
|
||||
|
||||
# Set this to true to make OctoPrint ignore incomplete startups. Helpful for development.
|
||||
ignoreIncompleteStartup: false
|
||||
|
||||
# Secret key for encrypting cookies and such, randomly generated on first run
|
||||
secretKey: someSecretKey
|
||||
|
||||
|
||||
+28
-1
@@ -38,6 +38,13 @@ Example
|
||||
- event: PrintDone
|
||||
command: python ~/growl.py -t mygrowlserver -d "Completed {file}" -a OctoPrint -i http://raspi/Octoprint_logo.png
|
||||
type: system
|
||||
- event:
|
||||
- PrintStarted
|
||||
- PrintFailed
|
||||
- PrintDone
|
||||
- PrintCancelled
|
||||
command: python ~/growl.py -t mygrowlserver -d "Event {__eventname} ({name})" -a OctoPrint -i http://raspi/Octoprint_logo.png
|
||||
type: system
|
||||
- event: Connected
|
||||
command:
|
||||
- M115
|
||||
@@ -53,6 +60,7 @@ Placeholders
|
||||
You can use the following generic placeholders in your event hooks:
|
||||
|
||||
* ``{__currentZ}``: the current Z position of the head if known, -1 if not available
|
||||
* ``{__eventname}`` : the name of the event hook being triggered
|
||||
* ``{__filename}`` : name of currently selected file, or ``NO FILE`` if no file is selected
|
||||
* ``{__filepath}`` : path in origin location of currently selected file, or ``NO FILE`` if no file is selected
|
||||
* ``{__fileorigin}`` : origin of currently selected file, or ``NO FILE`` if no file is selected
|
||||
@@ -80,6 +88,8 @@ Available Events
|
||||
|
||||
Plugins may add additional events via the :ref:`octoprint.events.register_custom_events hook <sec-plugins-hook-events-register_custom_events>`.
|
||||
|
||||
.. _sec-events-available_events-server:
|
||||
|
||||
Server
|
||||
------
|
||||
|
||||
@@ -113,6 +123,8 @@ ConnectivityChanged
|
||||
* ``old``: Old connectivity value (true for online, false for offline)
|
||||
* ``new``: New connectivity value (true for online, false for offline)
|
||||
|
||||
.. _sec-events-available_events-printer_commmunication:
|
||||
|
||||
Printer communication
|
||||
---------------------
|
||||
|
||||
@@ -152,6 +164,8 @@ PrinterStateChanged
|
||||
:func:`~octoprint.printer.PrinterInterface.get_state_id` for possible values.
|
||||
* ``state_string``: Text representation of the new state.
|
||||
|
||||
.. _sec-events-available_events-file_handling:
|
||||
|
||||
File handling
|
||||
-------------
|
||||
|
||||
@@ -299,6 +313,8 @@ TransferDone
|
||||
* ``local``: the file's name as stored locally
|
||||
* ``remote``: the file's name as stored on SD
|
||||
|
||||
.. _sec-events-available_events-printing:
|
||||
|
||||
Printing
|
||||
--------
|
||||
|
||||
@@ -443,6 +459,8 @@ PrintResumed
|
||||
* ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). To be removed in 1.4.0.
|
||||
* ``filename``: the file's name. To be removed in 1.4.0.
|
||||
|
||||
.. _sec-events-available_events-gcode_processing:
|
||||
|
||||
GCODE processing
|
||||
----------------
|
||||
|
||||
@@ -504,6 +522,8 @@ ToolChange
|
||||
* ``old``: old tool index
|
||||
* ``new``: new tool index
|
||||
|
||||
.. _sec-events-available_events-timelapses:
|
||||
|
||||
Timelapses
|
||||
----------
|
||||
|
||||
@@ -558,6 +578,8 @@ MovieFailed
|
||||
returned a non-0 return code, ``no_frames`` if no frames were captured that could be rendered
|
||||
to a timelapse, or ``unknown`` for any other reason of failure to render.
|
||||
|
||||
.. _sec-events-available_events-slicing:
|
||||
|
||||
Slicing
|
||||
-------
|
||||
|
||||
@@ -629,8 +651,13 @@ SlicingProfileDeleted
|
||||
* ``slicer``: the slicer for which the profile was deleted
|
||||
* ``profile``: the profile that was deleted
|
||||
|
||||
.. _sec-events-available_events-settings:
|
||||
|
||||
Settings
|
||||
--------
|
||||
|
||||
SettingsUpdated
|
||||
The internal settings were updated.
|
||||
The settings were updated via the REST API.
|
||||
|
||||
This event may also be triggered if calling code of :py:class:`octoprint.settings.Settings.save` or
|
||||
:py:class:`octoprint.plugin.PluginSettings.save` sets the ``trigger_event`` parameter to ``True``.
|
||||
@@ -21,12 +21,12 @@ Commands, which are admin-only.
|
||||
|
||||
If Access Control is disabled, everything is directly accessible. **That also
|
||||
includes all administrative functionality as well as full control over the
|
||||
printer!**
|
||||
printer**, and without the need for an :ref:`API key <sec-api-general-authorization>`!
|
||||
|
||||
Upon first start a configuration wizard is provided which allows configuration
|
||||
of the first administrator account or alternatively disabling Access Control
|
||||
(which is **NOT** recommended for systems that are directly accessible via the
|
||||
Internet!).
|
||||
internet or other untrusted networks!).
|
||||
|
||||
.. hint::
|
||||
|
||||
|
||||
+2
-2
@@ -11,7 +11,7 @@ and released under the `GNU Affero General Public License V3 <http://www.gnu.org
|
||||
|
||||
Its website can be found at `octoprint.org <https://octoprint.org/>`_.
|
||||
|
||||
The community forum is available at `discourse.octoprint.org <https://discourse.octoprint.org/>`_.
|
||||
The community forum is available at `community.octoprint.org <https://community.octoprint.org/>`_.
|
||||
|
||||
The FAQ can be accessed by following `faq.octoprint.org <https://faq.octoprint.org/>`_.
|
||||
|
||||
@@ -23,7 +23,7 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!
|
||||
.. note::
|
||||
|
||||
This documentation currently focuses primarily on developers and less on end users. If you are interested in
|
||||
helping to change this, please get in touch `on the forum <https://discourse.octoprint.org/>`_!
|
||||
helping to change this, please get in touch `on the forum <https://community.octoprint.org/>`_!
|
||||
|
||||
Contents
|
||||
========
|
||||
|
||||
@@ -210,6 +210,64 @@
|
||||
: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.printer.getChamberState(data, opts)
|
||||
|
||||
Retrieves the current printer chamber state/temperature information, and optionally also the temperature
|
||||
history.
|
||||
|
||||
The ``flags`` object can be used to specify the data to retrieve further via the following
|
||||
properties:
|
||||
|
||||
* ``history``: a boolean value to specify whether the temperature history should be included (``true``)
|
||||
or not (``false``), defaults to it not being included
|
||||
* ``limit``: an integer value to specify how many history entries to include
|
||||
|
||||
See :ref:`Retrieve the current bed state <sec-api-printer-chamberstate>` for more details.
|
||||
|
||||
:param object flags: Flags that further specify which data to retrieve, see above for details
|
||||
:param object opts: Additional options for the request
|
||||
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
|
||||
|
||||
.. js:function:: OctoPrintClient.printer.setChamberTargetTemperature(target, opts)
|
||||
|
||||
Sets the given temperature on the printer's heated chamber (if available).
|
||||
|
||||
``target`` is expected to be the target temperature as a float value.
|
||||
|
||||
**Example:**
|
||||
|
||||
Set the chamber to 50°C.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
OctoPrint.printer.setChamberTargetTemperature(50.0);
|
||||
|
||||
See the ``target`` command in :ref:`Issue a chamber command <sec-api-printer-chambercommand>` for more details.
|
||||
|
||||
:param float target: The target to set
|
||||
: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.printer.setChamberTemperatureOffset(offset, opts)
|
||||
|
||||
Sets the given temperature offset for the printer's heated chamber (if available).
|
||||
|
||||
``offset`` is expected to be the temperature offset to set.
|
||||
|
||||
**Example:**
|
||||
|
||||
Set the offset for the chamber to -5°C.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
OctoPrint.printer.setChamberTemperatureOffset(-5);
|
||||
|
||||
See the ``offset`` command in :ref:`Issue a chamber command <sec-api-printer-chambercommand>` for more details.
|
||||
|
||||
:param object offsets: The offsets to set
|
||||
: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.printer.jog(amounts, opts)
|
||||
|
||||
Jogs the specified axes by the specified ``amounts``.
|
||||
|
||||
@@ -736,9 +736,10 @@ octoprint.comm.protocol.scripts
|
||||
make sure to only proceed with returning additional scripts if the ``script_type`` and ``script_name`` match
|
||||
handled scripts. If not, None should be returned directly.
|
||||
|
||||
If the hook handler has something to add to the specified script, it may return a 2-tuple or a 3-tuple with the first entry
|
||||
If the hook handler has something to add to the specified script, it may return a 2-tuple, a 3-tuple or a 4-tuple with the first entry
|
||||
defining the prefix (what to *prepend* to the script in question), the second entry defining the postfix (what to
|
||||
*append* to the script in question), and finally if desired a dictionary of variables to be made available to the script. Both prefix and postfix can be None to signify that nothing should be prepended
|
||||
*append* to the script in question), and finally if desired a dictionary of variables to be made available to the script on third and additional tags to set on the
|
||||
commands on fourth position. Both prefix and postfix can be None to signify that nothing should be prepended
|
||||
respectively appended.
|
||||
|
||||
The returned prefix and postfix entries may be either iterables of script lines or a string including newlines of the script lines (which
|
||||
|
||||
@@ -27,7 +27,7 @@ INSTALL_REQUIRES = [
|
||||
# guarantee backwards compatibility for plugins and such with that
|
||||
# version, hence we need to pin to a lower version for now. See #1697
|
||||
"tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585
|
||||
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
|
||||
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
|
||||
|
||||
# anything below this should be checked on releases for new versions
|
||||
|
||||
@@ -35,39 +35,39 @@ INSTALL_REQUIRES = [
|
||||
"Flask-Principal>=0.4,<0.5",
|
||||
"Flask-Babel>=0.12,<0.13",
|
||||
"Flask-Assets>=0.12,<0.13",
|
||||
"werkzeug>=0.14.1,<0.15",
|
||||
"PyYAML>=3.13,<4",
|
||||
"werkzeug>=0.15.1,<0.16",
|
||||
"cachelib>=0.1,<0.2",
|
||||
"PyYAML>=5.1,<6",
|
||||
"markdown>=3.0,<3.1",
|
||||
"pyserial>=3.4,<3.5",
|
||||
"netaddr>=0.7.19,<0.8",
|
||||
"watchdog>=0.9.0,<0.10",
|
||||
"sarge==0.1.5post0",
|
||||
"netifaces>=0.10.7,<0.11",
|
||||
"pylru>=1.1,<1.2",
|
||||
"netifaces>=0.10.9,<0.11",
|
||||
"pylru>=1.2,<1.3",
|
||||
"rsa>=4.0,<5",
|
||||
"pkginfo>=1.4.2,<1.5",
|
||||
"requests>=2.20.0,<3",
|
||||
"pkginfo>=1.5.0.1,<1.6",
|
||||
"requests>=2.21.0,<3",
|
||||
"semantic_version>=2.6,<2.7",
|
||||
"psutil>=5.4.8,<5.5",
|
||||
"psutil>=5.6.1,<5.7",
|
||||
"Click>=7,<8",
|
||||
"awesome-slugify>=1.6.5,<1.7",
|
||||
"feedparser>=5.2.1,<5.3",
|
||||
"future>=0.17,<0.18",
|
||||
"websocket-client>=0.53,<0.54",
|
||||
"python-dateutil>=2.7.5,<2.8",
|
||||
"wrapt>=1.10.11,<1.11",
|
||||
"websocket-client>=0.56,<0.57",
|
||||
"wrapt>=1.11.1,<1.12",
|
||||
"emoji>=0.5.1,<0.6",
|
||||
"frozendict>=1.2,<1.3",
|
||||
"sentry-sdk==0.6.6"
|
||||
"sentry-sdk==0.7.7"
|
||||
]
|
||||
|
||||
# Python 2 specific requirements
|
||||
INSTALL_REQUIRES_PYTHON2 = [
|
||||
"futures>=3.2,<3.3",
|
||||
"monotonic>=1.5,<1.6",
|
||||
"scandir>=1.9,<1.10",
|
||||
"chainmap>=1.0.2,<1.1",
|
||||
"typing>=3.6.4,<4"
|
||||
"scandir>=1.10,<1.11",
|
||||
"chainmap>=1.0.3,<1.1",
|
||||
"typing>=3.6.6,<4"
|
||||
]
|
||||
|
||||
# OSX specific requirements
|
||||
@@ -227,7 +227,7 @@ def params():
|
||||
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
|
||||
|
||||
project_urls={
|
||||
"Community Forum": "https://discourse.octoprint.org",
|
||||
"Community Forum": "https://community.octoprint.org",
|
||||
"Bug Reports": "https://github.com/foosel/OctoPrint/issues",
|
||||
"Source": "https://github.com/foosel/OctoPrint",
|
||||
"Funding": "https://donate.octoprint.org"
|
||||
|
||||
@@ -105,7 +105,10 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
|
||||
after_logging(**kwargs)
|
||||
|
||||
settings_start_once_in_safemode = "settings" if settings.getBoolean(["server", "startOnceInSafeMode"]) else None
|
||||
settings_incomplete_startup_safemode = "incomplete_startup" if settings.getBoolean(["server", "incompleteStartup"]) else None
|
||||
settings_incomplete_startup_safemode = "incomplete_startup" \
|
||||
if settings.getBoolean(["server", "incompleteStartup"]) \
|
||||
and not settings.getBoolean(["server", "ignoreIncompleteStartup"]) \
|
||||
else None
|
||||
safe_mode = safe_mode or settings_start_once_in_safemode or settings_incomplete_startup_safemode
|
||||
kwargs["safe_mode"] = safe_mode
|
||||
if callable(after_safe_mode):
|
||||
|
||||
@@ -20,7 +20,7 @@ import logging
|
||||
from builtins import range, bytes
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import atomic_write, to_bytes, deprecated
|
||||
from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time
|
||||
from octoprint.access.permissions import Permissions, OctoPrintPermission
|
||||
from octoprint.access.groups import GroupChangeListener, Group
|
||||
|
||||
@@ -129,11 +129,10 @@ class UserManager(GroupChangeListener, object):
|
||||
self._logger.debug("Logged out user: %r" % user)
|
||||
|
||||
def _cleanup_sessions(self):
|
||||
import time
|
||||
for session, user in self._session_users_by_session.items():
|
||||
if not isinstance(user, SessionUser):
|
||||
continue
|
||||
if user.created + (24 * 60 * 60) < time.time():
|
||||
if user.created + (24 * 60 * 60) < monotonic_time():
|
||||
self.logout_user(user)
|
||||
|
||||
@staticmethod
|
||||
@@ -1191,8 +1190,8 @@ class SessionUser(wrapt.ObjectProxy):
|
||||
wrapt.ObjectProxy.__init__(self, user)
|
||||
|
||||
self._self_session = "".join('%02X' % z for z in bytes(uuid.uuid4().bytes))
|
||||
self._self_created = time.time()
|
||||
self._self_touched = time.time()
|
||||
self._self_created = monotonic_time()
|
||||
self._self_touched = monotonic_time()
|
||||
|
||||
@property
|
||||
def session(self):
|
||||
@@ -1207,7 +1206,7 @@ class SessionUser(wrapt.ObjectProxy):
|
||||
return self._self_touched
|
||||
|
||||
def touch(self):
|
||||
self._self_touched = time.time()
|
||||
self._self_touched = monotonic_time()
|
||||
|
||||
@deprecated("SessionUser.get_session() has been deprecated, use SessionUser.session instead", since="1.3.5")
|
||||
def get_session(self):
|
||||
|
||||
@@ -35,6 +35,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
|
||||
|
||||
import time
|
||||
import yaml
|
||||
from octoprint.util import monotonic_time
|
||||
from octoprint.util.gcodeInterpreter import gcode
|
||||
|
||||
throttle_callback = None
|
||||
@@ -53,7 +54,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
|
||||
if len(offsets) < maxt:
|
||||
offsets += [(0, 0)] * (maxt - len(offsets))
|
||||
|
||||
start_time = time.time()
|
||||
start_time = monotonic_time()
|
||||
|
||||
progress_callback = None
|
||||
if progress:
|
||||
@@ -69,7 +70,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
|
||||
max_extruders=maxt,
|
||||
g90_extruder=g90_extruder)
|
||||
|
||||
click.echo("DONE:{}s".format(time.time() - start_time))
|
||||
click.echo("DONE:{}s".format(monotonic_time() - start_time))
|
||||
click.echo("RESULTS:")
|
||||
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=4, allow_unicode=True))
|
||||
|
||||
|
||||
@@ -93,7 +93,8 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
continue
|
||||
result[name + self.sep + command.name] = command
|
||||
except Exception:
|
||||
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name))
|
||||
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
+29
-13
@@ -12,7 +12,7 @@ import sys
|
||||
|
||||
from octoprint.cli import bulk_options, standard_options, set_ctx_obj_option, get_ctx_obj_option
|
||||
|
||||
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode,
|
||||
def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logging_config, verbosity, safe_mode,
|
||||
ignore_blacklist, octoprint_daemon=None):
|
||||
"""Initializes the environment and starts up the server."""
|
||||
|
||||
@@ -111,6 +111,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
environment_detector=environment_detector,
|
||||
host=host,
|
||||
port=port,
|
||||
v6_only=v6_only,
|
||||
debug=debug,
|
||||
safe_mode=safe_mode,
|
||||
allow_root=allow_root,
|
||||
@@ -121,9 +122,13 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
|
||||
|
||||
server_options = bulk_options([
|
||||
click.option("--host", type=click.STRING, callback=set_ctx_obj_option,
|
||||
help="Specify the host on which to bind the server."),
|
||||
help="Specify the host address on which to bind the server."),
|
||||
click.option("--port", type=click.INT, callback=set_ctx_obj_option,
|
||||
help="Specify the port on which to bind the server."),
|
||||
click.option("-4", "--ipv4", "v4", is_flag=True, callback=set_ctx_obj_option,
|
||||
help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present."),
|
||||
click.option("-6", "--ipv6", "v6", is_flag=True, callback=set_ctx_obj_option,
|
||||
help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present."),
|
||||
click.option("--logging", type=click.Path(), callback=set_ctx_obj_option,
|
||||
help="Specify the config file to use for configuring logging."),
|
||||
click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option,
|
||||
@@ -133,7 +138,7 @@ server_options = bulk_options([
|
||||
click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option,
|
||||
help="Disable processing of the plugin blacklist.")
|
||||
])
|
||||
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``,
|
||||
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``-4``, ``-6``
|
||||
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
|
||||
|
||||
daemon_options = bulk_options([
|
||||
@@ -163,11 +168,11 @@ def enable_safemode(ctx, **kwargs):
|
||||
click.echo(e.message, err=True)
|
||||
click.echo("There was a fatal error initializing the settings manager.", err=True)
|
||||
ctx.exit(-1)
|
||||
else:
|
||||
settings.setBoolean(["server", "startOnceInSafeMode"], True)
|
||||
settings.save()
|
||||
|
||||
settings.setBoolean(["server", "startOnceInSafeMode"], True)
|
||||
settings.save()
|
||||
|
||||
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
|
||||
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
|
||||
|
||||
|
||||
@server_commands.command(name="serve")
|
||||
@@ -182,6 +187,8 @@ def serve_command(ctx, **kwargs):
|
||||
|
||||
host = get_value("host")
|
||||
port = get_value("port")
|
||||
v4 = get_value("v4")
|
||||
v6 = get_value("v6")
|
||||
logging = get_value("logging")
|
||||
allow_root = get_value("allow_root")
|
||||
debug = get_value("debug")
|
||||
@@ -192,7 +199,10 @@ def serve_command(ctx, **kwargs):
|
||||
safe_mode = "flag" if get_value("safe_mode") else None
|
||||
ignore_blacklist = get_value("ignore_blacklist")
|
||||
|
||||
run_server(basedir, configfile, host, port, debug,
|
||||
if v4 and not host:
|
||||
host = "0.0.0.0"
|
||||
|
||||
run_server(basedir, configfile, host, port, v6, debug,
|
||||
allow_root, logging, verbosity, safe_mode,
|
||||
ignore_blacklist)
|
||||
|
||||
@@ -219,6 +229,8 @@ if sys.platform != "win32" and sys.platform != "darwin":
|
||||
|
||||
host = get_value("host")
|
||||
port = get_value("port")
|
||||
v4 = get_value("v4")
|
||||
v6 = get_value("v6")
|
||||
logging = get_value("logging")
|
||||
allow_root = get_value("allow_root")
|
||||
debug = get_value("debug")
|
||||
@@ -230,6 +242,9 @@ if sys.platform != "win32" and sys.platform != "darwin":
|
||||
safe_mode = "flag" if get_value("safe_mode") else None
|
||||
ignore_blacklist = get_value("ignore_blacklist")
|
||||
|
||||
if v4 and not host:
|
||||
host = "0.0.0.0"
|
||||
|
||||
if pid is None:
|
||||
click.echo("No path to a pidfile set",
|
||||
file=sys.stderr)
|
||||
@@ -237,14 +252,15 @@ if sys.platform != "win32" and sys.platform != "darwin":
|
||||
|
||||
from octoprint.daemon import Daemon
|
||||
class OctoPrintDaemon(Daemon):
|
||||
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity,
|
||||
safe_mode, ignore_blacklist):
|
||||
def __init__(self, pidfile, basedir, configfile, host, port, v6_only, debug, allow_root, logging_config,
|
||||
verbosity, safe_mode, ignore_blacklist):
|
||||
Daemon.__init__(self, pidfile)
|
||||
|
||||
self._basedir = basedir
|
||||
self._configfile = configfile
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._v6_only = v6_only
|
||||
self._debug = debug
|
||||
self._allow_root = allow_root
|
||||
self._logging_config = logging_config
|
||||
@@ -253,12 +269,12 @@ if sys.platform != "win32" and sys.platform != "darwin":
|
||||
self._ignore_blacklist = ignore_blacklist
|
||||
|
||||
def run(self):
|
||||
run_server(self._basedir, self._configfile, self._host, self._port, self._debug,
|
||||
run_server(self._basedir, self._configfile, self._host, self._port, self._v6_only, self._debug,
|
||||
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
|
||||
self._ignore_blacklist, octoprint_daemon=self)
|
||||
|
||||
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity,
|
||||
safe_mode, ignore_blacklist)
|
||||
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, v6, debug, allow_root, logging,
|
||||
verbosity, safe_mode, ignore_blacklist)
|
||||
|
||||
if command == "start":
|
||||
octoprint_daemon.start()
|
||||
|
||||
@@ -370,6 +370,9 @@ class ThreeDPrinterProtocolMixin(ThreeAxisProtocolMixin, MultiToolProtocolMixin)
|
||||
def set_bed_temperature(self, temperature, wait=False, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def set_chamber_temperature(self, temperature, wait=False, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class FanControlProtocolMixin(object):
|
||||
def set_fan_speed(self, speed, *args, **kwargs):
|
||||
|
||||
@@ -82,6 +82,7 @@ CAPABILITY_AUTOREPORT_TEMP = "AUTOREPORT_TEMP"
|
||||
CAPABILITY_AUTOREPORT_SD_STATUS = "AUTOREPORT_SD_STATUS"
|
||||
CAPABILITY_BUSY_PROTOCOL = "BUSY_PROTOCOL"
|
||||
CAPABILITY_EMERGENCY_PARSER = "EMERGENCY_PARSER"
|
||||
CAPABILITY_CHAMBER_TEMP = "CHAMBER_TEMPERATURE"
|
||||
|
||||
|
||||
class FallbackValue(object):
|
||||
@@ -192,6 +193,7 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
self._capability_support = dict()
|
||||
self._capability_support[CAPABILITY_AUTOREPORT_TEMP] = True
|
||||
self._capability_support[CAPABILITY_BUSY_PROTOCOL] = True
|
||||
self._capability_support[CAPABILITY_CHAMBER_TEMP] = True
|
||||
|
||||
self._transport = None
|
||||
|
||||
@@ -562,6 +564,11 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
self._send_commands(self.flavor.command_set_bed_temp(temperature, wait=wait),
|
||||
tags=tags)
|
||||
|
||||
def set_chamber_temperature(self, temperature, wait=False, *args, **kwargs):
|
||||
tags = kwargs.get("tags", set()) | {"trigger:protocol.set_chamber_temperature"}
|
||||
self._send_commands(self.flavor.command_set_bed_temp(temperature, wait=wait),
|
||||
tags=tags)
|
||||
|
||||
##~~ MotorControlProtocolMixin
|
||||
|
||||
def set_motor_state(self, enabled, *args, **kwargs):
|
||||
@@ -1285,6 +1292,10 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
actual, target = temperatures["B"]
|
||||
self._internal_flags["temperatures"].set_bed(actual=actual, target=target)
|
||||
|
||||
if "C" in temperatures and (self._capability_support.get(CAPABILITY_CHAMBER_TEMP, False) or self._printer_profile["heatedChamber"]):
|
||||
actual, target = temperatures["C"]
|
||||
self._internal_flags["temperatures"].set_chamber(actual=actual, target=target)
|
||||
|
||||
self.notify_listeners("on_protocol_temperature", self, self._internal_flags["temperatures"].as_dict())
|
||||
|
||||
def _on_message_position(self, position):
|
||||
@@ -2049,6 +2060,17 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
self._internal_flags["temperatures"].set_bed(target=target)
|
||||
self.notify_listeners("on_protocol_temperature", self, self._internal_flags["temperatures"].as_dict())
|
||||
|
||||
def _gcode_M141_sent(self, command, wait=False, support_r=False):
|
||||
target = None
|
||||
if command.s is not None:
|
||||
target = float(command.s)
|
||||
elif command.r is not None and support_r:
|
||||
target = float(command.r)
|
||||
|
||||
if target:
|
||||
self._internal_flags["temperatures"].set_chamber(target=target)
|
||||
self.notify_listeners("on_protocol_temperature", self, self._internal_flags["temperatures"].as_dict())
|
||||
|
||||
def _gcode_M109_sent(self, command):
|
||||
self._internal_flags["heatup_start"] = monotonic_time()
|
||||
self._internal_flags["long_running_command"] = True
|
||||
@@ -2061,6 +2083,12 @@ class ReprapGcodeProtocol(Protocol, ThreeDPrinterProtocolMixin, MotorControlProt
|
||||
self._internal_flags["heating"] = True
|
||||
self._gcode_M140_sent(command, wait=True, support_r=True)
|
||||
|
||||
def _gcode_M191_sent(self, command):
|
||||
self._internal_flags["heatup_start"] = monotonic_time()
|
||||
self._internal_flags["long_running_command"] = True
|
||||
self._internal_flags["heating"] = True
|
||||
self._gcode_M141_sent(command, wait=True, support_r=True)
|
||||
|
||||
def _gcode_M116_sent(self, command):
|
||||
self._internal_flags["heatup_start"] = monotonic_time()
|
||||
self._internal_flags["long_running_command"] = True
|
||||
|
||||
@@ -432,6 +432,10 @@ class GenericFlavor(with_metaclass(FlavorMeta, object)):
|
||||
def command_set_bed_temp(cls, temperature, wait=False):
|
||||
return GcodeCommand("M190" if wait else "M140", s=temperature)
|
||||
|
||||
@classmethod
|
||||
def command_set_chamber_temp(cls, temperature, wait=False):
|
||||
return GcodeCommand("M191" if wait else "M141", s=temperature)
|
||||
|
||||
@classmethod
|
||||
def command_set_relative_positioning(cls):
|
||||
return GcodeCommand("G91")
|
||||
|
||||
@@ -312,10 +312,12 @@ class TemperatureRecord(object):
|
||||
def __init__(self):
|
||||
self._tools = dict()
|
||||
self._bed = (None, None)
|
||||
self._chamber = (None, None)
|
||||
|
||||
def copy_from(self, other):
|
||||
self._tools = other.tools
|
||||
self._bed = other.bed
|
||||
self._chamber = other.chamber
|
||||
|
||||
def set_tool(self, tool, actual=None, target=None):
|
||||
current = self._tools.get(tool, (None, None))
|
||||
@@ -325,6 +327,10 @@ class TemperatureRecord(object):
|
||||
current = self._bed
|
||||
self._bed = self._to_new_tuple(current, actual, target)
|
||||
|
||||
def set_chamber(self, actual=None, target=None):
|
||||
current = self._chamber()
|
||||
self._chamber = self._to_new_tuple(current, actual, target)
|
||||
|
||||
@property
|
||||
def tools(self):
|
||||
return dict(self._tools)
|
||||
@@ -333,6 +339,10 @@ class TemperatureRecord(object):
|
||||
def bed(self):
|
||||
return self._bed
|
||||
|
||||
@property
|
||||
def chamber(self):
|
||||
return self._chamber
|
||||
|
||||
def as_dict(self):
|
||||
result = dict()
|
||||
|
||||
@@ -345,6 +355,10 @@ class TemperatureRecord(object):
|
||||
result["bed"] = dict(actual=bed[0],
|
||||
target=bed[1])
|
||||
|
||||
chamber = self.chamber
|
||||
result["chamber"] = dict(actual=chamber[0],
|
||||
target=chamber[1])
|
||||
|
||||
return result
|
||||
|
||||
def as_script_dict(self):
|
||||
@@ -360,6 +374,10 @@ class TemperatureRecord(object):
|
||||
result["b"] = dict(actual=bed[0],
|
||||
target=bed[1])
|
||||
|
||||
chamber = self.chamber
|
||||
result["c"] = dict(actual=chamber[0],
|
||||
target=chamber[1])
|
||||
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -25,10 +25,15 @@ class EnvironmentDetector(object):
|
||||
self._cache = None
|
||||
self._cache_lock = threading.RLock()
|
||||
|
||||
self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
try:
|
||||
self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
|
||||
except Exception:
|
||||
# just in case, see #3100...
|
||||
self._logger.exception("There was an error fetching EnvironmentDetectionPlugins from the plugin manager")
|
||||
self._environment_plugins = []
|
||||
|
||||
@property
|
||||
def environment(self):
|
||||
with self._cache_lock:
|
||||
@@ -120,7 +125,8 @@ class EnvironmentDetector(object):
|
||||
result[implementation._identifier] = additional
|
||||
except Exception:
|
||||
self._logger.exception("Error while fetching additional "
|
||||
"environment data from plugin {}".format(implementation._identifier))
|
||||
"environment data from plugin {}".format(implementation._identifier),
|
||||
extra=dict(plugin=implementation._identifier))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
+19
-11
@@ -186,8 +186,7 @@ class EventManager(object):
|
||||
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
|
||||
"on_event",
|
||||
args=(event, payload),
|
||||
initialized=True)
|
||||
args=(event, payload))
|
||||
self._logger.info("Event loop shut down")
|
||||
except Exception:
|
||||
self._logger.exception("Ooops, the event bus worker loop crashed")
|
||||
@@ -343,17 +342,24 @@ class CommandTrigger(GenericEventListener):
|
||||
self._logger.info("Disabled command trigger: {!r}".format(subscription))
|
||||
continue
|
||||
|
||||
event = subscription["event"]
|
||||
events = subscription["event"]
|
||||
command = subscription["command"]
|
||||
commandType = subscription["type"]
|
||||
debug = subscription["debug"] if "debug" in subscription else False
|
||||
|
||||
if event not in self._subscriptions:
|
||||
self._subscriptions[event] = []
|
||||
self._subscriptions[event].append((command, commandType, debug))
|
||||
# "event" in the configuration can be a string, or
|
||||
# a list of strings. If it's the former, convert it
|
||||
# into the latter.
|
||||
if not isinstance(events, (tuple, list, set)):
|
||||
events = [events]
|
||||
|
||||
if event not in eventsToSubscribe:
|
||||
eventsToSubscribe.append(event)
|
||||
for event in events:
|
||||
if event not in self._subscriptions:
|
||||
self._subscriptions[event] = []
|
||||
self._subscriptions[event].append((command, commandType, debug))
|
||||
|
||||
if event not in eventsToSubscribe:
|
||||
eventsToSubscribe.append(event)
|
||||
|
||||
self.subscribe(eventsToSubscribe)
|
||||
|
||||
@@ -373,9 +379,9 @@ class CommandTrigger(GenericEventListener):
|
||||
if isinstance(command, (tuple, list, set)):
|
||||
processedCommand = []
|
||||
for c in command:
|
||||
processedCommand.append(self._processCommand(c, payload))
|
||||
processedCommand.append(self._processCommand(c, event, payload))
|
||||
else:
|
||||
processedCommand = self._processCommand(command, payload)
|
||||
processedCommand = self._processCommand(command, event, payload)
|
||||
self.executeCommand(processedCommand, commandType, debug=debug)
|
||||
except KeyError:
|
||||
self._logger.warning("There was an error processing one or more placeholders in the following command: %s" % command)
|
||||
@@ -424,13 +430,14 @@ class CommandTrigger(GenericEventListener):
|
||||
self._logger.info("Executing GCode commands: %r" % command)
|
||||
self._printer.commands(commands)
|
||||
|
||||
def _processCommand(self, command, payload):
|
||||
def _processCommand(self, command, event, payload):
|
||||
"""
|
||||
Performs string substitutions in the command string based on a few current parameters.
|
||||
|
||||
The following substitutions are currently supported:
|
||||
|
||||
- {__currentZ} : current Z position of the print head, or -1 if not available
|
||||
- {__eventname} : the name of the event hook being triggered
|
||||
- {__filename} : name of currently selected file, or "NO FILE" if no file is selected
|
||||
- {__filepath} : path in origin location of currently selected file, or "NO FILE" if no file is selected
|
||||
- {__fileorigin} : origin of currently selected file, or "NO FILE" if no file is selected
|
||||
@@ -453,6 +460,7 @@ class CommandTrigger(GenericEventListener):
|
||||
|
||||
params = {
|
||||
"__currentZ": "-1",
|
||||
"__eventname": event,
|
||||
"__filename": "NO FILE",
|
||||
"__filepath": "NO PATH",
|
||||
"__progress": "0",
|
||||
|
||||
@@ -79,7 +79,9 @@ def full_extension_tree():
|
||||
continue
|
||||
result = octoprint.util.dict_merge(result, plugin_result, leaf_merger=leaf_merger)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from SlicerPlugin {name}".format(name=plugin.key))
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension "
|
||||
"tree entries from SlicerPlugin {name}".format(name=plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
|
||||
extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree")
|
||||
for name, hook in extension_tree_hooks.items():
|
||||
@@ -89,7 +91,9 @@ def full_extension_tree():
|
||||
continue
|
||||
result = octoprint.util.dict_merge(result, hook_result, leaf_merger=leaf_merger)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from hook {name}".format(name=name))
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional extension "
|
||||
"tree entries from hook {name}".format(name=name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
return result
|
||||
|
||||
@@ -338,13 +342,13 @@ class FileManager(object):
|
||||
gcode_location=dest_location))
|
||||
else:
|
||||
source_meta = self.get_metadata(source_location, source_path)
|
||||
hash = source_meta["hash"]
|
||||
hash = source_meta.get("hash", "n/a")
|
||||
|
||||
import io
|
||||
links = [("model", dict(name=source_path))]
|
||||
_, stl_name = self.split_path(source_location, source_path)
|
||||
file_obj = StreamWrapper(os.path.basename(dest_path),
|
||||
io.BytesIO(";Generated from {stl_name} {hash}\n".format(**locals()).encode("ascii", "replace")),
|
||||
io.BytesIO(";Generated from {stl_name} (hash: {hash})\n".format(**locals()).encode("ascii", "replace")),
|
||||
io.FileIO(tmp_path, 'rb'))
|
||||
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
@@ -352,7 +356,7 @@ class FileManager(object):
|
||||
display=display, links=links, allow_overwrite=True,
|
||||
printer_profile=printer_profile, analysis=_analysis)
|
||||
|
||||
end_time = time.time()
|
||||
end_time = octoprint.util.monotonic_time()
|
||||
eventManager().fire(Events.SLICING_DONE, dict(stl=source_path,
|
||||
stl_location=source_location,
|
||||
gcode=dest_path,
|
||||
@@ -377,8 +381,7 @@ class FileManager(object):
|
||||
|
||||
slicer = self._slicing_manager.get_slicer(slicer_name)
|
||||
|
||||
import time
|
||||
start_time = time.time()
|
||||
start_time = octoprint.util.monotonic_time()
|
||||
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path,
|
||||
"stl_location": source_location,
|
||||
"gcode": dest_path,
|
||||
@@ -433,7 +436,8 @@ class FileManager(object):
|
||||
try:
|
||||
plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress)
|
||||
except Exception:
|
||||
self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier)
|
||||
self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier,
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
|
||||
import threading
|
||||
thread = threading.Thread(target=call_plugins, args=(slicer, source_location, source_path, dest_location, dest_path, progress_int))
|
||||
@@ -468,11 +472,11 @@ class FileManager(object):
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
for hook in self._preprocessor_hooks.values():
|
||||
for name, hook in self._preprocessor_hooks.items():
|
||||
try:
|
||||
hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
except Exception:
|
||||
self._logger.exception("Error when calling preprocessor hook {}, ignoring".format(hook))
|
||||
self._logger.exception("Error when calling preprocessor hook for plugin {}, ignoring".format(name), extra=dict(plugin=name))
|
||||
continue
|
||||
|
||||
if hook_file_object is not None:
|
||||
|
||||
@@ -18,6 +18,7 @@ import time
|
||||
|
||||
from octoprint.events import Events, eventManager
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import monotonic_time
|
||||
|
||||
|
||||
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
|
||||
@@ -249,7 +250,7 @@ class AbstractAnalysisQueue(object):
|
||||
self._current_progress = 0
|
||||
|
||||
try:
|
||||
start_time = time.time()
|
||||
start_time = monotonic_time()
|
||||
self._logger.info("Starting analysis of {}".format(entry))
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name,
|
||||
"path": entry.path,
|
||||
@@ -262,7 +263,7 @@ class AbstractAnalysisQueue(object):
|
||||
result = self._do_analysis(high_priority=high_priority)
|
||||
except TypeError:
|
||||
result = self._do_analysis()
|
||||
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, time.time() - start_time))
|
||||
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, monotonic_time() - start_time))
|
||||
self._finished_callback(self._current, result)
|
||||
finally:
|
||||
self._current = None
|
||||
|
||||
@@ -1151,13 +1151,21 @@ class LocalFileStorage(Storage):
|
||||
except Exception:
|
||||
self._logger.exception("Error while reading .metadata.json from {path}".format(**locals()))
|
||||
|
||||
def valid_json(value):
|
||||
try:
|
||||
json.dumps(value, allow_nan=False)
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
if isinstance(metadata, dict):
|
||||
old_size = len(metadata)
|
||||
metadata = { k: v for k, v in metadata.items() if valid_json(v) }
|
||||
metadata = { k: v for k, v in metadata.items() if os.path.exists(os.path.join(path, k)) }
|
||||
new_size = len(metadata)
|
||||
if new_size != old_size:
|
||||
self._logger.info("Deleted {} stale entries from metadata for path {}".format(old_size - new_size,
|
||||
path))
|
||||
self._logger.info("Deleted {} stale or invalid entries from metadata for path {}".format(old_size - new_size,
|
||||
path))
|
||||
self._save_metadata(path, metadata)
|
||||
else:
|
||||
with self._get_metadata_lock(path):
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
from past.builtins import basestring
|
||||
from past.builtins import basestring, unicode
|
||||
|
||||
from octoprint.logging import handlers
|
||||
|
||||
from typing import Union
|
||||
|
||||
def log_to_handler(logger, handler, level, msg, exc_info=None, extra=None, *args):
|
||||
"""
|
||||
Logs to the provided handler only.
|
||||
@@ -139,13 +141,16 @@ def get_divider_line(c, message=None, length=78, indent=3):
|
||||
return c * indent + " " + message
|
||||
|
||||
|
||||
def prefix_multilines(text, prefix=": "):
|
||||
def prefix_multilines(text, prefix=u": "):
|
||||
# type: (Union[unicode, bytes], unicode) -> unicode
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
lines = text.splitlines()
|
||||
if not lines:
|
||||
return ""
|
||||
return u""
|
||||
|
||||
if len(lines) == 1:
|
||||
return lines[0]
|
||||
return to_unicode(lines[0])
|
||||
|
||||
return lines[0] + "\n" + "\n".join(map(lambda line: prefix + line,
|
||||
lines[1:]))
|
||||
return to_unicode(lines[0]) + u"\n" + u"\n".join(map(lambda line: prefix + to_unicode(line),
|
||||
lines[1:]))
|
||||
@@ -201,8 +201,7 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
error_callback (function): A callback to invoke after the call of an implementation resulted in an exception.
|
||||
Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin
|
||||
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
|
||||
initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status
|
||||
is determined be presence of injected ``_identifier`` property.
|
||||
initialized (boolean): Ignored.
|
||||
"""
|
||||
|
||||
if not isinstance(types, (list, tuple)):
|
||||
@@ -216,7 +215,7 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
|
||||
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
|
||||
for plugin in plugins:
|
||||
if initialized and not hasattr(plugin, "_identifier"):
|
||||
if not hasattr(plugin, "_identifier"):
|
||||
continue
|
||||
|
||||
if hasattr(plugin, method):
|
||||
@@ -226,7 +225,7 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
|
||||
if callback:
|
||||
callback(plugin._identifier, plugin, result)
|
||||
except Exception as exc:
|
||||
logger.exception("Error while calling plugin %s" % plugin._identifier)
|
||||
logger.exception("Error while calling plugin %s" % plugin._identifier, extra=dict(plugin=plugin._identifier))
|
||||
if error_callback:
|
||||
error_callback(plugin._identifier, plugin, exc)
|
||||
|
||||
@@ -302,6 +301,17 @@ class PluginSettings(SubSettings):
|
||||
.. method:: set_boolean(path, value, force=False)
|
||||
|
||||
Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it.
|
||||
|
||||
.. method:: save(force=False, trigger_event=False)
|
||||
|
||||
Saves the settings to ``config.yaml`` if there are active changes. If ``force`` is set to ``True`` the settings
|
||||
will be saved even if there are no changes. Settings ``trigger_event`` to ``True`` will cause a ``SettingsUpdated``
|
||||
:ref:`event <sec-events-available_events-settings>` to get triggered.
|
||||
|
||||
:param force: Force saving to ``config.yaml`` even if there are no changes.
|
||||
:type force: boolean
|
||||
:param trigger_event: Trigger the ``SettingsUpdated`` :ref:`event <sec-events-available_events-settings>` on save.
|
||||
:type trigger_event: boolean
|
||||
"""
|
||||
|
||||
def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
|
||||
|
||||
@@ -794,7 +794,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
def get_ui_custom_etag(self):
|
||||
"""
|
||||
Allows to use a custom way to calculate the ETag, instead of the default method (hashing
|
||||
OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value).
|
||||
OctoPrint's version, tracked file paths and ``LastModified`` value).
|
||||
|
||||
Returns:
|
||||
str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
|
||||
@@ -1391,8 +1391,9 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def is_blueprint_protected(self):
|
||||
"""
|
||||
Whether a valid API key is needed to access the blueprint (the default) or not. Note that this only restricts
|
||||
access to the blueprint's dynamic methods, static files are always accessible without API key.
|
||||
Whether a login session is needed to access the blueprint if the forcelogin plugin is enabled or not. Requiring
|
||||
a session is the default. Note that this only restricts access to the blueprint's dynamic methods, static files
|
||||
are always accessible.
|
||||
"""
|
||||
|
||||
return True
|
||||
|
||||
@@ -25,7 +25,7 @@ from collections import OrderedDict
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag
|
||||
from octoprint.util import utmify, count
|
||||
from octoprint.util import utmify, count, monotonic_time
|
||||
from flask_babel import gettext
|
||||
from octoprint import __version__ as OCTOPRINT_VERSION
|
||||
|
||||
@@ -377,10 +377,10 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
url = config["url"]
|
||||
try:
|
||||
start = time.time()
|
||||
start = monotonic_time()
|
||||
r = requests.get(url, timeout=30)
|
||||
r.raise_for_status()
|
||||
self._logger.info("Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start))
|
||||
self._logger.info("Loaded channel {} from {} in {:.2}s".format(key, config["url"], monotonic_time() - start))
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Could not fetch channel {} from {}".format(key, config["url"]))
|
||||
|
||||
@@ -361,7 +361,11 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
|
||||
with self._keys_lock:
|
||||
for user_id, data in self._keys.items():
|
||||
if any(filter(lambda x: x.api_key == api_key, data)):
|
||||
return self._user_manager.findUser(userid=user_id)
|
||||
if self._user_manager.enabled:
|
||||
return self._user_manager.findUser(userid=user_id)
|
||||
elif user_id == "_admin" or user_id == "dummy":
|
||||
# dummy = backwards compatible
|
||||
return self._user_manager.anonymous_user_factory()
|
||||
return None
|
||||
|
||||
def _api_keys_for_user(self, user_id):
|
||||
|
||||
@@ -634,6 +634,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
|
||||
if exclude is None:
|
||||
exclude = []
|
||||
|
||||
if "timelapse" in exclude:
|
||||
exclude.append("timelapse_tmp")
|
||||
|
||||
configfile = settings._configfile
|
||||
basedir = settings._basedir
|
||||
|
||||
|
||||
@@ -170,10 +170,6 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardPreventSettingsRefreshDialog = function() {
|
||||
return self.active;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.onlinecheck && response.corewizard.details.onlinecheck.required;
|
||||
};
|
||||
@@ -252,10 +248,6 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardPreventSettingsRefreshDialog = function() {
|
||||
return self.active;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.pluginblacklist && response.corewizard.details.pluginblacklist.required;
|
||||
};
|
||||
|
||||
@@ -569,9 +569,8 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
"""
|
||||
|
||||
import socket
|
||||
import time
|
||||
|
||||
if alive and self._ssdp_last_notify + self._ssdp_notify_timeout > time.time():
|
||||
if alive and self._ssdp_last_notify + self._ssdp_notify_timeout > octoprint.util.monotonic_time():
|
||||
# we just sent an alive, no need to send another one now
|
||||
return
|
||||
|
||||
@@ -610,7 +609,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self._ssdp_last_notify = time.time()
|
||||
self._ssdp_last_notify = octoprint.util.monotonic_time()
|
||||
|
||||
def _ssdp_monitor(self, timeout=5):
|
||||
"""
|
||||
|
||||
@@ -12,8 +12,8 @@ from octoprint.util.version import get_octoprint_version_string, is_released_oct
|
||||
from flask import jsonify
|
||||
from flask_babel import gettext
|
||||
|
||||
SENTRY_URL_SERVER = "https://827d1f11ccda4b31b924f29aaacab493@sentry.io/1373987"
|
||||
SENTRY_URL_COREUI = "https://30bdc39d2248444c8bc01484f38c9444@sentry.io/1374096"
|
||||
SENTRY_URL_SERVER = "https://4069187705ab4e76921eb19db2e9ccbb@sentry.io/1373987"
|
||||
SENTRY_URL_COREUI = "https://a4ab48f27daf4c129392b78be15412b8@sentry.io/1374096"
|
||||
|
||||
SETTINGS_DEFAULTS = dict(enabled=False,
|
||||
enabled_unreleased=False,
|
||||
@@ -21,6 +21,40 @@ SETTINGS_DEFAULTS = dict(enabled=False,
|
||||
url_server=SENTRY_URL_SERVER,
|
||||
url_coreui=SENTRY_URL_COREUI)
|
||||
|
||||
import serial
|
||||
import requests.exceptions
|
||||
import errno
|
||||
import octoprint.util.avr_isp.ispBase
|
||||
import tornado.websocket
|
||||
|
||||
IGNORED_EXCEPTIONS = [
|
||||
# serial exceptions in octoprint.util.comm
|
||||
(serial.SerialException, lambda exc, logger, plugin: logger == "octoprint.util.comm"),
|
||||
|
||||
# isp errors during port auto detection in octoprint.util.comm
|
||||
(octoprint.util.avr_isp.ispBase.IspError, lambda exc, logger, plugin: logger == "octoprint.util.comm"),
|
||||
|
||||
# IOErrors of any kind due to a full file system
|
||||
(IOError, lambda exc, logger, plugin: getattr(exc, "errno") and exc.errno in (getattr(errno, "ENOSPC"),)),
|
||||
|
||||
# RequestExceptions of any kind
|
||||
requests.exceptions.RequestException,
|
||||
|
||||
# Tornado WebSocketErrors of any kind
|
||||
tornado.websocket.WebSocketError
|
||||
]
|
||||
|
||||
try:
|
||||
# noinspection PyUnresolvedReferences
|
||||
from octoprint.plugins.backup import InsufficientSpace
|
||||
|
||||
# if the backup plugin is enabled, ignore InsufficientSpace errors from it as well
|
||||
IGNORED_EXCEPTIONS.append(InsufficientSpace)
|
||||
|
||||
del InsufficientSpace
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
class ErrorTrackingPlugin(octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
@@ -94,13 +128,67 @@ def _enable_errortracking():
|
||||
|
||||
if _is_enabled(enabled, enabled_unreleased):
|
||||
import sentry_sdk
|
||||
from octoprint.plugin import plugin_manager
|
||||
|
||||
def _before_send(event, hint):
|
||||
if not "exc_info" in hint:
|
||||
# we only want exceptions
|
||||
return None
|
||||
|
||||
handled = True
|
||||
logger = event.get("logger", "")
|
||||
plugin = event.get("extra", dict()).get("plugin", None)
|
||||
|
||||
for ignore in IGNORED_EXCEPTIONS:
|
||||
if isinstance(ignore, tuple):
|
||||
ignored_exc, matcher = ignore
|
||||
else:
|
||||
ignored_exc = ignore
|
||||
matcher = lambda *args: True
|
||||
|
||||
exc = hint["exc_info"][1]
|
||||
if isinstance(exc, ignored_exc) and matcher(exc, logger, plugin):
|
||||
# exception ignored for logger
|
||||
return None
|
||||
|
||||
elif isinstance(ignore, type):
|
||||
if isinstance(hint["exc_info"][1], ignore):
|
||||
# exception ignored
|
||||
return None
|
||||
|
||||
if event.get("exception") and event["exception"].get("values"):
|
||||
handled = not any(map(lambda x: x.get("mechanism") and x["mechanism"].get("handled", True) == False,
|
||||
event["exception"]["values"]))
|
||||
|
||||
if handled:
|
||||
# error is handled, restrict further based on logger
|
||||
if logger != "" and not (logger.startswith("octoprint.") or logger.startswith("tornado.")):
|
||||
# we only want errors logged by loggers octoprint.* or tornado.*
|
||||
return None
|
||||
|
||||
if logger.startswith("octoprint.plugins."):
|
||||
plugin_id = logger.split(".")[2]
|
||||
plugin_info = plugin_manager().get_plugin_info(plugin_id)
|
||||
if plugin_info is None or not plugin_info.bundled:
|
||||
# we only want our active bundled plugins
|
||||
return None
|
||||
|
||||
if plugin is not None:
|
||||
plugin_info = plugin_manager().get_plugin_info(plugin)
|
||||
if plugin_info is None or not plugin_info.bundled:
|
||||
# we only want our active bundled plugins
|
||||
return None
|
||||
|
||||
return event
|
||||
|
||||
sentry_sdk.init(url_server,
|
||||
release=version)
|
||||
release=version,
|
||||
before_send=_before_send)
|
||||
|
||||
with sentry_sdk.configure_scope() as scope:
|
||||
scope.user = dict(id=unique_id)
|
||||
|
||||
logging.getLogger("octoprint.plugin.errortracking").info("Initialized error tracking")
|
||||
logging.getLogger("octoprint.plugins.errortracking").info("Initialized error tracking")
|
||||
_enabled = True
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
/*! @sentry/browser 4.5.1 (6a390acf) | https://github.com/getsentry/sentry-javascript */
|
||||
var Sentry=function(t){"use strict";var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,n)};function n(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var r,o,i=function(){return(i=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t}).apply(this,arguments)};function s(t,e,n,r){return new(n||(n=Promise))(function(o,i){function s(t){try{u(r.next(t))}catch(t){i(t)}}function a(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){t.done?o(t.value):new n(function(e){e(t.value)}).then(s,a)}u((r=r.apply(t,e||[])).next())})}function a(t,e){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=e.call(t,s)}catch(t){i=[6,t],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function u(t){var e="function"==typeof Symbol&&t[Symbol.iterator],n=0;return e?e.call(t):{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}}}function c(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function l(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(c(arguments[e]));return t}function p(t){switch(Object.prototype.toString.call(t)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return t instanceof Error}}function f(t){return"[object ErrorEvent]"===Object.prototype.toString.call(t)}function h(t){return"[object DOMError]"===Object.prototype.toString.call(t)}function d(t){return void 0===t}function v(t){return"function"==typeof t}function g(t){return"[object String]"===Object.prototype.toString.call(t)}function y(t){return"[object Object]"===Object.prototype.toString.call(t)}function m(t){return t!=t}function b(){return"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}}function E(){var t=b(),e=t.crypto||t.msCrypto;if(void 0!==e&&e.getRandomValues){var n=new Uint16Array(8);e.getRandomValues(n),n[3]=4095&n[3]|16384,n[4]=16383&n[4]|32768;var r=function(t){for(var e=t.toString(16);e.length<4;)e="0"+e;return e};return r(n[0])+r(n[1])+r(n[2])+r(n[3])+r(n[4])+r(n[5])+r(n[6])+r(n[7])}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(t){var e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function x(t){var e,n,r,o,i,s=[];if(!t||!t.tagName)return"";if(s.push(t.tagName.toLowerCase()),t.id&&s.push("#"+t.id),(e=t.className)&&g(e))for(n=e.split(/\s+/),i=0;i<n.length;i++)s.push("."+n[i]);var a=["type","name","title","alt"];for(i=0;i<a.length;i++)r=a[i],(o=t.getAttribute(r))&&s.push("["+r+'="'+o+'"]');return s.join("")}function _(t){if(!t)return{};var e=t.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)return{};var n=e[6]||"",r=e[8]||"";return{host:e[4],path:e[5],protocol:e[2],relative:e[5]+n+r}}function S(t){if(t.message)return t.message;if(t.exception&&t.exception.values&&t.exception.values[0]){var e=t.exception.values[0];return e.type&&e.value?e.type+": "+e.value:e.type||e.value||t.event_id||"<unknown>"}return t.event_id||"<unknown>"}function w(t){var e=b();if(!("console"in e))return t();var n=e.console,r={};["debug","info","warn","error","log"].forEach(function(t){t in e.console&&n[t].__sentry__&&(r[t]=n[t].__sentry_wrapped__,n[t]=n[t].__sentry_original__)});var o=t();return Object.keys(r).forEach(function(t){n[t]=r[t]}),o}function k(t,e){return void 0===e&&(e=0),0!==e&&g(t)?t.length<=e?t:t.substr(0,e)+"...":t}function O(t,e){if(!Array.isArray(t))return"";for(var n=[],r=0;r<t.length;r++){var o=t[r];try{n.push(String(o))}catch(t){n.push("[value cannot be serialized]")}}return n.join(e)}function j(t,e){return!(Line truncated
|
||||
//# sourceMappingURL=bundle.min.js.map
|
||||
/*! @sentry/browser 5.0.5 (913eafc4) | https://github.com/getsentry/sentry-javascript */
|
||||
var Sentry=function(n){"use strict";var t=function(n,r){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,t){n.__proto__=t}||function(n,t){for(var r in t)t.hasOwnProperty(r)&&(n[r]=t[r])})(n,r)};function r(n,r){function i(){this.constructor=n}t(n,r),n.prototype=null===r?Object.create(r):(i.prototype=r.prototype,new i)}var i,e,o,u=function(){return(u=Object.assign||function(n){for(var t,r=1,i=arguments.length;r<i;r++)for(var e in t=arguments[r])Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e]);return n}).apply(this,arguments)};function c(n,t,r,i){return new(r||(r=Promise))(function(e,o){function u(n){try{s(i.next(n))}catch(n){o(n)}}function c(n){try{s(i.throw(n))}catch(n){o(n)}}function s(n){n.done?e(n.value):new r(function(t){t(n.value)}).then(u,c)}s((i=i.apply(n,t||[])).next())})}function s(n,t){var r,i,e,o,u={label:0,sent:function(){if(1&e[0])throw e[1];return e[1]},trys:[],ops:[]};return o={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function c(o){return function(c){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;u;)try{if(r=1,i&&(e=2&o[0]?i.return:o[0]?i.throw||((e=i.return)&&e.call(i),0):i.next)&&!(e=e.call(i,o[1])).done)return e;switch(i=0,e&&(o=[2&o[0],e.value]),o[0]){case 0:case 1:e=o;break;case 4:return u.label++,{value:o[1],done:!1};case 5:u.label++,i=o[1],o=[0];continue;case 7:o=u.ops.pop(),u.trys.pop();continue;default:if(!(e=(e=u.trys).length>0&&e[e.length-1])&&(6===o[0]||2===o[0])){u=0;continue}if(3===o[0]&&(!e||o[1]>e[0]&&o[1]<e[3])){u.label=o[1];break}if(6===o[0]&&u.label<e[1]){u.label=e[1],e=o;break}if(e&&u.label<e[2]){u.label=e[2],u.ops.push(o);break}e[2]&&u.ops.pop(),u.trys.pop();continue}o=t.call(n,u)}catch(n){o=[6,n],i=0}finally{r=e=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,c])}}}function f(n,t){var r="function"==typeof Symbol&&n[Symbol.iterator];if(!r)return n;var i,e,o=r.call(n),u=[];try{for(;(void 0===t||t-- >0)&&!(i=o.next()).done;)u.push(i.value)}catch(n){e={error:n}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return u}function a(){for(var n=[],t=0;t<arguments.length;t++)n=n.concat(f(arguments[t]));return n}function h(n){switch(Object.prototype.toString.call(n)){case"[object Error]":case"[object Exception]":case"[object DOMException]":return!0;default:return n instanceof Error}}function v(n){return"[object ErrorEvent]"===Object.prototype.toString.call(n)}function l(n){return"[object DOMError]"===Object.prototype.toString.call(n)}function d(n){return"[object String]"===Object.prototype.toString.call(n)}function p(n){return null===n||"object"!=typeof n&&"function"!=typeof n}function m(n){return"[object Object]"===Object.prototype.toString.call(n)}function y(n){return Boolean(n&&n.then&&"function"==typeof n.then)}!function(n){n[n.None=0]="None",n[n.Error=1]="Error",n[n.Debug=2]="Debug",n[n.Verbose=3]="Verbose"}(i||(i={})),(e=n.Severity||(n.Severity={})).Fatal="fatal",e.Error="error",e.Warning="warning",e.Log="log",e.Info="info",e.Debug="debug",e.Critical="critical",function(n){n.fromString=function(t){switch(t){case"debug":return n.Debug;case"info":return n.Info;case"warn":case"warning":return n.Warning;case"error":return n.Error;case"fatal":return n.Fatal;case"critical":return n.Critical;case"log":default:return n.Log}}}(n.Severity||(n.Severity={})),(o=n.Status||(n.Status={})).Unknown="unknown",o.Skipped="skipped",o.Success="success",o.RateLimit="rate_limit",o.Invalid="invalid",o.Failed="failed",function(n){n.fromHttpCode=function(t){return t>=200&&t<300?n.Success:429===t?n.RateLimit:t>=400&&t<500?n.Invalid:t>=500?n.Failed:n.Unknown}}(n.Status||(n.Status={}));var b={};function w(){return"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0)?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:b}function g(){var n=w(),t=n.crypto||n.msCrypto;if(void 0!==t&&t.getRandomValues){var r=new Uint16Array(8);t.getRandomValues(r),r[3]=4095&r[3]|16384,r[4]=16383&r[4]|32768;var i=function(n){for(var t=n.toString(16);t.length<4;)t="0"+t;return t};return i(r[0])+i(r[1])+i(r[2])+i(r[3])+i(r[4])+i(r[5])+i(r[6])+i(r[7])}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(n){var t=16*Math.random()|0;return("x"===n?t:3&t|8).toString(16)})}function E(n){var t,r,i,e,o,u=[];if(!n||!n.tagName)return"";if(u.push(n.tagName.toLowerCase()),n.id&&u.push("#"+n.id),(t=n.className)&&d(t))for(r=t.split(/\s+/),o=0;o<r.length;o++)u.push("."+r[o]);var c=["type","name","title","alt"];for(o=0;o<c.length;o++)i=c[o],(e=n.getAttribute(i))&&u.push("["+i+'="'+e+'"]');return u.join("")}function x(n){if(!n)return{};var t=n.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!t)return{};var r=t[6]||"",i=t[8]||"";return{host:t[4],path:t[5],protocol:t[2],relative:t[5]+r+i}}function j(n){if(n.message)return n.message;if(n.exception&&n.exception.values&&n.excepLine truncated
|
||||
@@ -7,7 +7,15 @@
|
||||
|
||||
Sentry.init({
|
||||
dsn: errortracking_url_coreui,
|
||||
release: VERSION
|
||||
release: VERSION,
|
||||
whitelistUrls: [
|
||||
// only include static assets
|
||||
"/static/"
|
||||
],
|
||||
blacklistUrls: [
|
||||
// exclude third party plugins
|
||||
"/static/webassets/packed_plugins.js"
|
||||
]
|
||||
});
|
||||
Sentry.configureScope(function (scope) {
|
||||
scope.setUser({"id": errortracking_unique_id});
|
||||
|
||||
@@ -31,10 +31,11 @@ import requests
|
||||
import re
|
||||
import os
|
||||
import copy
|
||||
import dateutil.parser
|
||||
import time
|
||||
import threading
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
_DATA_FORMAT_VERSION = "v2"
|
||||
|
||||
|
||||
@@ -721,7 +722,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if additional_args:
|
||||
args.append(additional_args)
|
||||
|
||||
return self._pip_caller.execute(*args)
|
||||
kwargs = dict(env=dict(PYTHONWARNINGS="ignore:DEPRECATION::pip._internal.cli.base_command"))
|
||||
|
||||
return self._pip_caller.execute(*args, **kwargs)
|
||||
|
||||
def _log_message(self, *lines):
|
||||
self._log(lines, prefix="*", stream="message")
|
||||
@@ -902,7 +905,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
key = notice["plugin"]
|
||||
|
||||
try:
|
||||
parsed_date = dateutil.parser.parse(notice["date"])
|
||||
# Jekyll turns "%Y-%m-%d %H:%M:%SZ" into "%Y-%m-%d %H:%M:%S +0000", so be sure to ignore "+0000"
|
||||
#
|
||||
# Being able to use dateutil here would make things way easier but sadly that can no longer get
|
||||
# installed (from source) under OctoPi 0.14 due to its setuptools-scm dependency, so we have to do
|
||||
# without it for now until we can drop support for OctoPi 0.14.
|
||||
parsed_date = datetime.strptime(notice["date"], "%Y-%m-%d %H:%M:%S +0000")
|
||||
notice["timestamp"] = parsed_date.timetuple()
|
||||
except Exception as e:
|
||||
self._logger.warning("Error while parsing date {!r} for plugin notice "
|
||||
@@ -928,7 +936,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
reconnect_hooks.extend(filter(lambda x: isinstance(x, basestring), result))
|
||||
except Exception:
|
||||
self._logger.exception("Error while retrieving additional hooks for which a "
|
||||
"reconnect is required from plugin {name}".format(**locals()))
|
||||
"reconnect is required from plugin {name}".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
return reconnect_hooks
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
@@ -32,7 +32,7 @@ $(function() {
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
5
|
||||
0
|
||||
);
|
||||
|
||||
self.repositoryplugins = new ItemListHelper(
|
||||
|
||||
@@ -1,21 +1,32 @@
|
||||
table {
|
||||
th, td {
|
||||
&.settings_plugin_plugin_manager_plugins_name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
}
|
||||
#settings_plugin_pluginmanager_pluginlist {
|
||||
display: block;
|
||||
width: auto;
|
||||
height: 500px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: scroll;
|
||||
padding-right: 2px;
|
||||
margin-bottom: 1em;
|
||||
|
||||
&.settings_plugin_plugin_manager_plugins_actions {
|
||||
text-align: center;
|
||||
width: 80px;
|
||||
table {
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
th, td {
|
||||
&.settings_plugin_plugin_manager_plugins_name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
&.disabled {
|
||||
color: #ccc;
|
||||
cursor: default;
|
||||
&.settings_plugin_plugin_manager_plugins_actions {
|
||||
text-align: center;
|
||||
width: 80px;
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
|
||||
&.disabled {
|
||||
color: #ccc;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,42 +37,33 @@
|
||||
|
||||
<h3>{{ _('Installed Plugins') }}</h3>
|
||||
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_plugin_manager_plugins_name">{{ _('Name') }}</th>
|
||||
<th class="settings_plugin_plugin_manager_plugins_actions">{{ _('Actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: plugins.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_plugin_manager_plugins_name">
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="fa fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fa fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin') }}" data-bind="visible: notifications && notifications.length"></i> <i class="fa fa-ban" title="{{ _('This plugin is blacklisted') }}" data-bind="visible: blacklisted"></i></div>
|
||||
<div data-bind="visible: notifications && notifications.length"><a href="javascript:void(0)" class="text-error" style="text-decoration: underline" data-bind="click: function() { $root.showPluginNotifications($data) }, text: $root.showPluginNotificationsLinkText($data)"></a></div>
|
||||
<div><small class="muted" data-bind="text: description"> </small></div>
|
||||
<div data-bind="css: {muted: !enabled}">
|
||||
<small data-bind="visible: url"><i class="fa fa-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small> </small>
|
||||
</div>
|
||||
</td>
|
||||
<td class="settings_plugin_plugin_manager_plugins_actions">
|
||||
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a> | <a href="#" class="fa fa-trash-o" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: plugins.currentPage() === 0}"><a href="#" data-bind="click: plugins.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: plugins.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.plugins.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.plugins.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: plugins.currentPage() === plugins.lastPage()}"><a href="#" data-bind="click: plugins.nextPage">»</a></li>
|
||||
</ul>
|
||||
<div id="settings_plugin_pluginmanager_pluginlist">
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_plugin_manager_plugins_name">{{ _('Name') }}</th>
|
||||
<th class="settings_plugin_plugin_manager_plugins_actions">{{ _('Actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: plugins.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_plugin_manager_plugins_name">
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="fa fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fa fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin') }}" data-bind="visible: notifications && notifications.length"></i> <i class="fa fa-ban" title="{{ _('This plugin is blacklisted') }}" data-bind="visible: blacklisted"></i></div>
|
||||
<div data-bind="visible: notifications && notifications.length"><a href="javascript:void(0)" class="text-error" style="text-decoration: underline" data-bind="click: function() { $root.showPluginNotifications($data) }, text: $root.showPluginNotificationsLinkText($data)"></a></div>
|
||||
<div><small class="muted" data-bind="text: description"> </small></div>
|
||||
<div data-bind="css: {muted: !enabled}">
|
||||
<small data-bind="visible: url"><i class="fa fa-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small> </small>
|
||||
</div>
|
||||
</td>
|
||||
<td class="settings_plugin_plugin_manager_plugins_actions">
|
||||
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a> | <a href="#" class="fa fa-trash-o" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
|
||||
|
||||
@@ -9,6 +9,7 @@ import octoprint.plugin
|
||||
from octoprint.events import Events
|
||||
from octoprint.access import USER_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
from .checks.firmware_unsafe import FirmwareUnsafeChecks
|
||||
|
||||
@@ -78,19 +79,24 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
def on_gcode_received(self, comm_instance, line, *args, **kwargs):
|
||||
if self._scan_received:
|
||||
self._run_checks("received", line)
|
||||
self._run_checks("received", to_unicode(line, errors="replace"))
|
||||
return line
|
||||
|
||||
##~~ Firmware info hook handler
|
||||
|
||||
def on_firmware_info_received(self, comm_instance, firmware_name, firmware_data):
|
||||
self._run_checks("m115", firmware_name, firmware_data)
|
||||
self._run_checks("m115",
|
||||
to_unicode(firmware_name, errors="replace"),
|
||||
dict((to_unicode(key, errors="replace"), to_unicode(value, errors="replace"))
|
||||
for key, value in firmware_data.items()))
|
||||
self._scan_received = False
|
||||
|
||||
##~~ Firmware capability hook handler
|
||||
|
||||
def on_firmware_cap_received(self, comm_instance, cap, enabled, all_caps):
|
||||
self._run_checks("cap", cap, enabled)
|
||||
self._run_checks("cap",
|
||||
to_unicode(cap, errors="replace"),
|
||||
enabled)
|
||||
|
||||
##~~ Additional permissions hook handler
|
||||
|
||||
|
||||
@@ -140,7 +140,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
try:
|
||||
hook_checks = hook()
|
||||
except Exception:
|
||||
self._logger.exception("Error while retrieving update information from plugin {name}".format(**locals()))
|
||||
self._logger.exception("Error while retrieving update information "
|
||||
"from plugin {name}".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
else:
|
||||
for key, default_config in hook_checks.items():
|
||||
if key in effective_configs or key == "octoprint":
|
||||
@@ -941,7 +943,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
elif restart_type == "environment":
|
||||
restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||
|
||||
if restart_command is not None:
|
||||
if restart_command:
|
||||
self._send_client_message("restarting", dict(restart_type=restart_type, results=target_results))
|
||||
try:
|
||||
self._perform_restart(restart_command)
|
||||
|
||||
@@ -1 +1 @@
|
||||
td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
|
||||
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
|
||||
@@ -85,7 +85,7 @@ $(function() {
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
5
|
||||
0
|
||||
);
|
||||
|
||||
self.availableAndPossible = ko.pureComputed(function() {
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
#settings_plugin_softwareupdate_updatelist {
|
||||
display: block;
|
||||
width: auto;
|
||||
height: 500px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: scroll;
|
||||
padding-right: 2px;
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
|
||||
td.settings_plugin_softwareupdate_column_update {
|
||||
width: 16px;
|
||||
}
|
||||
|
||||
@@ -39,41 +39,26 @@
|
||||
|
||||
<h3>{{ _('Current versions') }}</h3>
|
||||
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<tbody data-bind="foreach: versions.paginatedItems">
|
||||
<tr data-bind="attr: {title: displayName}">
|
||||
<td class="settings_plugin_softwareupdate_column_update">
|
||||
<span data-bind="invisible: !updateAvailable"><i class="fa fa-bell-o" title="{{ _('Update available') }}"></i></span>
|
||||
</td>
|
||||
<td class="settings_plugin_softwareupdate_column_information">
|
||||
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$data]) }, visible: updateAvailable && updatePossible" class="btn btn-primary pull-right">{{ _('Update') }}</a>
|
||||
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fa fa-exclamation-triangle" data-bind="css: {'fa-unlink': !online && information && information.needs_online, 'fa-exclamation-triangle': !(!online && information && information.needs_online)}, attr: {title: $root.iconTitleForEntry($data)}"></i></span><br>
|
||||
<small class="muted">
|
||||
<span class="line">{{ _('Installed:') }} <span data-bind="text: information.local.name"></span></span>
|
||||
<span class="line">{{ _('Available:') }} <span data-bind="text: information.remote.name"></span></span>
|
||||
<span class="line" data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
|
||||
<span class="line text-error" data-bind="visible: error, text: $root.errorTextForEntry($data)"></span>
|
||||
</small>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: versions.currentPage() === 0}">
|
||||
<a href="#" data-bind="click: versions.prevPage">«</a>
|
||||
</li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: versions.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.versions.currentPage(), disabled: $data.number === -1 }">
|
||||
<a href="#" data-bind="text: $data.text, click: function() { $root.versions.changePage($data.number); }"></a>
|
||||
</li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: versions.currentPage() === versions.lastPage()}">
|
||||
<a href="#" data-bind="click: versions.nextPage">»</a>
|
||||
</li>
|
||||
</ul>
|
||||
<div id="settings_plugin_softwareupdate_updatelist">
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<tbody data-bind="foreach: versions.paginatedItems">
|
||||
<tr data-bind="attr: {title: displayName}">
|
||||
<td class="settings_plugin_softwareupdate_column_update">
|
||||
<span data-bind="invisible: !updateAvailable"><i class="fa fa-bell-o" title="{{ _('Update available') }}"></i></span>
|
||||
</td>
|
||||
<td class="settings_plugin_softwareupdate_column_information">
|
||||
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$data]) }, visible: updateAvailable && updatePossible" class="btn btn-primary pull-right">{{ _('Update') }}</a>
|
||||
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fa fa-exclamation-triangle" data-bind="css: {'fa-unlink': !online && information && information.needs_online, 'fa-exclamation-triangle': !(!online && information && information.needs_online)}, attr: {title: $root.iconTitleForEntry($data)}"></i></span><br>
|
||||
<small class="muted">
|
||||
<span class="line">{{ _('Installed:') }} <span data-bind="text: information.local.name"></span></span>
|
||||
<span class="line">{{ _('Available:') }} <span data-bind="text: information.remote.name"></span></span>
|
||||
<span class="line" data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank" rel="noreferrer noopener"></a></span>
|
||||
<span class="line text-error" data-bind="visible: error, text: $root.errorTextForEntry($data)"></span>
|
||||
</small>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.update(); }, enable: enableUpdate, css: {disabled: !enableUpdate}"><i class="fa fa-spinner fa-spin" data-bind="visible: updateInProgress"></i> {{ _('Update all') }}</button>
|
||||
|
||||
@@ -87,7 +87,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
|
||||
|
||||
logger.debug("Target: %s, executing pip install %s" % (target, install_arg))
|
||||
pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"]
|
||||
pip_kwargs = dict()
|
||||
pip_kwargs = dict(env=dict(PYTHONWARNINGS="ignore:DEPRECATION::pip._internal.cli.base_command"))
|
||||
if pip_working_directory is not None:
|
||||
pip_kwargs.update(cwd=pip_working_directory)
|
||||
|
||||
|
||||
@@ -29,4 +29,5 @@ def execute(command, cwd=None, evaluate_returncode=True, **kwargs):
|
||||
if evaluate_returncode and p.returncode != 0:
|
||||
raise ScriptError(p.returncode, p.stdout.text, p.stderr.text)
|
||||
|
||||
return p.returncode, p.stdout.text, p.stderr.text
|
||||
if not do_async:
|
||||
return p.returncode, p.stdout.text, p.stderr.text
|
||||
@@ -44,10 +44,6 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardPreventSettingsRefreshDialog = function() {
|
||||
return self.active();
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.tracking && response.tracking.required;
|
||||
};
|
||||
|
||||
@@ -23,7 +23,7 @@ from serial import SerialTimeoutException
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.plugin import plugin_manager
|
||||
from octoprint.util import RepeatedTimer, monotonic_time, to_bytes
|
||||
from octoprint.util import RepeatedTimer, monotonic_time, to_bytes, to_unicode
|
||||
|
||||
from typing import Any
|
||||
|
||||
@@ -54,7 +54,7 @@ class VirtualPrinter(object):
|
||||
self._seriallog.addHandler(seriallog_handler)
|
||||
self._seriallog.setLevel(logging.INFO)
|
||||
|
||||
self._seriallog.info("-"*78)
|
||||
self._seriallog.info(u"-"*78)
|
||||
|
||||
self._read_timeout = read_timeout
|
||||
self._write_timeout = write_timeout
|
||||
@@ -93,6 +93,8 @@ class VirtualPrinter(object):
|
||||
self.targetTemp = [0.0] * self.temperatureCount
|
||||
self.bedTemp = self._ambient_temperature
|
||||
self.bedTargetTemp = 0.0
|
||||
self.chamberTemp = self._ambient_temperature
|
||||
self.chamberTargetTemp = 0.0
|
||||
self.lastTempAt = monotonic_time()
|
||||
|
||||
self._relative = True
|
||||
@@ -288,12 +290,17 @@ class VirtualPrinter(object):
|
||||
|
||||
try:
|
||||
data = self.incoming.get(timeout=0.01)
|
||||
data = to_bytes(data, encoding="ascii", errors="replace")
|
||||
self.incoming.task_done()
|
||||
except queue.Empty:
|
||||
if self._sendWait and monotonic_time() > next_wait_timeout:
|
||||
self._send("wait")
|
||||
next_wait_timeout = monotonic_time() + self._waitInterval
|
||||
continue
|
||||
except Exception:
|
||||
if self.incoming is None:
|
||||
# just got closed
|
||||
break
|
||||
|
||||
if data is not None:
|
||||
buf += data
|
||||
@@ -313,8 +320,6 @@ class VirtualPrinter(object):
|
||||
self._dont_answer = False
|
||||
continue
|
||||
|
||||
data = data.strip()
|
||||
|
||||
# strip checksum
|
||||
if b"*" in data:
|
||||
checksum = int(data[data.rfind(b"*") + 1:])
|
||||
@@ -380,7 +385,7 @@ class VirtualPrinter(object):
|
||||
|
||||
data += b"\n"
|
||||
|
||||
data = data.decode("ascii").strip()
|
||||
data = to_unicode(data, encoding="ascii", errors="replace").strip()
|
||||
|
||||
if data.startswith("!!DEBUG:") or data.strip() == "!!DEBUG":
|
||||
debug_command = ""
|
||||
@@ -485,6 +490,12 @@ class VirtualPrinter(object):
|
||||
# type: (str) -> None
|
||||
self._parseBedCommand(data, wait=True, support_r=True)
|
||||
|
||||
def _gcode_M141(self, data):
|
||||
self._parseChamberCommand(data)
|
||||
|
||||
def _gcode_M191(self, data):
|
||||
self._parseChamberCommand(data, wait=True, support_r=True)
|
||||
|
||||
# noinspection PyUnusedLocal
|
||||
def _gcode_M105(self, data):
|
||||
# type: (str) -> bool
|
||||
@@ -691,7 +702,7 @@ class VirtualPrinter(object):
|
||||
|
||||
def _gcode_G28(self, data):
|
||||
# type: (str) -> None
|
||||
self._performMove(data)
|
||||
self._home(data)
|
||||
|
||||
def _gcode_G0(self, data):
|
||||
# type: (str) -> None
|
||||
@@ -728,8 +739,8 @@ class VirtualPrinter(object):
|
||||
timeout = 60
|
||||
|
||||
if self._sendBusy and self._busyInterval > 0:
|
||||
until = time.time() + timeout
|
||||
while time.time() < until:
|
||||
until = monotonic_time() + timeout
|
||||
while monotonic_time() < until:
|
||||
time.sleep(self._busyInterval)
|
||||
self._send("busy:processing")
|
||||
else:
|
||||
@@ -1011,6 +1022,12 @@ class VirtualPrinter(object):
|
||||
else:
|
||||
allTempsString = "B:%.2f %s" % (self.bedTemp, allTempsString)
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "hasChamber"]):
|
||||
if includeTarget:
|
||||
allTempsString = "C:%.2f /%.2f %s" % (self.chamberTemp, self.chamberTargetTemp, allTempsString)
|
||||
else:
|
||||
allTempsString = "C:%.2f %s" % (self.chamberTemp, allTempsString)
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "includeCurrentToolInTemps"]):
|
||||
if includeTarget:
|
||||
output = "T:%.2f /%.2f %s" % (self.temp[self.currentExtruder], self.targetTemp[self.currentExtruder], allTempsString)
|
||||
@@ -1020,9 +1037,28 @@ class VirtualPrinter(object):
|
||||
output = allTempsString
|
||||
else:
|
||||
if includeTarget:
|
||||
output = "T:%.2f /%.2f B:%.2f /%.2f" % (self.temp[0], self.targetTemp[0], self.bedTemp, self.bedTargetTemp)
|
||||
t = "T:%.2f /%.2f" % (self.temp[0], self.targetTemp[0])
|
||||
else:
|
||||
output = "T:%.2f B:%.2f" % (self.temp[0], self.bedTemp)
|
||||
t = "T:%.2f" % self.temp[0]
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "hasBed"]):
|
||||
if includeTarget:
|
||||
b = "B:%.2f /%.2f" % (self.bedTemp, self.bedTargetTemp)
|
||||
else:
|
||||
b = "B:%.2f" % self.bedTemp
|
||||
else:
|
||||
b = ""
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "hasChamber"]):
|
||||
if includeTarget:
|
||||
c = "C:%.2f /%.2f" % (self.chamberTemp, self.chamberTargetTemp)
|
||||
else:
|
||||
c = "C:%.2f" % self.chamberTemp
|
||||
else:
|
||||
c = ""
|
||||
|
||||
output = t + " " + b + " " + c
|
||||
output = output.strip()
|
||||
|
||||
output += " @:64\n"
|
||||
return output
|
||||
@@ -1065,6 +1101,9 @@ class VirtualPrinter(object):
|
||||
|
||||
def _parseBedCommand(self, line, wait=False, support_r=False):
|
||||
# type: (str, bool, bool) -> None
|
||||
if not settings().getBoolean(["devel", "virtualPrinter", "hasBed"]):
|
||||
return
|
||||
|
||||
only_wait_if_higher = True
|
||||
try:
|
||||
self.bedTargetTemp = float(re.search(r'S([0-9]+)', line).group(1))
|
||||
@@ -1081,12 +1120,30 @@ class VirtualPrinter(object):
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]):
|
||||
self._send("TargetBed:%d" % self.bedTargetTemp)
|
||||
|
||||
def _parseChamberCommand(self, line, wait=False, support_r=False):
|
||||
if not settings().getBoolean(["devel", "virtualPrinter", "hasChamber"]):
|
||||
return
|
||||
|
||||
only_wait_if_higher = True
|
||||
try:
|
||||
self.chamberTargetTemp = float(re.search('S([0-9]+)', line).group(1))
|
||||
except:
|
||||
if support_r:
|
||||
try:
|
||||
self.chamberTargetTemp = float(re.search('R([0-9]+)', line).group(1))
|
||||
only_wait_if_higher = False
|
||||
except:
|
||||
pass
|
||||
|
||||
if wait:
|
||||
self._waitForHeatup("chamber", only_wait_if_higher)
|
||||
|
||||
def _performMove(self, line):
|
||||
# type: (str) -> None
|
||||
matchX = re.search(r"X([0-9.]+)", line)
|
||||
matchY = re.search(r"Y([0-9.]+)", line)
|
||||
matchZ = re.search(r"Z([0-9.]+)", line)
|
||||
matchE = re.search(r"E([0-9.]+)", line)
|
||||
matchX = re.search(r"X(-?[0-9.]+)", line)
|
||||
matchY = re.search(r"Y(-?[0-9.]+)", line)
|
||||
matchZ = re.search(r"Z(-?[0-9.]+)", line)
|
||||
matchE = re.search(r"E(-?[0-9.]+)", line)
|
||||
matchF = re.search(r"F([0-9.]+)", line)
|
||||
|
||||
duration = 0.0
|
||||
@@ -1177,10 +1234,10 @@ class VirtualPrinter(object):
|
||||
|
||||
def _setPosition(self, line):
|
||||
# type: (str) -> None
|
||||
matchX = re.search(r"X([0-9.]+)", line)
|
||||
matchY = re.search(r"Y([0-9.]+)", line)
|
||||
matchZ = re.search(r"Z([0-9.]+)", line)
|
||||
matchE = re.search(r"E([0-9.]+)", line)
|
||||
matchX = re.search(r"X(-?[0-9.]+)", line)
|
||||
matchY = re.search(r"Y(-?[0-9.]+)", line)
|
||||
matchZ = re.search(r"Z(-?[0-9.]+)", line)
|
||||
matchE = re.search(r"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[self.currentExtruder] = 0
|
||||
@@ -1206,6 +1263,30 @@ class VirtualPrinter(object):
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def _home(self, line):
|
||||
x = y = z = e = None
|
||||
|
||||
if "X" in line:
|
||||
x = True
|
||||
if "Y" in line:
|
||||
y = True
|
||||
if "Z" in line:
|
||||
z = True
|
||||
if "E" in line:
|
||||
e = True
|
||||
|
||||
if x is None and y is None and z is None and e is None:
|
||||
self._lastX = self._lastY = self._lastZ = self._lastE[self.currentExtruder] = 0
|
||||
else:
|
||||
if x:
|
||||
self._lastX = 0
|
||||
if y:
|
||||
self._lastY = 0
|
||||
if z:
|
||||
self._lastZ = 0
|
||||
if e:
|
||||
self._lastE = 0
|
||||
|
||||
def _writeSdFile(self, filename):
|
||||
# type: (str) -> None
|
||||
filename = filename
|
||||
@@ -1303,6 +1384,9 @@ class VirtualPrinter(object):
|
||||
elif heater == "bed":
|
||||
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
|
||||
elif heater == "chamber":
|
||||
test = lambda: self.chamberTemp < self.chamberTargetTemp - delta or (not only_wait_if_higher and self.chamberTemp > self.chamberTargetTemp + delta)
|
||||
output = lambda: "C:%0.2f" % self.chamberTemp
|
||||
else:
|
||||
return
|
||||
|
||||
@@ -1355,6 +1439,7 @@ class VirtualPrinter(object):
|
||||
continue
|
||||
self.temp[i] = simulate(self.temp[i], self.targetTemp[i], self._ambient_temperature)
|
||||
self.bedTemp = simulate(self.bedTemp, self.bedTargetTemp, self._ambient_temperature)
|
||||
self.chamberTemp = simulate(self.chamberTemp, self.chamberTargetTemp, self._ambient_temperature)
|
||||
|
||||
def _processBuffer(self):
|
||||
while self.buffered is not None:
|
||||
@@ -1373,6 +1458,9 @@ class VirtualPrinter(object):
|
||||
|
||||
def write(self, data):
|
||||
# type: (bytes) -> int
|
||||
data = to_bytes(data, errors="replace")
|
||||
u_data = to_unicode(data, errors="replace")
|
||||
|
||||
if self._debug_awol:
|
||||
return len(data)
|
||||
|
||||
@@ -1385,13 +1473,13 @@ class VirtualPrinter(object):
|
||||
return 0
|
||||
|
||||
if b"M112" in data and self._supportM112:
|
||||
self._seriallog.info("<<< {}".format(data.strip().decode("utf-8")))
|
||||
self._seriallog.info("<<< {}".format(u_data))
|
||||
self._kill()
|
||||
return len(data)
|
||||
|
||||
try:
|
||||
written = self.incoming.put(data, timeout=self._write_timeout, partial=True)
|
||||
self._seriallog.info("<<< {}".format(data.strip().decode("utf-8")))
|
||||
self._seriallog.info("<<< {}".format(u_data))
|
||||
return written
|
||||
except queue.Full:
|
||||
self._logger.info("Incoming queue is full, raising SerialTimeoutException")
|
||||
|
||||
@@ -50,7 +50,7 @@ class PrinterInterface(object):
|
||||
valid_tool_regex = re.compile(r"^(tool\d+)$")
|
||||
"""Regex for valid tool identifiers."""
|
||||
|
||||
valid_heater_regex = re.compile(r"^(tool\d+|bed)$")
|
||||
valid_heater_regex = re.compile(r"^(tool\d+|bed|chamber)$")
|
||||
"""Regex for valid heater identifiers."""
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -43,6 +43,8 @@ class PrintTimeEstimator(object):
|
||||
if interval <= 0:
|
||||
interval = 1.0
|
||||
rolling_window = 15 / interval
|
||||
if rolling_window < 1:
|
||||
rolling_window = 1
|
||||
|
||||
# we are happy when one rolling window has been stable
|
||||
countdown = rolling_window
|
||||
@@ -229,14 +231,14 @@ class TimeEstimationHelper(object):
|
||||
|
||||
@property
|
||||
def average_total_rolling(self):
|
||||
if not self._count or self._count < self._rolling_window:
|
||||
if not self._count or self._count < self._rolling_window or not len(self._totals):
|
||||
return -1
|
||||
else:
|
||||
return sum(self._totals) / len(self._totals)
|
||||
|
||||
@property
|
||||
def average_distance(self):
|
||||
if not self._count or self._count < self._rolling_window + 1:
|
||||
if not self._count or self._count < self._rolling_window + 1 or not len(self._distances):
|
||||
return -1
|
||||
else:
|
||||
return sum(self._distances) / len(self._distances)
|
||||
@@ -68,6 +68,9 @@ A printer profile is a ``dict`` of the following structure:
|
||||
* - ``heatedBed``
|
||||
- ``bool``
|
||||
- Whether the printer has a heated bed (``True``) or not (``False``)
|
||||
* - ``heatedChamber``
|
||||
- ``bool``
|
||||
- Whether the printer has a heated chamber (``True``) or not (``False``)
|
||||
* - ``extruder``
|
||||
- ``dict``
|
||||
- Information about the printer's extruders
|
||||
@@ -219,6 +222,7 @@ class PrinterProfileManager(object):
|
||||
custom_box = False
|
||||
),
|
||||
heatedBed = True,
|
||||
heatedChamber = False,
|
||||
extruder=dict(
|
||||
count = 1,
|
||||
offsets = [
|
||||
@@ -510,6 +514,10 @@ class PrinterProfileManager(object):
|
||||
profile["extruder"]["offsets"] = [(0.0, 0.0)]
|
||||
modified = True
|
||||
|
||||
if not "heatedChamber" in profile:
|
||||
profile["heatedChamber"] = False
|
||||
modified = True
|
||||
|
||||
return modified
|
||||
|
||||
def _ensure_valid_profile(self, profile):
|
||||
|
||||
@@ -30,6 +30,7 @@ from octoprint.printer.estimation import PrintTimeEstimator
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import InvariantContainer
|
||||
from octoprint.util import to_unicode
|
||||
from octoprint.util import monotonic_time
|
||||
|
||||
from octoprint.comm.protocol import ProtocolListener, FileAwareProtocolListener, PositionAwareProtocolListener, ProtocolState
|
||||
from octoprint.comm.job import StoragePrintjob, LocalGcodeFilePrintjob, LocalGcodeStreamjob, SDFilePrintjob, CopyJobMixin
|
||||
@@ -125,7 +126,8 @@ class Printer(PrinterInterface,
|
||||
self._logger.info("Using print time estimator provided by {}".format(name))
|
||||
self._estimator_factory = estimator
|
||||
except Exception:
|
||||
self._logger.exception("Error while processing analysis queues from {}".format(name))
|
||||
self._logger.exception("Error while processing analysis queues from {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
#hook card upload
|
||||
self.sd_card_upload_hooks = plugin_manager().get_hooks("octoprint.printer.sdcardupload")
|
||||
@@ -260,7 +262,8 @@ class Printer(PrinterInterface,
|
||||
try:
|
||||
plugin.on_print_progress(storage, filename, progress)
|
||||
except Exception:
|
||||
self._logger.exception("Exception while sending print progress to plugin %s" % plugin._identifier)
|
||||
self._logger.exception("Exception while sending print progress to plugin %s" % plugin._identifier,
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
|
||||
thread = threading.Thread(target=call_plugins, args=(storage, filename, progress))
|
||||
thread.daemon = False
|
||||
@@ -502,23 +505,32 @@ class Printer(PrinterInterface,
|
||||
|
||||
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))
|
||||
raise ValueError("heater must match \"tool[0-9]+\", \"bed\" or \"chamber\": {heater}".format(heater=heater))
|
||||
|
||||
if not isinstance(value, (int, long, float)) or value < 0:
|
||||
raise ValueError("value must be a valid number >= 0: {value}".format(value=value))
|
||||
|
||||
tags = kwargs.get("tags", set()) | {"trigger:printer.set_temperature"}
|
||||
|
||||
if heater.startswith("tool"):
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
extruder_count = printer_profile["extruder"]["count"]
|
||||
shared_nozzle = printer_profile["extruder"]["sharedNozzle"]
|
||||
if extruder_count > 1 and not shared_nozzle:
|
||||
toolNum = int(heater[len("tool"):])
|
||||
self._protocol.set_extruder_temperature(value, tool=toolNum, wait=False)
|
||||
self._protocol.set_extruder_temperature(value,
|
||||
tool=toolNum,
|
||||
wait=False,
|
||||
tags=tags)
|
||||
else:
|
||||
self._protocol.set_extruder_temperature(value, wait=False)
|
||||
self._protocol.set_extruder_temperature(value,
|
||||
wait=False,
|
||||
tags=tags)
|
||||
|
||||
elif heater == "bed":
|
||||
self._protocol.set_bed_temperature(value, wait=False)
|
||||
self._protocol.set_bed_temperature(value,
|
||||
wait=False,
|
||||
tags=tags)
|
||||
|
||||
def set_temperature_offset(self, offsets=None, *args, **kwargs):
|
||||
if offsets is None:
|
||||
@@ -853,7 +865,9 @@ class Printer(PrinterInterface,
|
||||
if result is not None:
|
||||
return result
|
||||
except Exception:
|
||||
self._logger.exception("There was an error running the sd upload hook provided by plugin {}".format(name))
|
||||
self._logger.exception("There was an error running the sd upload "
|
||||
"hook provided by plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
else:
|
||||
# no plugin feels responsible, use the default implementation
|
||||
@@ -1014,12 +1028,15 @@ class Printer(PrinterInterface,
|
||||
original_estimate = None
|
||||
original_estimate_type = None
|
||||
|
||||
# TODO: self._estimator vs self._job.estimator
|
||||
print_time_left, print_time_left_origin = estimator.estimate(progress,
|
||||
print_time,
|
||||
cleaned_print_time,
|
||||
original_estimate,
|
||||
original_estimate_type)
|
||||
try:
|
||||
# TODO: self._estimator vs self._job.estimator
|
||||
print_time_left, print_time_left_origin = estimator.estimate(progress,
|
||||
print_time,
|
||||
cleaned_print_time,
|
||||
original_estimate,
|
||||
original_estimate_type)
|
||||
except Exception:
|
||||
self._logger.exception("Error while estimating print time via {}".format(estimator))
|
||||
|
||||
return self._dict(completion=progress * 100 if progress is not None else None,
|
||||
filepos=pos,
|
||||
@@ -1247,7 +1264,7 @@ class Printer(PrinterInterface,
|
||||
return
|
||||
|
||||
self._sd_files = files
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "printables"})
|
||||
self._sd_filelist_available.set()
|
||||
|
||||
#~~ octoprint.comm.protocol.PositionAwareProtocolListener implementation
|
||||
@@ -1562,7 +1579,7 @@ class StateMonitor(object):
|
||||
self._state_lock = threading.Lock()
|
||||
self._progress_lock = threading.Lock()
|
||||
|
||||
self._last_update = time.time()
|
||||
self._last_update = monotonic_time()
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
@@ -1624,7 +1641,7 @@ class StateMonitor(object):
|
||||
while True:
|
||||
self._change_event.wait()
|
||||
|
||||
now = time.time()
|
||||
now = monotonic_time()
|
||||
delta = now - self._last_update
|
||||
additional_wait_time = self._interval - delta
|
||||
if additional_wait_time > 0:
|
||||
@@ -1633,7 +1650,7 @@ class StateMonitor(object):
|
||||
with self._state_lock:
|
||||
data = self.get_current_data()
|
||||
self._update_callback(data)
|
||||
self._last_update = time.time()
|
||||
self._last_update = monotonic_time()
|
||||
self._change_event.clear()
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Looks like something crashed inside the state update worker. Please report this on the OctoPrint issue tracker (make sure to include logs!)")
|
||||
|
||||
@@ -96,12 +96,10 @@ import octoprint.timelapse
|
||||
import octoprint._version
|
||||
import octoprint.filemanager.analysis
|
||||
import octoprint.slicing
|
||||
from octoprint.server.util import enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, corsRequestHandler, \
|
||||
from octoprint.server.util import loginFromApiKeyRequestHandler, corsRequestHandler, \
|
||||
corsResponseHandler
|
||||
from octoprint.server.util.flask import PreemptiveCache
|
||||
|
||||
UI_API_KEY = ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes))
|
||||
|
||||
VERSION = __version__
|
||||
BRANCH = __branch__
|
||||
DISPLAY_VERSION = __display_version__
|
||||
@@ -166,7 +164,17 @@ def load_user(id):
|
||||
return None
|
||||
|
||||
def load_user_from_request(request):
|
||||
return util.get_user_for_authorization_header(request.headers.get('Authorization'))
|
||||
user = None
|
||||
|
||||
if settings().getBoolean(["accessControl", "trustBasicAuthentication"]):
|
||||
# Basic Authentication?
|
||||
user = util.get_user_for_authorization_header(request.headers.get('Authorization'))
|
||||
|
||||
if settings().getBoolean(["accessControl", "trustRemoteUser"]):
|
||||
# Remote user header?
|
||||
user = util.get_user_for_remote_user_header(request)
|
||||
|
||||
return user
|
||||
|
||||
def unauthorized_user():
|
||||
from flask import abort
|
||||
@@ -178,7 +186,7 @@ def unauthorized_user():
|
||||
|
||||
class Server(object):
|
||||
def __init__(self, settings=None, plugin_manager=None, connectivity_checker=None, environment_detector=None,
|
||||
event_manager=None, host=None, port=None, debug=False, safe_mode=False, allow_root=False,
|
||||
event_manager=None, host=None, port=None, v6_only=False, debug=False, safe_mode=False, allow_root=False,
|
||||
octoprint_daemon=None):
|
||||
self._settings = settings
|
||||
self._plugin_manager = plugin_manager
|
||||
@@ -187,6 +195,7 @@ class Server(object):
|
||||
self._event_manager = event_manager
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._v6_only = v6_only
|
||||
self._debug = debug
|
||||
self._safe_mode = safe_mode
|
||||
self._allow_root = allow_root
|
||||
@@ -208,8 +217,9 @@ class Server(object):
|
||||
if self._settings is None:
|
||||
self._settings = settings()
|
||||
|
||||
self._settings.setBoolean(["server", "incompleteStartup"], True)
|
||||
self._settings.save()
|
||||
if not self._settings.getBoolean(["server", "ignoreIncompleteStartup"]):
|
||||
self._settings.setBoolean(["server", "incompleteStartup"], True)
|
||||
self._settings.save()
|
||||
|
||||
if self._plugin_manager is None:
|
||||
self._plugin_manager = octoprint.plugin.plugin_manager()
|
||||
@@ -242,6 +252,9 @@ class Server(object):
|
||||
debug = self._debug
|
||||
safe_mode = self._safe_mode
|
||||
|
||||
if self._v6_only and not octoprint.util.net.HAS_V6:
|
||||
raise RuntimeError("IPv6 only mode configured but system doesn't support IPv6")
|
||||
|
||||
if self._host is None:
|
||||
host = self._settings.get(["server", "host"])
|
||||
if host is None:
|
||||
@@ -305,7 +318,8 @@ class Server(object):
|
||||
additional_factories = hook()
|
||||
analysis_queue_factories.update(**additional_factories)
|
||||
except Exception:
|
||||
self._logger.exception("Error while processing analysis queues from {}".format(name))
|
||||
self._logger.exception("Error while processing analysis queues from {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
analysisQueue = octoprint.filemanager.analysis.AnalysisQueue(analysis_queue_factories)
|
||||
|
||||
slicingManager = octoprint.slicing.SlicingManager(self._settings.getBaseFolder("slicingProfiles"), printerProfileManager)
|
||||
@@ -404,7 +418,8 @@ class Server(object):
|
||||
self._logger.debug("Created user manager instance from factory {}".format(name))
|
||||
break
|
||||
except Exception:
|
||||
self._logger.exception("Error while creating user manager instance from factory {}".format(name))
|
||||
self._logger.exception("Error while creating user manager instance from factory {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
else:
|
||||
user_manager_name = self._settings.get(["accessControl", "userManager"])
|
||||
try:
|
||||
@@ -435,7 +450,8 @@ class Server(object):
|
||||
self._logger.debug("Created printer instance from factory {}".format(name))
|
||||
break
|
||||
except Exception:
|
||||
self._logger.exception("Error while creating printer instance from factory {}".format(name))
|
||||
self._logger.exception("Error while creating printer instance from factory {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
else:
|
||||
printer = Printer(fileManager, analysisQueue, printerProfileManager)
|
||||
components.update(dict(printer=printer))
|
||||
@@ -524,7 +540,8 @@ class Server(object):
|
||||
constant, value = octoprint.events.Events.register_event(event, prefix="plugin_{}_".format(name))
|
||||
self._logger.debug("Registered event {} of plugin {} as Events.{} = \"{}\"".format(event, name, constant, value))
|
||||
except Exception:
|
||||
self._logger.exception("Error while retrieving custom event list from plugin {}".format(name))
|
||||
self._logger.exception("Error while retrieving custom event list from plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
pluginManager.implementation_inject_factories=[octoprint_plugin_inject_factory,
|
||||
settings_plugin_inject_factory]
|
||||
@@ -535,7 +552,9 @@ class Server(object):
|
||||
try:
|
||||
settings_plugin_config_migration_and_cleanup(implementation._identifier, implementation)
|
||||
except Exception:
|
||||
self._logger.exception("Error while trying to migrate settings for plugin {}, ignoring it".format(implementation._identifier))
|
||||
self._logger.exception("Error while trying to migrate settings for "
|
||||
"plugin {}, ignoring it".format(implementation._identifier),
|
||||
extra=dict(plugin=implementation._identifier))
|
||||
|
||||
pluginManager.implementation_post_inits=[settings_plugin_config_migration_and_cleanup]
|
||||
|
||||
@@ -609,7 +628,8 @@ class Server(object):
|
||||
try:
|
||||
access_validators_from_plugins.append(util.tornado.access_validation_factory(app, hook))
|
||||
except Exception:
|
||||
self._logger.exception("Error while adding tornado access validator from plugin {}".format(plugin))
|
||||
self._logger.exception("Error while adding tornado access validator from plugin {}".format(plugin),
|
||||
extra=dict(plugin=plugin))
|
||||
access_validator = dict(access_validation=util.tornado.validation_chain(*access_validators_from_plugins))
|
||||
|
||||
timelapse_validators = [util.tornado.access_validation_factory(app, util.flask.permission_validator, permissions.Permissions.TIMELAPSE_LIST),] + access_validators_from_plugins
|
||||
@@ -679,7 +699,9 @@ class Server(object):
|
||||
try:
|
||||
result = hook(list(server_routes))
|
||||
except Exception:
|
||||
self._logger.exception("There was an error while retrieving additional server routes from plugin hook {name}".format(**locals()))
|
||||
self._logger.exception("There was an error while retrieving additional "
|
||||
"server routes from plugin hook {name}".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
else:
|
||||
if isinstance(result, (list, tuple)):
|
||||
for entry in result:
|
||||
@@ -722,7 +744,9 @@ class Server(object):
|
||||
try:
|
||||
result = hook(list(max_body_sizes))
|
||||
except Exception:
|
||||
self._logger.exception("There was an error while retrieving additional upload sizes from plugin hook {name}".format(**locals()))
|
||||
self._logger.exception("There was an error while retrieving additional "
|
||||
"upload sizes from plugin hook {name}".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
else:
|
||||
if isinstance(result, (list, tuple)):
|
||||
for entry in result:
|
||||
@@ -756,9 +780,13 @@ class Server(object):
|
||||
server_kwargs.update(dict(idle_connection_timeout=600))
|
||||
|
||||
self._server = util.tornado.CustomHTTPServer(self._tornado_app, **server_kwargs)
|
||||
self._server.listen(self._port, address=self._host if self._host != "::" else None) # special case - tornado
|
||||
# only listens on v4 & v6
|
||||
# if we use None as address
|
||||
|
||||
listening_address = self._host
|
||||
if self._host == "::" and not self._v6_only:
|
||||
# special case - tornado only listens on v4 _and_ v6 if we use None as address
|
||||
listening_address = None
|
||||
|
||||
self._server.listen(self._port, address=listening_address)
|
||||
|
||||
### From now on it's ok to launch subprocesses again
|
||||
|
||||
@@ -779,13 +807,17 @@ class Server(object):
|
||||
self._logger.exception("Something went wrong while attempting to automatically connect to the printer")
|
||||
|
||||
# start up watchdogs
|
||||
watched = self._settings.getBaseFolder("watched")
|
||||
watchdog_handler = util.watchdog.GcodeWatchdogHandler(fileManager, printer)
|
||||
watchdog_handler.initial_scan(watched)
|
||||
|
||||
if self._settings.getBoolean(["feature", "pollWatched"]):
|
||||
# use less performant polling observer if explicitely configured
|
||||
# use less performant polling observer if explicitly configured
|
||||
observer = PollingObserver()
|
||||
else:
|
||||
# use os default
|
||||
observer = Observer()
|
||||
observer.schedule(util.watchdog.GcodeWatchdogHandler(fileManager, printer), self._settings.getBaseFolder("watched"))
|
||||
observer.schedule(watchdog_handler, watched)
|
||||
observer.start()
|
||||
|
||||
# run our startup plugins
|
||||
@@ -803,8 +835,16 @@ class Server(object):
|
||||
|
||||
# prepare our after startup function
|
||||
def on_after_startup():
|
||||
self._logger.info("Listening on http://{}:{}".format(self._host if not ":" in self._host else "[" + self._host + "]",
|
||||
self._port))
|
||||
if self._host == "::":
|
||||
if self._v6_only:
|
||||
# only v6
|
||||
self._logger.info("Listening on http://[::]:{port}".format(port=self._port))
|
||||
else:
|
||||
# all v4 and v6
|
||||
self._logger.info("Listening on http://0.0.0.0:{port} and http://[::]:{port}".format(port=self._port))
|
||||
else:
|
||||
self._logger.info("Listening on http://{}:{}".format(self._host if not ":" in self._host else "[" + self._host + "]",
|
||||
self._port))
|
||||
|
||||
if safe_mode and self._settings.getBoolean(["server", "startOnceInSafeMode"]):
|
||||
self._logger.info("Server started successfully in safe mode as requested from config, removing flag")
|
||||
@@ -1168,7 +1208,7 @@ class Server(object):
|
||||
kwargs.update(additional_request_data)
|
||||
|
||||
try:
|
||||
start = time.time()
|
||||
start = octoprint.util.monotonic_time()
|
||||
if plugin:
|
||||
logger.info("Preemptively caching {} (ui {}) for {!r}".format(route, plugin, kwargs))
|
||||
else:
|
||||
@@ -1182,7 +1222,7 @@ class Server(object):
|
||||
builder = EnvironBuilder(**kwargs)
|
||||
app(builder.get_environ(), lambda *a, **kw: None)
|
||||
|
||||
logger.info("... done in {:.2f}s".format(time.time() - start))
|
||||
logger.info("... done in {:.2f}s".format(octoprint.util.monotonic_time() - start))
|
||||
except Exception:
|
||||
logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs))
|
||||
|
||||
@@ -1239,7 +1279,9 @@ class Server(object):
|
||||
blueprint, prefix = self._prepare_blueprint_plugin(plugin)
|
||||
blueprints[prefix] = blueprint
|
||||
except Exception:
|
||||
self._logger.exception("Error while registering blueprint of plugin {}, ignoring it".format(plugin._identifier))
|
||||
self._logger.exception("Error while registering blueprint of "
|
||||
"plugin {}, ignoring it".format(plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
continue
|
||||
|
||||
return blueprints
|
||||
@@ -1255,7 +1297,9 @@ class Server(object):
|
||||
blueprint, prefix = self._prepare_asset_plugin(plugin)
|
||||
blueprints[prefix] = blueprint
|
||||
except Exception:
|
||||
self._logger.exception("Error while registering assets of plugin {}, ignoring it".format(plugin._identifier))
|
||||
self._logger.exception("Error while registering assets of plugin "
|
||||
"{}, ignoring it".format(plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
continue
|
||||
|
||||
return blueprints
|
||||
@@ -1266,15 +1310,9 @@ class Server(object):
|
||||
if blueprint is None:
|
||||
return
|
||||
|
||||
if plugin.is_blueprint_protected():
|
||||
blueprint.before_request(corsRequestHandler)
|
||||
blueprint.before_request(enforceApiKeyRequestHandler)
|
||||
blueprint.before_request(loginFromApiKeyRequestHandler)
|
||||
blueprint.after_request(corsResponseHandler)
|
||||
else:
|
||||
blueprint.before_request(corsRequestHandler)
|
||||
blueprint.before_request(loginFromApiKeyRequestHandler)
|
||||
blueprint.after_request(corsResponseHandler)
|
||||
blueprint.before_request(corsRequestHandler)
|
||||
blueprint.before_request(loginFromApiKeyRequestHandler)
|
||||
blueprint.after_request(corsResponseHandler)
|
||||
|
||||
url_prefix = "/plugin/{name}".format(name=name)
|
||||
app.register_blueprint(blueprint, url_prefix=url_prefix)
|
||||
@@ -1303,22 +1341,24 @@ class Server(object):
|
||||
for plugin, hook in before_hooks.items():
|
||||
for blueprint in blueprints:
|
||||
try:
|
||||
result = hook()
|
||||
result = hook(plugin=plugin)
|
||||
if isinstance(result, (list, tuple)):
|
||||
for h in result:
|
||||
blueprint.before_request(h)
|
||||
except Exception:
|
||||
self._logger.exception("Error processing before_request hooks from plugin {}".format(plugin))
|
||||
self._logger.exception("Error processing before_request hooks from plugin {}".format(plugin),
|
||||
extra=dict(plugin=plugin))
|
||||
|
||||
for plugin, hook in after_hooks.items():
|
||||
for blueprint in blueprints:
|
||||
try:
|
||||
result = hook()
|
||||
result = hook(plugin=plugin)
|
||||
if isinstance(result, (list, tuple)):
|
||||
for h in result:
|
||||
blueprint.after_request(h)
|
||||
except Exception:
|
||||
self._logger.exception("Error processing after_request hooks from plugin {}".format(plugin))
|
||||
self._logger.exception("Error processing after_request hooks from plugin {}".format(plugin),
|
||||
extra=dict(plugin=plugin))
|
||||
|
||||
def _setup_assets(self):
|
||||
global app
|
||||
@@ -1666,10 +1706,7 @@ class Server(object):
|
||||
loginManager.user_callback = load_user
|
||||
loginManager.unauthorized_callback = unauthorized_user
|
||||
loginManager.anonymous_user = userManager.anonymous_user_factory
|
||||
|
||||
# login users authenticated by basic auth
|
||||
if self._settings.get(["accessControl", "trustBasicAuthentication"]):
|
||||
loginManager.request_callback = load_user_from_request
|
||||
loginManager.request_callback = load_user_from_request
|
||||
|
||||
loginManager.init_app(app, add_context_processor=False)
|
||||
|
||||
@@ -1744,23 +1781,42 @@ class Server(object):
|
||||
|
||||
rules = list(map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules)))
|
||||
|
||||
HTTPServerV4 = HTTPServer
|
||||
|
||||
class HTTPServerV6(HTTPServer):
|
||||
address_family = socket.AF_INET6
|
||||
|
||||
class HTTPServerV6SingleStack(HTTPServerV6):
|
||||
def __init__(self, *args, **kwargs):
|
||||
HTTPServer.__init__(self, *args, **kwargs)
|
||||
HTTPServerV6.__init__(self, *args, **kwargs)
|
||||
|
||||
# make sure to enable dual stack mode, otherwise the socket might only listen on IPv6
|
||||
# explicitly set V6ONLY flag - seems to be the default, but just to make sure...
|
||||
self.socket.setsockopt(octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 1)
|
||||
|
||||
class HTTPServerV6DualStack(HTTPServerV6):
|
||||
def __init__(self, *args, **kwargs):
|
||||
HTTPServerV6.__init__(self, *args, **kwargs)
|
||||
|
||||
# explicitly unset V6ONLY flag
|
||||
self.socket.setsockopt(octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 0)
|
||||
|
||||
if ":" in host:
|
||||
# v6
|
||||
ServerClass = HTTPServerV6
|
||||
if host == "::" and not self._v6_only:
|
||||
ServerClass = HTTPServerV6DualStack
|
||||
else:
|
||||
ServerClass = HTTPServerV6SingleStack
|
||||
else:
|
||||
# v4
|
||||
ServerClass = HTTPServer
|
||||
ServerClass = HTTPServerV4
|
||||
|
||||
self._logger.debug("Starting intermediary server on http://{}:{}".format(host if not ":" in host else "[" + host + "]", port))
|
||||
if host == "::":
|
||||
if self._v6_only:
|
||||
self._logger.debug("Starting intermediary server on http://[::]:{port}".format(port=port))
|
||||
else:
|
||||
self._logger.debug("Starting intermediary server on http://0.0.0.0:{port} and http://[::]:{port}".format(port=port))
|
||||
else:
|
||||
self._logger.debug("Starting intermediary server on http://{}:{}".format(host if not ":" in host else "[" + host + "]", port))
|
||||
|
||||
self._intermediary_server = ServerClass((host, port),
|
||||
lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs),
|
||||
|
||||
@@ -18,7 +18,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, loginFromAuthorizationHeaderRequestHandler, corsRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util import noCachingExceptGetResponseHandler, loginFromApiKeyRequestHandler, loginFromAuthorizationHeaderRequestHandler, corsRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util.flask import no_firstrun_access, get_json_command_from_request, passive_login, get_remote_address
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
@@ -46,7 +46,6 @@ VERSION = "0.1"
|
||||
api.after_request(noCachingExceptGetResponseHandler)
|
||||
|
||||
api.before_request(corsRequestHandler)
|
||||
api.before_request(enforceApiKeyRequestHandler)
|
||||
api.before_request(loginFromAuthorizationHeaderRequestHandler)
|
||||
api.before_request(loginFromApiKeyRequestHandler)
|
||||
api.after_request(corsResponseHandler)
|
||||
@@ -62,15 +61,20 @@ def pluginData(name):
|
||||
if len(api_plugins) > 1:
|
||||
return make_response("More than one api provider registered for {name}, can't proceed".format(name=name), 500)
|
||||
|
||||
api_plugin = api_plugins[0]
|
||||
if api_plugin.is_api_adminonly() and not current_user.is_admin:
|
||||
return make_response("Forbidden", 403)
|
||||
try:
|
||||
api_plugin = api_plugins[0]
|
||||
if api_plugin.is_api_adminonly() and not current_user.is_admin:
|
||||
return make_response("Forbidden", 403)
|
||||
|
||||
response = api_plugin.on_api_get(request)
|
||||
response = api_plugin.on_api_get(request)
|
||||
|
||||
if response is not None:
|
||||
return response
|
||||
return NO_CONTENT
|
||||
if response is not None:
|
||||
return response
|
||||
return NO_CONTENT
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Error calling SimpleApiPlugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
return abort(500)
|
||||
|
||||
#~~ commands for plugins
|
||||
|
||||
@@ -86,21 +90,26 @@ def pluginCommand(name):
|
||||
return make_response("More than one api provider registered for {name}, can't proceed".format(name=name), 500)
|
||||
|
||||
api_plugin = api_plugins[0]
|
||||
valid_commands = api_plugin.get_api_commands()
|
||||
if valid_commands is None:
|
||||
return make_response("Method not allowed", 405)
|
||||
try:
|
||||
valid_commands = api_plugin.get_api_commands()
|
||||
if valid_commands is None:
|
||||
return make_response("Method not allowed", 405)
|
||||
|
||||
if api_plugin.is_api_adminonly() and not Permissions.ADMIN.can():
|
||||
return make_response("Forbidden", 403)
|
||||
if api_plugin.is_api_adminonly() and not Permissions.ADMIN.can():
|
||||
return make_response("Forbidden", 403)
|
||||
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
response = api_plugin.on_api_command(command, data)
|
||||
if response is not None:
|
||||
return response
|
||||
return NO_CONTENT
|
||||
response = api_plugin.on_api_command(command, data)
|
||||
if response is not None:
|
||||
return response
|
||||
return NO_CONTENT
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Error while excuting SimpleApiPlugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
return abort(500)
|
||||
|
||||
#~~ first run setup
|
||||
|
||||
@@ -121,7 +130,9 @@ def wizardState():
|
||||
version = implementation.get_wizard_version()
|
||||
ignored = octoprint.plugin.WizardPlugin.is_wizard_ignored(seen_wizards, implementation)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("There was an error fetching wizard details for {}, ignoring".format(name))
|
||||
logging.getLogger(__name__).exception("There was an error fetching wizard "
|
||||
"details for {}, ignoring".format(name),
|
||||
extra=dict(plugin=name))
|
||||
else:
|
||||
result[name] = dict(required=required, details=details, version=version, ignored=ignored)
|
||||
|
||||
@@ -159,7 +170,9 @@ def wizardFinish():
|
||||
if name in handled:
|
||||
seen_wizards[name] = implementation.get_wizard_version()
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("There was an error finishing the wizard for {}, ignoring".format(name))
|
||||
logging.getLogger(__name__).exception("There was an error finishing the "
|
||||
"wizard for {}, ignoring".format(name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
s().set(["server", "seenWizards"], seen_wizards)
|
||||
s().save()
|
||||
@@ -226,7 +239,10 @@ def login():
|
||||
response["_is_external_client"] = s().getBoolean(["server", "ipCheck", "enabled"]) \
|
||||
and not util_net.is_lan_address(remote_addr,
|
||||
additional_private=s().get(["server", "ipCheck", "trustedSubnets"]))
|
||||
return jsonify(response)
|
||||
|
||||
r = make_response(jsonify(response))
|
||||
r.delete_cookie("active_logout")
|
||||
return r
|
||||
|
||||
return make_response(("User unknown or password incorrect", 401, []))
|
||||
|
||||
@@ -244,7 +260,11 @@ def logout():
|
||||
# ... and from flask login (and principal)
|
||||
logout_user()
|
||||
|
||||
return jsonify(octoprint.access.users.AnonymousUser([octoprint.server.groupManager.guest_group]))
|
||||
# ... and send an active logout session cookie
|
||||
r = make_response(jsonify(octoprint.access.users.AnonymousUser([octoprint.server.groupManager.guest_group])))
|
||||
r.set_cookie("active_logout", "true")
|
||||
|
||||
return r
|
||||
|
||||
|
||||
def _logout(user):
|
||||
|
||||
@@ -81,9 +81,19 @@ def getInstalledLanguagePacks():
|
||||
plugin_packs[plugin_entry.name]["display"] = plugin_info.name
|
||||
|
||||
for language_entry in scandir(plugin_entry.path):
|
||||
plugin_packs[plugin_entry.name]["languages"].append(load_meta(language_entry.path, language_entry.name))
|
||||
try:
|
||||
plugin_packs[plugin_entry.name]["languages"].append(load_meta(language_entry.path, language_entry.name))
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Error while parsing metadata for language pack {} from {} for plugin {}".format(language_entry.name,
|
||||
language_entry.path,
|
||||
plugin_entry.name))
|
||||
continue
|
||||
else:
|
||||
core_packs.append(load_meta(entry.path, entry.name))
|
||||
try:
|
||||
core_packs.append(load_meta(entry.path, entry.name))
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Error while parsing metadata for core language pack {} from {}".format(entry.name,
|
||||
entry.path))
|
||||
|
||||
result = dict(_core=dict(identifier="_core", display="Core", languages=core_packs))
|
||||
result.update(plugin_packs)
|
||||
|
||||
@@ -9,7 +9,7 @@ from flask import request, jsonify, make_response, Response
|
||||
from werkzeug.exceptions import BadRequest
|
||||
import re
|
||||
|
||||
from past.builtins import long, unicode
|
||||
from past.builtins import long, unicode, basestring
|
||||
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, printerProfileManager, NO_CONTENT
|
||||
@@ -38,12 +38,18 @@ def printerState():
|
||||
|
||||
result = {}
|
||||
|
||||
processor = lambda x: x
|
||||
if not printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
processor = _delete_bed
|
||||
|
||||
# add temperature information
|
||||
if not "temperature" in excludes:
|
||||
processor = lambda x: x
|
||||
heated_bed = printerProfileManager.get_current_or_default()["heatedBed"]
|
||||
heated_chamber = printerProfileManager.get_current_or_default()["heatedChamber"]
|
||||
if not heated_bed and not heated_chamber:
|
||||
processor = _keep_tools
|
||||
elif not heated_bed:
|
||||
processor = _delete_bed
|
||||
elif not heated_chamber:
|
||||
processor = _delete_chamber
|
||||
|
||||
result.update({"temperature": _get_temperature_data(processor)})
|
||||
|
||||
# add sd information
|
||||
@@ -86,7 +92,7 @@ def printerToolCommand():
|
||||
##~~ tool selection
|
||||
if command == "select":
|
||||
tool = data["tool"]
|
||||
if re.match(validation_regex, tool) is None:
|
||||
if not isinstance(tool, basestring) or re.match(validation_regex, tool) is None:
|
||||
return make_response("Invalid tool: %s" % tool, 400)
|
||||
if not tool.startswith("tool"):
|
||||
return make_response("Invalid tool for selection: %s" % tool, 400)
|
||||
@@ -159,7 +165,7 @@ def printerToolState():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
return jsonify(_get_temperature_data(_delete_bed))
|
||||
return jsonify(_get_temperature_data(_keep_tools))
|
||||
|
||||
|
||||
##~~ Heated bed
|
||||
@@ -222,7 +228,74 @@ def printerBedState():
|
||||
if not printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
return make_response("Printer does not have a heated bed", 409)
|
||||
|
||||
data = _get_temperature_data(_delete_tools)
|
||||
data = _get_temperature_data(_keep_bed)
|
||||
if isinstance(data, Response):
|
||||
return data
|
||||
else:
|
||||
return jsonify(data)
|
||||
|
||||
|
||||
##~~ Heated chamber
|
||||
|
||||
|
||||
@api.route("/printer/chamber", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerChamberCommand():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
if not printerProfileManager.get_current_or_default()["heatedChamber"]:
|
||||
return make_response("Printer does not have a heated chamber", 409)
|
||||
|
||||
valid_commands = {
|
||||
"target": ["target"],
|
||||
"offset": ["offset"]
|
||||
}
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
tags = {"source:api", "api:printer.chamber"}
|
||||
|
||||
##~~ temperature
|
||||
if command == "target":
|
||||
target = data["target"]
|
||||
|
||||
# make sure the target is a number
|
||||
if not isinstance(target, (int, long, float)):
|
||||
return make_response("Not a number: %r" % target, 400)
|
||||
|
||||
# perform the actual temperature command
|
||||
printer.set_temperature("chamber", target, tags=tags)
|
||||
|
||||
##~~ temperature offset
|
||||
elif command == "offset":
|
||||
offset = data["offset"]
|
||||
|
||||
# make sure the offset is valid
|
||||
if not isinstance(offset, (int, long, float)):
|
||||
return make_response("Not a number: %r" % offset, 400)
|
||||
if not -50 <= offset <= 50:
|
||||
return make_response("Offset not in range [-50, 50]: %f" % offset, 400)
|
||||
|
||||
# set the offsets
|
||||
printer.set_temperature_offset({"chamber": offset})
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/chamber", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
@Permissions.STATUS.require(403)
|
||||
def printerChamberState():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
if not printerProfileManager.get_current_or_default()["heatedChamber"]:
|
||||
return make_response("Printer does not have a heated chamber", 409)
|
||||
|
||||
data = _get_temperature_data(_keep_chamber)
|
||||
if isinstance(data, Response):
|
||||
return data
|
||||
else:
|
||||
@@ -433,13 +506,22 @@ def _get_temperature_data(preprocessor):
|
||||
return preprocessor(tempData)
|
||||
|
||||
|
||||
def _delete_tools(x):
|
||||
return _delete_from_data(x, lambda k: k.startswith("tool"))
|
||||
def _keep_tools(x):
|
||||
return _delete_from_data(x, lambda k: not k.startswith("tool"))
|
||||
|
||||
|
||||
def _keep_bed(x):
|
||||
return _delete_from_data(x, lambda k: k != "bed")
|
||||
|
||||
def _delete_bed(x):
|
||||
return _delete_from_data(x, lambda k: k == "bed")
|
||||
|
||||
def _keep_chamber(x):
|
||||
return _delete_from_data(x, lambda k: k != "chamber")
|
||||
|
||||
def _delete_chamber(x):
|
||||
return _delete_from_data(x, lambda k: k == "chamber")
|
||||
|
||||
|
||||
def _delete_from_data(x, key_matcher):
|
||||
data = dict(x)
|
||||
|
||||
@@ -86,8 +86,6 @@ def getSettings():
|
||||
|
||||
data = {
|
||||
"api": {
|
||||
"enabled": s.getBoolean(["api", "enabled"]),
|
||||
"keyEnforced": s.getBoolean(["api", "keyEnforced"]),
|
||||
"key": s.get(["api", "key"]) if Permissions.ADMIN.can() else None,
|
||||
"allowCrossOrigin": s.get(["api", "allowCrossOrigin"])
|
||||
},
|
||||
@@ -137,6 +135,7 @@ def getSettings():
|
||||
"serial": {
|
||||
"port": connectionOptions["portPreference"],
|
||||
"baudrate": connectionOptions["baudratePreference"],
|
||||
"exclusive": s.getBoolean(["serial", "exclusive"]),
|
||||
"portOptions": connectionOptions["ports"],
|
||||
"baudrateOptions": connectionOptions["baudrates"],
|
||||
"autoconnect": s.getBoolean(["serial", "autoconnect"]),
|
||||
@@ -156,11 +155,13 @@ def getSettings():
|
||||
"additionalBaudrates": s.get(["serial", "additionalBaudrates"]),
|
||||
"longRunningCommands": s.get(["serial", "longRunningCommands"]),
|
||||
"checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]),
|
||||
"blockedCommands": s.get(["serial", "blockedCommands"]),
|
||||
"pausingCommands": s.get(["serial", "pausingCommands"]),
|
||||
"emergencyCommands": s.get(["serial", "emergencyCommands"]),
|
||||
"helloCommand": s.get(["serial", "helloCommand"]),
|
||||
"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
|
||||
"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
|
||||
"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]),
|
||||
"blockM0M1": s.getBoolean(["serial", "blockM0M1"]),
|
||||
"logPositionOnPause": s.getBoolean(["serial", "logPositionOnPause"]),
|
||||
"logPositionOnCancel": s.getBoolean(["serial", "logPositionOnCancel"]),
|
||||
"abortHeatupOnCancel": s.getBoolean(["serial", "abortHeatupOnCancel"]),
|
||||
@@ -276,7 +277,8 @@ def _get_plugin_settings():
|
||||
process_plugin_result(plugin._identifier, result)
|
||||
except Exception:
|
||||
logger.exception("Could not load settings for plugin {name} ({version})".format(version=plugin._plugin_version,
|
||||
name=plugin._plugin_name))
|
||||
name=plugin._plugin_name),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
|
||||
return data
|
||||
|
||||
@@ -373,8 +375,6 @@ def _saveSettings(data):
|
||||
return make_response("One of the configured folders is invalid", 400)
|
||||
|
||||
if "api" in data:
|
||||
if "enabled" in data["api"]: s.setBoolean(["api", "enabled"], data["api"]["enabled"])
|
||||
if "keyEnforced" in data["api"]: s.setBoolean(["api", "keyEnforced"], data["api"]["keyEnforced"])
|
||||
if "allowCrossOrigin" in data["api"]: s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
|
||||
|
||||
if "appearance" in data:
|
||||
@@ -424,6 +424,7 @@ def _saveSettings(data):
|
||||
if "autoconnect" in data["serial"]: s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
||||
if "port" in data["serial"]: s.set(["serial", "port"], data["serial"]["port"])
|
||||
if "baudrate" in data["serial"]: s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
|
||||
if "exclusive" in data["serial"]: s.setBoolean(["serial", "exclusive"], data["serial"]["exclusive"])
|
||||
if "timeoutConnection" in data["serial"]: s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"], min=1.0)
|
||||
if "timeoutDetection" in data["serial"]: s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"], min=1.0)
|
||||
if "timeoutCommunication" in data["serial"]: s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"], min=1.0)
|
||||
@@ -439,11 +440,13 @@ def _saveSettings(data):
|
||||
if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"])
|
||||
if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"])
|
||||
if "checksumRequiringCommands" in data["serial"] and isinstance(data["serial"]["checksumRequiringCommands"], (list, tuple)): s.set(["serial", "checksumRequiringCommands"], data["serial"]["checksumRequiringCommands"])
|
||||
if "blockedCommands" in data["serial"] and isinstance(data["serial"]["blockedCommands"], (list, tuple)): s.set(["serial", "blockedCommands"], data["serial"]["blockedCommands"])
|
||||
if "pausingCommands" in data["serial"] and isinstance(data["serial"]["pausingCommands"], (list, tuple)): s.set(["serial", "pausingCommands"], data["serial"]["pausingCommands"])
|
||||
if "emergencyCommands" in data["serial"] and isinstance(data["serial"]["emergencyCommands"], (list, tuple)): s.set(["serial", "emergencyCommands"], data["serial"]["emergencyCommands"])
|
||||
if "helloCommand" in data["serial"]: s.set(["serial", "helloCommand"], data["serial"]["helloCommand"])
|
||||
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 "blockM0M1" in data["serial"]: s.setBoolean(["serial", "blockM0M1"], data["serial"]["blockM0M1"])
|
||||
if "supportResendsWithoutOk" in data["serial"]:
|
||||
value = data["serial"]["supportResendsWithoutOk"]
|
||||
if value in ("always", "detect", "never"):
|
||||
@@ -556,6 +559,8 @@ def _saveSettings(data):
|
||||
logger.warning("Please contact the plugin's author and ask to update the plugin to use a direct call like")
|
||||
logger.warning("octoprint.plugin.SettingsPlugin.on_settings_save(self, data) instead.")
|
||||
except Exception:
|
||||
logger.exception("Could not save settings for plugin {name} ({version})".format(version=plugin._plugin_version, name=plugin._plugin_name))
|
||||
logger.exception("Could not save settings for plugin {name} ({version})".format(version=plugin._plugin_version,
|
||||
name=plugin._plugin_name),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
|
||||
s.save()
|
||||
s.save(trigger_event=True)
|
||||
@@ -48,7 +48,7 @@ def performSystemAction():
|
||||
data = request.values
|
||||
|
||||
if not "action" in data:
|
||||
return make_response("action to perform is not defined", 400)
|
||||
return make_response(u"action to perform is not defined", 400)
|
||||
|
||||
return executeSystemCommand("custom", data["action"])
|
||||
|
||||
@@ -70,7 +70,7 @@ def retrieveSystemCommandsForSource(source):
|
||||
elif source == "custom":
|
||||
specs = _get_custom_command_specs()
|
||||
else:
|
||||
return make_response("Unknown system command source: {}".format(source), 404)
|
||||
return make_response(u"Unknown system command source: {}".format(source), 404)
|
||||
|
||||
return jsonify(_to_client_specs(specs))
|
||||
|
||||
@@ -86,26 +86,26 @@ def executeSystemCommand(source, command):
|
||||
|
||||
command_spec = _get_command_spec(source, command)
|
||||
if not command_spec:
|
||||
return make_response("Command {}:{} not found".format(source, command), 404)
|
||||
return make_response(u"Command {}:{} not found".format(source, command), 404)
|
||||
|
||||
if not "command" in command_spec:
|
||||
return make_response("Command {}:{} does not define a command to execute, can't proceed".format(source, command), 500)
|
||||
return make_response(u"Command {}:{} does not define a command to execute, can't proceed".format(source, command), 500)
|
||||
|
||||
do_async = command_spec.get("async", False)
|
||||
do_ignore = command_spec.get("ignore", False)
|
||||
debug = command_spec.get("debug", False)
|
||||
|
||||
if logger.isEnabledFor(logging.DEBUG) or debug:
|
||||
logger.info("Performing command for {}:{}: {}".format(source, command, command_spec["command"]))
|
||||
logger.info(u"Performing command for {}:{}: {}".format(source, command, command_spec["command"]))
|
||||
else:
|
||||
logger.info("Performing command for {}:{}".format(source, command))
|
||||
logger.info(u"Performing command for {}:{}".format(source, command))
|
||||
|
||||
try:
|
||||
if "before" in command_spec and callable(command_spec["before"]):
|
||||
command_spec["before"]()
|
||||
except Exception as e:
|
||||
if not do_ignore:
|
||||
error = "Command \"before\" for {}:{} failed: {}".format(source, command, str(e))
|
||||
error = u"Command \"before\" for {}:{} failed: {}".format(source, command, e)
|
||||
logger.warning(error)
|
||||
return make_response(error, 500)
|
||||
|
||||
@@ -145,7 +145,7 @@ def executeSystemCommand(source, command):
|
||||
|
||||
except Exception as e:
|
||||
if not do_ignore:
|
||||
error = "Command for {}:{} failed: {}".format(source, command, str(e))
|
||||
error = "Command for {}:{} failed: {}".format(source, command, e)
|
||||
logger.warning(error)
|
||||
return make_response(error, 500)
|
||||
|
||||
@@ -183,19 +183,19 @@ def _get_core_command_specs():
|
||||
shutdown=dict(
|
||||
command=s().get(["server", "commands", "systemShutdownCommand"]),
|
||||
name=gettext("Shutdown system"),
|
||||
confirm=gettext("<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
|
||||
confirm=gettext(u"<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
|
||||
reboot=dict(
|
||||
command=s().get(["server", "commands", "systemRestartCommand"]),
|
||||
name=gettext("Reboot system"),
|
||||
confirm=gettext("<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
|
||||
confirm=gettext(u"<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
|
||||
restart=dict(
|
||||
command=s().get(["server", "commands", "serverRestartCommand"]),
|
||||
name=gettext("Restart OctoPrint"),
|
||||
confirm=gettext("<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
|
||||
confirm=gettext(u"<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
|
||||
restart_safe=dict(
|
||||
command=s().get(["server", "commands", "serverRestartCommand"]),
|
||||
name=gettext("Restart OctoPrint in safe mode"),
|
||||
confirm=gettext("<strong>You are about to restart the OctoPrint server in safe mode.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."),
|
||||
confirm=gettext(u"<strong>You are about to restart the OctoPrint server in safe mode.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."),
|
||||
before=enable_safe_mode)
|
||||
)
|
||||
|
||||
@@ -211,7 +211,7 @@ def _get_core_command_specs():
|
||||
def _get_core_command_spec(action):
|
||||
available_actions = _get_core_command_specs()
|
||||
if not action in available_actions:
|
||||
logging.getLogger(__name__).warn("Command for core action {} is not configured, you need to configure the command before it can be used".format(action))
|
||||
logging.getLogger(__name__).warn(u"Command for core action {} is not configured, you need to configure the command before it can be used".format(action))
|
||||
return None
|
||||
|
||||
return available_actions[action]
|
||||
|
||||
@@ -28,29 +28,9 @@ from . import tornado
|
||||
from . import watchdog
|
||||
|
||||
|
||||
@deprecated("API keys are no longer needed for anonymous access and thus this is now obsolete")
|
||||
def enforceApiKeyRequestHandler():
|
||||
"""
|
||||
``before_request`` handler for blueprints which makes sure an API key is provided if configured as such
|
||||
"""
|
||||
|
||||
import octoprint.server
|
||||
|
||||
if _flask.request.method == 'OPTIONS':
|
||||
# we ignore OPTIONS requests here
|
||||
return
|
||||
|
||||
if _flask.request.endpoint and (_flask.request.endpoint == "static" or _flask.request.endpoint.endswith(".static")):
|
||||
# no further handling for static resources
|
||||
return
|
||||
|
||||
apikey = get_api_key(_flask.request)
|
||||
|
||||
if not apikey and settings().getBoolean(["api", "keyEnforced"]):
|
||||
return _flask.make_response("No API key provided", 403)
|
||||
|
||||
if apikey != octoprint.server.UI_API_KEY and not settings().getBoolean(["api", "enabled"]):
|
||||
# api disabled => 403
|
||||
return _flask.make_response("API disabled", 403)
|
||||
pass
|
||||
|
||||
apiKeyRequestHandler = deprecated("apiKeyRequestHandler has been renamed to enforceApiKeyRequestHandler")(enforceApiKeyRequestHandler)
|
||||
|
||||
@@ -59,7 +39,7 @@ def loginFromApiKeyRequestHandler():
|
||||
"""
|
||||
``before_request`` handler for blueprints which creates a login session for the provided api key (if available)
|
||||
|
||||
UI_API_KEY and app session keys are handled as anonymous keys here and ignored.
|
||||
App session keys are handled as anonymous keys here and ignored.
|
||||
"""
|
||||
try:
|
||||
if loginUserFromApiKey():
|
||||
@@ -72,7 +52,11 @@ def loginFromAuthorizationHeaderRequestHandler():
|
||||
"""
|
||||
``before_request`` handler for creating login sessions based on the Authorization header.
|
||||
"""
|
||||
loginUserFromApiKey()
|
||||
try:
|
||||
if loginUserFromAuthorizationHeader():
|
||||
_flask.g.login_via_header = True
|
||||
except InvalidApiKeyException:
|
||||
return _flask.make_response("Invalid API key", 403)
|
||||
|
||||
|
||||
class InvalidApiKeyException(Exception): pass
|
||||
@@ -84,14 +68,15 @@ def loginUserFromApiKey():
|
||||
if not apikey:
|
||||
return False
|
||||
|
||||
if apikey == octoprint.server.UI_API_KEY:
|
||||
user = get_user_for_apikey(apikey)
|
||||
if user is None:
|
||||
# invalid API key = no API key
|
||||
return False
|
||||
|
||||
user = get_user_for_apikey(apikey)
|
||||
if not loginUser(user):
|
||||
raise InvalidApiKeyException()
|
||||
else:
|
||||
return True
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def loginUserFromAuthorizationHeader():
|
||||
@@ -192,16 +177,11 @@ def optionsAllowOrigin(request):
|
||||
|
||||
|
||||
def get_user_for_apikey(apikey):
|
||||
if settings().getBoolean(["api", "enabled"]) and apikey is not None:
|
||||
if apikey == octoprint.server.UI_API_KEY:
|
||||
import flask_login
|
||||
if octoprint.server.userManager.enabled:
|
||||
return octoprint.server.userManager.find_user(session=flask_login.current_user.session)
|
||||
else:
|
||||
return flask_login.current_user
|
||||
elif apikey == settings().get(["api", "key"]):
|
||||
# master key or an app session key was used
|
||||
if apikey is not None:
|
||||
if apikey == settings().get(["api", "key"]):
|
||||
# master 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:
|
||||
@@ -215,10 +195,32 @@ def get_user_for_apikey(apikey):
|
||||
if user is not None:
|
||||
return user
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Error running api key validator for plugin {} and key {}".format(name, apikey))
|
||||
logging.getLogger(__name__).exception("Error running api key validator "
|
||||
"for plugin {} and key {}".format(name, apikey),
|
||||
extra=dict(plugin=name))
|
||||
return None
|
||||
|
||||
|
||||
def get_user_for_remote_user_header(request):
|
||||
if not octoprint.server.userManager.enabled:
|
||||
return None
|
||||
|
||||
if not settings().getBoolean(["accessControl", "trustRemoteUser"]):
|
||||
return None
|
||||
|
||||
header = request.headers.get(settings().get(["accessControl", "remoteUserHeader"]))
|
||||
if header is None:
|
||||
return None
|
||||
|
||||
user = octoprint.server.userManager.findUser(userid=header)
|
||||
|
||||
if user is None and settings().getBoolean(["accessControl", "addRemoteUsers"]):
|
||||
octoprint.server.userManager.addUser(header, settings().generateApiKey(), active=True)
|
||||
user = octoprint.server.userManager.findUser(userid=header)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
def get_user_for_authorization_header(header):
|
||||
if not settings().getBoolean(["accessControl", "trustBasicAuthentication"]):
|
||||
return None
|
||||
|
||||
@@ -36,7 +36,7 @@ from octoprint.util.json import JsonEncoding
|
||||
from octoprint.util.net import is_lan_address
|
||||
|
||||
from werkzeug.local import LocalProxy
|
||||
from werkzeug.contrib.cache import BaseCache
|
||||
from cachelib import BaseCache
|
||||
|
||||
from past.builtins import basestring, long
|
||||
|
||||
@@ -274,7 +274,7 @@ def fix_flask_jsonify():
|
||||
data = args or kwargs
|
||||
|
||||
return current_app.response_class(
|
||||
dumps(data, indent=indent, separators=separators) + '\n',
|
||||
dumps(data, indent=indent, separators=separators, allow_nan=False) + '\n',
|
||||
mimetype='application/json'
|
||||
)
|
||||
|
||||
@@ -462,7 +462,7 @@ class ReverseProxiedEnvironment(object):
|
||||
|
||||
#~~ request and response versions
|
||||
|
||||
from werkzeug.wrappers import cached_property
|
||||
from werkzeug.utils import cached_property
|
||||
|
||||
class OctoPrintFlaskRequest(flask.Request):
|
||||
environment_wrapper = staticmethod(lambda x: x)
|
||||
@@ -592,7 +592,8 @@ def passive_login():
|
||||
|
||||
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
|
||||
and settings().get(["accessControl", "autologinAs"]) is not None \
|
||||
and settings().get(["accessControl", "localNetworks"]) is not None:
|
||||
and settings().get(["accessControl", "localNetworks"]) is not None \
|
||||
and not "active_logout" in flask.request.cookies:
|
||||
|
||||
autologin_as = settings().get(["accessControl", "autologinAs"])
|
||||
local_networks = _local_networks()
|
||||
@@ -781,7 +782,7 @@ def cache_check_response_headers(response):
|
||||
|
||||
headers = response.headers
|
||||
|
||||
if "Cache-Control" in headers and "no-cache" in headers["Cache-Control"]:
|
||||
if "Cache-Control" in headers and ("no-cache" in headers["Cache-Control"] or "no-store" in headers["Cache-Control"]):
|
||||
return True
|
||||
|
||||
if "Pragma" in headers and "no-cache" in headers["Pragma"]:
|
||||
@@ -1050,6 +1051,18 @@ def conditional(condition, met):
|
||||
return decorator
|
||||
|
||||
|
||||
def with_client_revalidation(f):
|
||||
@functools.wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
r = f(*args, **kwargs)
|
||||
|
||||
if isinstance(r, flask.Response):
|
||||
r = add_revalidation_response_headers(r)
|
||||
|
||||
return r
|
||||
return decorated_function
|
||||
|
||||
|
||||
def with_revalidation_checking(etag_factory=None,
|
||||
lastmodified_factory=None,
|
||||
condition=None,
|
||||
@@ -1135,6 +1148,11 @@ def check_lastmodified(lastmodified):
|
||||
lastmodified >= flask.request.if_modified_since
|
||||
|
||||
|
||||
def add_revalidation_response_headers(response):
|
||||
response.headers["Cache-Control"] = "no-cache, must-revalidate"
|
||||
return response
|
||||
|
||||
|
||||
def add_non_caching_response_headers(response):
|
||||
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0"
|
||||
response.headers["Pragma"] = "no-cache"
|
||||
@@ -1183,12 +1201,11 @@ def get_flask_user_from_request(request):
|
||||
"""
|
||||
import octoprint.server.util
|
||||
import flask_login
|
||||
from octoprint.settings import settings
|
||||
|
||||
user = None
|
||||
|
||||
apikey = octoprint.server.util.get_api_key(request)
|
||||
if settings().getBoolean(["api", "enabled"]) and apikey is not None:
|
||||
if apikey is not None:
|
||||
user = octoprint.server.util.get_user_for_apikey(apikey)
|
||||
|
||||
if user is None:
|
||||
@@ -1457,7 +1474,8 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
all_assets = implementation.get_assets()
|
||||
basefolder = implementation.get_asset_folder()
|
||||
except Exception:
|
||||
logger.exception("Got an error while trying to collect assets from {}, ignoring assets from the plugin".format(name))
|
||||
logger.exception("Got an error while trying to collect assets from {}, ignoring assets from the plugin".format(name),
|
||||
extra=dict(plugin=name))
|
||||
continue
|
||||
|
||||
def asset_exists(category, asset):
|
||||
|
||||
@@ -146,8 +146,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
config_hash = settings().config_hash
|
||||
|
||||
# connected => update the API key, might be necessary if the client was left open while the server restarted
|
||||
self._emit("connected", dict(apikey=octoprint.server.UI_API_KEY,
|
||||
version=octoprint.server.VERSION,
|
||||
self._emit("connected", dict(version=octoprint.server.VERSION,
|
||||
display_version=octoprint.server.DISPLAY_VERSION,
|
||||
branch=octoprint.server.BRANCH,
|
||||
plugin_hash=plugin_hash.hexdigest(),
|
||||
@@ -324,7 +323,8 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
try:
|
||||
proceed = proceed and hook(self, self._user)
|
||||
except Exception:
|
||||
self._logger.exception("Error processing register hook handler for plugin {}".format(name))
|
||||
self._logger.exception("Error processing register hook handler for plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
if not proceed:
|
||||
return
|
||||
@@ -385,7 +385,8 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
try:
|
||||
proceed = proceed and hook(self, self._user, type, payload)
|
||||
except Exception:
|
||||
self._logger.exception("Error processing emit hook handler from plugin {}".format(name))
|
||||
self._logger.exception("Error processing emit hook handler from plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
if not proceed:
|
||||
return
|
||||
@@ -416,7 +417,8 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
try:
|
||||
hook(self, self._user)
|
||||
except Exception:
|
||||
self._logger.exception("Error processing authed hook handler for plugin {}".format(name))
|
||||
self._logger.exception("Error processing authed hook handler for plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
def _on_logout(self):
|
||||
self._user = self._userManager.anonymous_user_factory()
|
||||
@@ -425,5 +427,6 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection,
|
||||
try:
|
||||
hook(self, self._user)
|
||||
except Exception:
|
||||
self._logger.exception("Error processing authed hook handler for plugin {}".format(name))
|
||||
self._logger.exception("Error processing authed hook handler for plugin {}".format(name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
@@ -39,7 +39,7 @@ def fix_json_encode():
|
||||
import json
|
||||
|
||||
def fixed_json_encode(value):
|
||||
return json.dumps(value, default=JsonEncoding.encode).replace("</", "<\\/")
|
||||
return json.dumps(value, default=JsonEncoding.encode, allow_nan=False).replace("</", "<\\/")
|
||||
|
||||
import tornado.escape
|
||||
tornado.escape.json_encode = fixed_json_encode
|
||||
|
||||
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import threading
|
||||
import watchdog.events
|
||||
@@ -30,7 +31,39 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
self._file_manager = file_manager
|
||||
self._printer = printer
|
||||
|
||||
def initial_scan(self, folder):
|
||||
def run_scan():
|
||||
try:
|
||||
from os import scandir
|
||||
except ImportError:
|
||||
from scandir import scandir
|
||||
|
||||
self._logger.info("Running initial scan on watched folder...")
|
||||
for entry in scandir(folder):
|
||||
path = entry.path
|
||||
|
||||
if not self._valid_path(path):
|
||||
continue
|
||||
|
||||
self._logger.info("Found {}, trying to add it".format(path))
|
||||
self._upload(path)
|
||||
self._logger.info("... initial scan done.")
|
||||
|
||||
thread = threading.Thread(target=run_scan)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
def on_created(self, event):
|
||||
path = event.src_path
|
||||
if not self._valid_path(path):
|
||||
return
|
||||
|
||||
thread = threading.Thread(target=self._repeatedly_check, args=(path,))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
def _upload(self, path):
|
||||
# noinspection PyBroadException
|
||||
try:
|
||||
file_wrapper = octoprint.filemanager.util.DiskFileWrapper(os.path.basename(path), path)
|
||||
|
||||
@@ -70,15 +103,15 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
False)
|
||||
except Exception:
|
||||
self._logger.exception("There was an error while processing the file {} in the watched folder".format(path))
|
||||
|
||||
def on_created(self, event):
|
||||
path = event.src_path
|
||||
if octoprint.util.is_hidden_path(path):
|
||||
return
|
||||
|
||||
thread = threading.Thread(target=self._repeatedly_check, args=(path,))
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
finally:
|
||||
if os.path.exists(path):
|
||||
# file is still there - that should only happen if something went wrong, so mark it as failed
|
||||
# noinspection PyBroadException
|
||||
try:
|
||||
shutil.move(path, "{}.failed".format(path))
|
||||
except:
|
||||
# something went really wrong here.... but we can't do anything about it, so just log it
|
||||
self._logger.exception("There was an error while trying to mark {} as failed in the watched folder".format(path))
|
||||
|
||||
def _repeatedly_check(self, path, interval=1, stable=5):
|
||||
try:
|
||||
@@ -108,3 +141,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
|
||||
self._logger.debug("File at {} is stable, moving it".format(path))
|
||||
self._upload(path)
|
||||
|
||||
def _valid_path(self, path):
|
||||
_, ext = os.path.splitext(path)
|
||||
return octoprint.filemanager.valid_file_type(path) and not octoprint.util.is_hidden_path(path) and ext != "failed"
|
||||
@@ -17,12 +17,12 @@ from flask import request, g, url_for, make_response, render_template, send_from
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.server import app, userManager, groupManager, pluginManager, gettext, \
|
||||
debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY, BRANCH, preemptiveCache, \
|
||||
debug, LOCALES, VERSION, DISPLAY_VERSION, BRANCH, preemptiveCache, \
|
||||
NOT_MODIFIED
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.settings import settings
|
||||
from octoprint.filemanager import full_extension_tree, get_all_extensions
|
||||
from octoprint.util import to_unicode
|
||||
from octoprint.util import to_unicode, to_bytes
|
||||
|
||||
import re
|
||||
import base64
|
||||
@@ -124,18 +124,22 @@ def in_cache():
|
||||
ui_plugins = pluginManager.get_implementations(octoprint.plugin.UiPlugin,
|
||||
sorting_context="UiPlugin.on_ui_render")
|
||||
for plugin in ui_plugins:
|
||||
if plugin.will_handle_ui(request):
|
||||
ui = plugin._identifier
|
||||
key = _cache_key(plugin._identifier,
|
||||
url=url,
|
||||
additional_key_data=plugin.get_ui_additional_key_data_for_cache)
|
||||
unless = _preemptive_unless(url, additional_unless=plugin.get_ui_preemptive_caching_additional_unless)
|
||||
data = _preemptive_data(plugin._identifier,
|
||||
path=path,
|
||||
base_url=base_url,
|
||||
data=plugin.get_ui_data_for_preemptive_caching,
|
||||
additional_request_data=plugin.get_ui_additional_request_data_for_preemptive_caching)
|
||||
break
|
||||
try:
|
||||
if plugin.will_handle_ui(request):
|
||||
ui = plugin._identifier
|
||||
key = _cache_key(plugin._identifier,
|
||||
url=url,
|
||||
additional_key_data=plugin.get_ui_additional_key_data_for_cache)
|
||||
unless = _preemptive_unless(url, additional_unless=plugin.get_ui_preemptive_caching_additional_unless)
|
||||
data = _preemptive_data(plugin._identifier,
|
||||
path=path,
|
||||
base_url=base_url,
|
||||
data=plugin.get_ui_data_for_preemptive_caching,
|
||||
additional_request_data=plugin.get_ui_additional_request_data_for_preemptive_caching)
|
||||
break
|
||||
except Exception:
|
||||
_logger.exception("Error while calling plugin {}, skipping it".format(plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
else:
|
||||
ui = "_default"
|
||||
key = _cache_key("_default", url=url)
|
||||
@@ -197,7 +201,9 @@ def index():
|
||||
|
||||
default_additional_etag = [enable_accesscontrol,
|
||||
enable_gcodeviewer,
|
||||
enable_timelapse] + sorted(["{}:{}".format(k, v) for k, v in _plugin_vars.items()])
|
||||
enable_timelapse] + sorted(["{}:{}".format(to_unicode(k, errors="replace"),
|
||||
to_unicode(v, errors="replace"))
|
||||
for k, v in _plugin_vars.items()])
|
||||
|
||||
def get_preemptively_cached_view(key, view, data=None, additional_request_data=None, additional_unless=None):
|
||||
if (data is None and additional_request_data is None) or g.locale is None:
|
||||
@@ -294,14 +300,13 @@ def index():
|
||||
import hashlib
|
||||
hash = hashlib.sha1()
|
||||
def hash_update(value):
|
||||
hash.update(value.encode('utf-8'))
|
||||
hash.update(to_bytes(value, encoding="utf-8", errors="replace"))
|
||||
hash_update(octoprint.__version__)
|
||||
hash_update(octoprint.server.UI_API_KEY)
|
||||
hash_update(",".join(sorted(files)))
|
||||
if lastmodified:
|
||||
hash_update(lastmodified)
|
||||
for add in additional:
|
||||
hash_update(str(add))
|
||||
hash_update(add)
|
||||
return hash.hexdigest()
|
||||
|
||||
decorated_view = view
|
||||
@@ -311,6 +316,7 @@ def index():
|
||||
refreshif=validate_cache,
|
||||
key=cache_key,
|
||||
unless_response=lambda response: util.flask.cache_check_response_headers(response) or util.flask.cache_check_status_code(response, _valid_status_for_cache))(decorated_view)
|
||||
decorated_view = util.flask.with_client_revalidation(decorated_view)
|
||||
decorated_view = util.flask.conditional(check_etag_and_lastmodified, NOT_MODIFIED)(decorated_view)
|
||||
return decorated_view
|
||||
|
||||
@@ -403,13 +409,17 @@ def index():
|
||||
# select view from plugins and fall back on default view if no plugin will handle it
|
||||
ui_plugins = pluginManager.get_implementations(octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render")
|
||||
for plugin in ui_plugins:
|
||||
if plugin.will_handle_ui(request):
|
||||
# plugin claims responsibility, let it render the UI
|
||||
response = plugin_view(plugin)
|
||||
if response is not None:
|
||||
break
|
||||
else:
|
||||
_logger.warning("UiPlugin {} returned an empty response".format(plugin._identifier))
|
||||
try:
|
||||
if plugin.will_handle_ui(request):
|
||||
# plugin claims responsibility, let it render the UI
|
||||
response = plugin_view(plugin)
|
||||
if response is not None:
|
||||
break
|
||||
else:
|
||||
_logger.warning("UiPlugin {} returned an empty response".format(plugin._identifier))
|
||||
except Exception:
|
||||
_logger.exception("Error while calling plugin {}, skipping it".format(plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
else:
|
||||
response = default_view()
|
||||
|
||||
@@ -442,7 +452,6 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
|
||||
debug=debug,
|
||||
firstRun=first_run,
|
||||
version=dict(number=VERSION, display=DISPLAY_VERSION, branch=BRANCH),
|
||||
uiApiKey=UI_API_KEY,
|
||||
templates=templates,
|
||||
pluginNames=plugin_names,
|
||||
locales=locales,
|
||||
@@ -511,7 +520,9 @@ def fetch_template_data(refresh=False):
|
||||
try:
|
||||
result = hook(dict(template_sorting), dict(template_rules))
|
||||
except Exception:
|
||||
_logger.exception("Error while retrieving custom template type definitions from plugin {name}".format(**locals()))
|
||||
_logger.exception("Error while retrieving custom template type "
|
||||
"definitions from plugin {name}".format(**locals()),
|
||||
extra=dict(plugin=name))
|
||||
else:
|
||||
if not isinstance(result, list):
|
||||
continue
|
||||
@@ -564,7 +575,7 @@ def fetch_template_data(refresh=False):
|
||||
# tabs
|
||||
|
||||
templates["tab"]["entries"] = dict(
|
||||
temperature=(gettext("Temperature"), dict(template="tabs/temperature.jinja2", _div="temp", styles=["display: none;"], data_bind="visible: loginState.hasAnyPermissionKo(access.permissions.STATUS, access.permissions.CONTROL)")),
|
||||
temperature=(gettext("Temperature"), dict(template="tabs/temperature.jinja2", _div="temp", styles=["display: none;"], data_bind="visible: loginState.hasAnyPermissionKo(access.permissions.STATUS, access.permissions.CONTROL) && visible()")),
|
||||
control=(gettext("Control"), dict(template="tabs/control.jinja2", _div="control", styles=["display: none;"], data_bind="visible: loginState.hasAnyPermissionKo(access.permissions.WEBCAM, access.permissions.CONTROL)")),
|
||||
gcodeviewer=(gettext("GCode Viewer"), dict(template="tabs/gcodeviewer.jinja2", _div="gcode", styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.GCODE_VIEWER)")),
|
||||
terminal=(gettext("Terminal"), dict(template="tabs/terminal.jinja2", _div="term", styles=["display: none;"], data_bind="visible: loginState.hasPermissionKo(access.permissions.MONITOR_TERMINAL)")),
|
||||
@@ -652,7 +663,8 @@ def fetch_template_data(refresh=False):
|
||||
wizard_required = implementation.is_wizard_required()
|
||||
wizard_ignored = octoprint.plugin.WizardPlugin.is_wizard_ignored(seen_wizards, implementation)
|
||||
except Exception:
|
||||
_logger.exception("Error while retrieving template data for plugin {}, ignoring it".format(name))
|
||||
_logger.exception("Error while retrieving template data for plugin {}, ignoring it".format(name),
|
||||
extra=dict(plugin=name))
|
||||
continue
|
||||
|
||||
if not isinstance(vars, dict):
|
||||
|
||||
+33
-10
@@ -94,6 +94,7 @@ default_settings = {
|
||||
"serial": {
|
||||
"port": None,
|
||||
"baudrate": None,
|
||||
"exclusive": True,
|
||||
"autoconnect": False,
|
||||
"log": False,
|
||||
"timeout": {
|
||||
@@ -119,6 +120,9 @@ default_settings = {
|
||||
"additionalPorts": [],
|
||||
"additionalBaudrates": [],
|
||||
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226", "M600"],
|
||||
"blockedCommands": ["M0", "M1"],
|
||||
"pausingCommands": ["M0", "M1", "M25"],
|
||||
"emergencyCommands": ["M112", "M108", "M410"],
|
||||
"checksumRequiringCommands": ["M110"],
|
||||
"helloCommand": "M110 N0",
|
||||
"disconnectOnErrors": True,
|
||||
@@ -155,14 +159,14 @@ default_settings = {
|
||||
},
|
||||
|
||||
# command specific flags
|
||||
"triggerOkForM29": True,
|
||||
"blockM0M1": True
|
||||
"triggerOkForM29": True
|
||||
},
|
||||
"server": {
|
||||
"host": None,
|
||||
"port": 5000,
|
||||
"firstRun": True,
|
||||
"startOnceInSafeMode": False,
|
||||
"ignoreIncompleteStartup": False,
|
||||
"incompleteStartup": False,
|
||||
"seenWizards": {},
|
||||
"secretKey": None,
|
||||
@@ -343,7 +347,10 @@ default_settings = {
|
||||
"localNetworks": ["127.0.0.0/8", "::1/128"],
|
||||
"autologinAs": None,
|
||||
"trustBasicAuthentication": False,
|
||||
"checkBasicAuthenticationPassword": True
|
||||
"checkBasicAuthenticationPassword": True,
|
||||
"trustRemoteUser": False,
|
||||
"remoteUserHeader": "REMOTE_USER",
|
||||
"addRemoteUsers": False
|
||||
},
|
||||
"slicing": {
|
||||
"enabled": True,
|
||||
@@ -355,8 +362,6 @@ default_settings = {
|
||||
"subscriptions": []
|
||||
},
|
||||
"api": {
|
||||
"enabled": True,
|
||||
"keyEnforced": False,
|
||||
"key": None,
|
||||
"allowCrossOrigin": False,
|
||||
"apps": {}
|
||||
@@ -408,6 +413,7 @@ default_settings = {
|
||||
"includeCurrentToolInTemps": True,
|
||||
"includeFilenameInOpened": True,
|
||||
"hasBed": True,
|
||||
"hasChamber": False,
|
||||
"repetierStyleTargetTemperature": False,
|
||||
"okBeforeCommandOutput": False,
|
||||
"smoothieTemperatureReporting": False,
|
||||
@@ -966,7 +972,8 @@ class Settings(object):
|
||||
self._migrate_core_system_commands,
|
||||
self._migrate_serial_features,
|
||||
self._migrate_resend_without_ok,
|
||||
self._migrate_string_temperature_profile_values
|
||||
self._migrate_string_temperature_profile_values,
|
||||
self._migrate_blocked_commands
|
||||
)
|
||||
|
||||
for migrate in migrators:
|
||||
@@ -1325,6 +1332,21 @@ class Settings(object):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _migrate_blocked_commands(self, config):
|
||||
if "serial" in config and "blockM0M1" in config["serial"]:
|
||||
blockM0M1 = config["serial"]["blockM0M1"]
|
||||
blockedCommands = config["serial"].get("blockedCommands", [])
|
||||
if blockM0M1:
|
||||
blockedCommands = set(blockedCommands)
|
||||
blockedCommands.add("M0")
|
||||
blockedCommands.add("M1")
|
||||
config["serial"]["blockedCommands"] = sorted(blockedCommands)
|
||||
else:
|
||||
config["serial"]["blockedCommands"] = sorted([v for v in blockedCommands if v not in ("M0", "M1")])
|
||||
del config["serial"]["blockM0M1"]
|
||||
return True
|
||||
return False
|
||||
|
||||
def backup(self, suffix=None, path=None, ext=None, hidden=False):
|
||||
import shutil
|
||||
|
||||
@@ -1347,7 +1369,7 @@ class Settings(object):
|
||||
shutil.copy(self._configfile, backup)
|
||||
return backup
|
||||
|
||||
def save(self, force=False):
|
||||
def save(self, force=False, trigger_event=False):
|
||||
if not self._dirty and not force:
|
||||
return False
|
||||
|
||||
@@ -1363,9 +1385,10 @@ class Settings(object):
|
||||
|
||||
self.load()
|
||||
|
||||
payload = dict(config_hash=self.config_hash,
|
||||
effective_hash=self.effective_hash)
|
||||
eventManager().fire(Events.SETTINGS_UPDATED, payload=payload)
|
||||
if trigger_event:
|
||||
payload = dict(config_hash=self.config_hash,
|
||||
effective_hash=self.effective_hash)
|
||||
eventManager().fire(Events.SETTINGS_UPDATED, payload=payload)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
@@ -140,7 +140,8 @@ class SlicingManager(object):
|
||||
try:
|
||||
slicers[plugin.get_slicer_properties()["type"]] = plugin
|
||||
except Exception:
|
||||
self._logger.exception("Error while getting properties from slicer {}, ignoring it".format(plugin._identifier))
|
||||
self._logger.exception("Error while getting properties from slicer {}, ignoring it".format(plugin._identifier),
|
||||
extra=dict(plugin=plugin._identifier))
|
||||
continue
|
||||
self._slicers = slicers
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ GCODE.gCodeReader = (function(){
|
||||
lines = [];
|
||||
};
|
||||
|
||||
var sortLayers = function(){
|
||||
var sortLayers = function(m){
|
||||
var sortedZ = [];
|
||||
var tmpModel = [];
|
||||
|
||||
@@ -68,10 +68,9 @@ GCODE.gCodeReader = (function(){
|
||||
|
||||
for(var i=0;i<sortedZ.length;i++){
|
||||
if(typeof(z_heights[sortedZ[i]]) === 'undefined')continue;
|
||||
tmpModel[i] = model[z_heights[sortedZ[i]]];
|
||||
tmpModel[i] = m[z_heights[sortedZ[i]]];
|
||||
}
|
||||
model = tmpModel;
|
||||
delete tmpModel;
|
||||
return tmpModel;
|
||||
};
|
||||
|
||||
var prepareLinesIndex = function(){
|
||||
@@ -97,23 +96,23 @@ GCODE.gCodeReader = (function(){
|
||||
}
|
||||
|
||||
var elements = percentageTree.findBest(key);
|
||||
if (elements.length == 0) {
|
||||
if (elements.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return elements[0];
|
||||
};
|
||||
|
||||
var purgeLayers = function(){
|
||||
if(!model) return;
|
||||
var purgeLayers = function(m){
|
||||
if(!m) return;
|
||||
|
||||
var purge;
|
||||
for(var i = 0; i < model.length; i++){
|
||||
for(var i = 0; i < m.length; i++){
|
||||
purge = true;
|
||||
|
||||
if (typeof(model[i]) !== "undefined") {
|
||||
for (var j = 0; j < model[i].length; j++) {
|
||||
if(model[i][j].extrude) {
|
||||
if (typeof(m[i]) !== "undefined") {
|
||||
for (var j = 0; j < m[i].length; j++) {
|
||||
if(m[i][j].extrude) {
|
||||
purge = false;
|
||||
break;
|
||||
}
|
||||
@@ -121,10 +120,12 @@ GCODE.gCodeReader = (function(){
|
||||
}
|
||||
|
||||
if (purge) {
|
||||
model.splice(i, 1);
|
||||
m.splice(i, 1);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
|
||||
return m;
|
||||
};
|
||||
|
||||
// ***** PUBLIC *******
|
||||
@@ -177,10 +178,11 @@ GCODE.gCodeReader = (function(){
|
||||
},
|
||||
|
||||
passDataToRenderer: function(){
|
||||
if (gCodeOptions["sortLayers"]) sortLayers();
|
||||
if (gCodeOptions["purgeEmptyLayers"]) purgeLayers();
|
||||
var m = model;
|
||||
if (gCodeOptions["sortLayers"]) m = sortLayers(m);
|
||||
if (gCodeOptions["purgeEmptyLayers"]) m = purgeLayers(m);
|
||||
prepareLinesIndex();
|
||||
GCODE.renderer.doRender(model, 0);
|
||||
GCODE.renderer.doRender(m, 0);
|
||||
},
|
||||
|
||||
processLayerFromWorker: function(msg){
|
||||
|
||||
@@ -86,6 +86,10 @@ GCODE.renderer = (function(){
|
||||
}
|
||||
|
||||
var reRender = function(){
|
||||
if (!model) return;
|
||||
|
||||
log.debug("Rerendering layer " + layerNumStore + " of " + model.length + " with " + GCODE.renderer.getLayerNumSegments(layerNumStore) + " segments");
|
||||
|
||||
notifyIfViewportChanged();
|
||||
|
||||
var p1 = ctx.transformedPoint(0,0);
|
||||
@@ -356,6 +360,11 @@ GCODE.renderer = (function(){
|
||||
ctx.fill();
|
||||
ctx.stroke();
|
||||
|
||||
// draw origin
|
||||
ctx.beginPath();
|
||||
ctx.arc(0, 0, 2, 0, Math.PI * 2, true);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.strokeStyle = renderOptions["colorGrid"];
|
||||
ctx.lineWidth = lineWidthFactor;
|
||||
|
||||
@@ -409,6 +418,11 @@ GCODE.renderer = (function(){
|
||||
ctx.fill();
|
||||
ctx.stroke();
|
||||
|
||||
// draw origin
|
||||
ctx.beginPath();
|
||||
ctx.arc(0, 0, 2, 0, Math.PI * 2, true);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.strokeStyle = renderOptions["colorGrid"];
|
||||
ctx.lineWidth = lineWidthFactor;
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
var printheadUrl = url + "/printhead";
|
||||
var toolUrl = url + "/tool";
|
||||
var bedUrl = url + "/bed";
|
||||
var chamberUrl = url + "/chamber";
|
||||
var sdUrl = url + "/sd";
|
||||
|
||||
var OctoPrintPrinterClient = function(base) {
|
||||
@@ -27,6 +28,10 @@
|
||||
return this.base.issueCommand(bedUrl, command, payload, opts);
|
||||
};
|
||||
|
||||
OctoPrintPrinterClient.prototype.issueChamberCommand = function (command, payload, opts) {
|
||||
return this.base.issueCommand(chamberUrl, command, payload, opts);
|
||||
};
|
||||
|
||||
OctoPrintPrinterClient.prototype.issueSdCommand = function (command, payload, opts) {
|
||||
return this.base.issueCommand(sdUrl, command, payload, opts);
|
||||
};
|
||||
@@ -90,6 +95,23 @@
|
||||
return this.base.get(getUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintPrinterClient.prototype.getChamberState = function (flags, opts) {
|
||||
flags = flags || {};
|
||||
|
||||
var history = flags.history || undefined;
|
||||
var limit = flags.limit || undefined;
|
||||
|
||||
var getUrl = chamberUrl;
|
||||
if (history) {
|
||||
getUrl += "?history=true";
|
||||
if (limit) {
|
||||
getUrl += "&limit=" + limit;
|
||||
}
|
||||
}
|
||||
|
||||
return this.base.get(getUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintPrinterClient.prototype.getSdState = function (opts) {
|
||||
return this.base.get(sdUrl, opts);
|
||||
};
|
||||
@@ -198,6 +220,26 @@
|
||||
return this.issueBedCommand("offset", payload, opts);
|
||||
};
|
||||
|
||||
OctoPrintPrinterClient.prototype.setChamberTargetTemperature = function (target, opts) {
|
||||
target = target || 0;
|
||||
|
||||
var payload = {
|
||||
target: target
|
||||
};
|
||||
|
||||
return this.issueChamberCommand("target", payload, opts);
|
||||
};
|
||||
|
||||
OctoPrintPrinterClient.prototype.setChamberTemperatureOffset = function (offset, opts) {
|
||||
offset = offset || 0;
|
||||
|
||||
var payload = {
|
||||
offset: offset
|
||||
};
|
||||
|
||||
return this.issueChamberCommand("offset", payload, opts);
|
||||
};
|
||||
|
||||
OctoPrintPrinterClient.prototype.initSd = function (opts) {
|
||||
return this.issueSdCommand("init", {}, opts);
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSorting, defaultFilters, exclusiveFilters, defaultPageSize) {
|
||||
function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSorting, defaultFilters, exclusiveFilters, defaultPageSize, persistPageSize) {
|
||||
var self = this;
|
||||
|
||||
self.listType = listType;
|
||||
@@ -8,6 +8,7 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
self.defaultFilters = defaultFilters;
|
||||
self.exclusiveFilters = exclusiveFilters;
|
||||
self.defaultPageSize = defaultPageSize;
|
||||
self.persistPageSize = !!persistPageSize;
|
||||
|
||||
self.searchFunction = undefined;
|
||||
|
||||
@@ -20,11 +21,12 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
self.currentSorting = ko.observable(self.defaultSorting);
|
||||
self.currentFilters = ko.observableArray(self.defaultFilters);
|
||||
self.selectedItem = ko.observable(undefined);
|
||||
self.filterSearch = ko.observable(true);
|
||||
|
||||
self.storageIds = {
|
||||
"currentSorting": self.listType + "." + "currentSorting",
|
||||
"currentFilters": self.listType + "." + "currentFilters",
|
||||
"pageSize": self.listType + "." + "pageSize",
|
||||
"pageSize": self.listType + "." + "pageSize"
|
||||
};
|
||||
|
||||
//~~ item handling
|
||||
@@ -55,7 +57,7 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
};
|
||||
|
||||
self.isSelected = function(data) {
|
||||
return self.selectedItem() == data;
|
||||
return self.selectedItem() === data;
|
||||
};
|
||||
|
||||
self.isSelectedByMatcher = function(matcher) {
|
||||
@@ -81,14 +83,14 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
self.addItem = function(item) {
|
||||
self.allItems.push(item);
|
||||
self._updateItems();
|
||||
}
|
||||
};
|
||||
|
||||
//~~ pagination
|
||||
|
||||
self.paginatedItems = ko.dependentObservable(function() {
|
||||
if (self.items() == undefined) {
|
||||
if (self.items() === undefined) {
|
||||
return [];
|
||||
} else if (self.pageSize() == 0) {
|
||||
} else if (self.pageSize() === 0) {
|
||||
return self.items();
|
||||
} else {
|
||||
var from = Math.max(self.currentPage() * self.pageSize(), 0);
|
||||
@@ -97,31 +99,33 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
}
|
||||
});
|
||||
self.lastPage = ko.dependentObservable(function() {
|
||||
return (self.pageSize() == 0 ? 1 : Math.ceil(self.items().length / self.pageSize()) - 1);
|
||||
return (self.pageSize() === 0 ? 1 : Math.ceil(self.items().length / self.pageSize()) - 1);
|
||||
});
|
||||
self.pages = ko.dependentObservable(function() {
|
||||
var pages = [];
|
||||
if (self.pageSize() == 0) {
|
||||
var i;
|
||||
|
||||
if (self.pageSize() === 0) {
|
||||
pages.push({ number: 0, text: 1 });
|
||||
} else if (self.lastPage() < 7) {
|
||||
for (var i = 0; i < self.lastPage() + 1; i++) {
|
||||
for (i = 0; i < self.lastPage() + 1; i++) {
|
||||
pages.push({ number: i, text: i+1 });
|
||||
}
|
||||
} else {
|
||||
pages.push({ number: 0, text: 1 });
|
||||
if (self.currentPage() < 5) {
|
||||
for (var i = 1; i < 5; i++) {
|
||||
for (i = 1; i < 5; i++) {
|
||||
pages.push({ number: i, text: i+1 });
|
||||
}
|
||||
pages.push({ number: -1, text: "…"});
|
||||
} else if (self.currentPage() > self.lastPage() - 5) {
|
||||
pages.push({ number: -1, text: "…"});
|
||||
for (var i = self.lastPage() - 4; i < self.lastPage(); i++) {
|
||||
for (i = self.lastPage() - 4; i < self.lastPage(); i++) {
|
||||
pages.push({ number: i, text: i+1 });
|
||||
}
|
||||
} else {
|
||||
pages.push({ number: -1, text: "…"});
|
||||
for (var i = self.currentPage() - 1; i <= self.currentPage() + 1; i++) {
|
||||
for (i = self.currentPage() - 1; i <= self.currentPage() + 1; i++) {
|
||||
pages.push({ number: i, text: i+1 });
|
||||
}
|
||||
pages.push({ number: -1, text: "…"});
|
||||
@@ -176,7 +180,7 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
};
|
||||
|
||||
self.getItem = function(matcher, all) {
|
||||
var index = self.getIndex(matcher, all);
|
||||
@@ -220,6 +224,19 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
|
||||
//~~ filtering
|
||||
|
||||
self.setFilterSearch = function(enabled) {
|
||||
if (self.filterSearch() === enabled)
|
||||
return;
|
||||
|
||||
self.filterSearch(enabled);
|
||||
self.changePage(0);
|
||||
self._updateItems();
|
||||
};
|
||||
|
||||
self.toggleFilterSearch = function() {
|
||||
self.setFilterSearch(!self.filterSearch());
|
||||
};
|
||||
|
||||
self.toggleFilter = function(filter) {
|
||||
if (!_.contains(_.keys(self.supportedFilters), filter))
|
||||
return;
|
||||
@@ -238,7 +255,7 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
for (var i = 0; i < self.exclusiveFilters.length; i++) {
|
||||
if (_.contains(self.exclusiveFilters[i], filter)) {
|
||||
for (var j = 0; j < self.exclusiveFilters[i].length; j++) {
|
||||
if (self.exclusiveFilters[i][j] == filter)
|
||||
if (self.exclusiveFilters[i][j] === filter)
|
||||
continue;
|
||||
self.removeFilter(self.exclusiveFilters[i][j]);
|
||||
}
|
||||
@@ -280,15 +297,19 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
// work on all items
|
||||
var result = self.allItems;
|
||||
|
||||
// filter if necessary
|
||||
var filters = self.currentFilters();
|
||||
_.each(filters, function(filter) {
|
||||
if (typeof filter !== 'undefined' && typeof supportedFilters[filter] !== 'undefined')
|
||||
result = _.filter(result, supportedFilters[filter]);
|
||||
});
|
||||
var hasSearch = typeof self.searchFunction !== 'undefined' && self.searchFunction;
|
||||
|
||||
// filter if we're not searching or have search filtering enabled
|
||||
if (!hasSearch || self.filterSearch()) {
|
||||
var filters = self.currentFilters();
|
||||
_.each(filters, function (filter) {
|
||||
if (typeof filter !== 'undefined' && typeof supportedFilters[filter] !== 'undefined')
|
||||
result = _.filter(result, supportedFilters[filter]);
|
||||
});
|
||||
}
|
||||
|
||||
// search if necessary
|
||||
if (typeof self.searchFunction !== 'undefined' && self.searchFunction) {
|
||||
if (hasSearch) {
|
||||
result = _.filter(result, self.searchFunction);
|
||||
}
|
||||
|
||||
@@ -335,18 +356,18 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
};
|
||||
|
||||
self._savePageSizeToLocalStorage = function(pageSize) {
|
||||
if (self._initializeLocalStorage()) {
|
||||
if (self._initializeLocalStorage() && self.persistPageSize) {
|
||||
localStorage[self.storageIds.pageSize] = pageSize;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.pageSize.subscribe(self._savePageSizeToLocalStorage);
|
||||
|
||||
self._loadPageSizeFromLocalStorage = function() {
|
||||
if (self._initializeLocalStorage) {
|
||||
if (self._initializeLocalStorage() && self.persistPageSize) {
|
||||
self.pageSize(parseInt(localStorage[self.storageIds.pageSize]));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self._initializeLocalStorage = function() {
|
||||
if (!Modernizr.localstorage)
|
||||
@@ -381,13 +402,13 @@ function formatSize(bytes) {
|
||||
}
|
||||
|
||||
function bytesFromSize(size) {
|
||||
if (size == undefined || size.trim() == "") return undefined;
|
||||
if (size === undefined || size.trim() === "") return undefined;
|
||||
|
||||
var parsed = size.match(/^([+]?[0-9]*\.?[0-9]+)(?:\s*)?(.*)$/);
|
||||
var number = parsed[1];
|
||||
var unit = parsed[2].trim();
|
||||
|
||||
if (unit == "") return parseFloat(number);
|
||||
if (unit === "") return parseFloat(number);
|
||||
|
||||
var units = {
|
||||
b: 1,
|
||||
@@ -423,7 +444,7 @@ function formatFuzzyEstimation(seconds, base) {
|
||||
if (!seconds || seconds < 1) return "-";
|
||||
|
||||
var m;
|
||||
if (base != undefined) {
|
||||
if (base !== undefined) {
|
||||
m = moment(base);
|
||||
} else {
|
||||
m = moment();
|
||||
@@ -621,15 +642,17 @@ function ping(url, callback) {
|
||||
}
|
||||
|
||||
function showOfflineOverlay(title, message, reconnectCallback) {
|
||||
if (title == undefined) {
|
||||
if (title === undefined) {
|
||||
title = gettext("Server is offline");
|
||||
}
|
||||
|
||||
$("#offline_overlay_title").text(title);
|
||||
$("#offline_overlay_message").html(message);
|
||||
$("#offline_overlay_reconnect").click(reconnectCallback);
|
||||
if (!$("#offline_overlay").is(":visible"))
|
||||
$("#offline_overlay").show();
|
||||
|
||||
var overlay = $("#offline_overlay");
|
||||
if (!overlay.is(":visible"))
|
||||
overlay.show();
|
||||
}
|
||||
|
||||
function hideOfflineOverlay() {
|
||||
@@ -942,7 +965,7 @@ function showProgressModal(options, promise) {
|
||||
var progressTextFront = $('<span class="progress-text-front"></span>')
|
||||
.width(progress.width());
|
||||
|
||||
if (max == undefined) {
|
||||
if (max === undefined) {
|
||||
progress.addClass("progress-striped active");
|
||||
progressBar.width("100%");
|
||||
}
|
||||
@@ -1289,7 +1312,7 @@ var sizeObservable = function(observable) {
|
||||
},
|
||||
write: function(value) {
|
||||
var result = bytesFromSize(value);
|
||||
if (result != undefined) {
|
||||
if (result !== undefined) {
|
||||
observable(result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,26 +11,12 @@ $(function() {
|
||||
|
||||
//~~ OctoPrint client setup
|
||||
OctoPrint.options.baseurl = BASEURL;
|
||||
OctoPrint.options.apikey = UI_API_KEY;
|
||||
|
||||
var l10n = getQueryParameterByName("l10n");
|
||||
if (l10n) {
|
||||
OctoPrint.options.locale = l10n;
|
||||
}
|
||||
|
||||
OctoPrint.socket.onMessage("connected", function(data) {
|
||||
var payload = data.data;
|
||||
OctoPrint.options.apikey = payload.apikey;
|
||||
|
||||
// update the API key directly in jquery's ajax options too,
|
||||
// to ensure the fileupload plugin and any plugins still using
|
||||
// $.ajax directly still work fine too
|
||||
UI_API_KEY = payload["apikey"];
|
||||
$.ajaxSetup({
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
});
|
||||
|
||||
//~~ some CoreUI specific stuff we put into OctoPrint.coreui
|
||||
|
||||
OctoPrint.coreui = (function() {
|
||||
@@ -123,31 +109,51 @@ $(function() {
|
||||
browserVisibilityCallbacks.push(callback);
|
||||
};
|
||||
exports.hashFromTabChange = false;
|
||||
exports.updateTab = function() {
|
||||
exports.onTabChange = function(current, previous) {
|
||||
log.debug("Selected OctoPrint tab changed: previous = " + previous + ", current = " + current);
|
||||
OctoPrint.coreui.selectedTab = current;
|
||||
callViewModels(allViewModels, "onTabChange", [current, previous]);
|
||||
};
|
||||
exports.onAfterTabChange = function(current, previous) {
|
||||
callViewModels(allViewModels, "onAfterTabChange", [current, previous]);
|
||||
};
|
||||
exports.updateTab = function(force) {
|
||||
force = !!force;
|
||||
|
||||
if (exports.hashFromTabChange) {
|
||||
exports.hashFromTabChange = false;
|
||||
return;
|
||||
}
|
||||
|
||||
var selectTab = function(tab) {
|
||||
if (tab.hash !== exports.selectedTab) {
|
||||
if ($(tab).parent("li").hasClass("active") && force) {
|
||||
var current = tab.hash;
|
||||
var previous = exports.selectedTab;
|
||||
exports.onTabChange(current, previous);
|
||||
exports.onAfterTabChange(current, previous);
|
||||
} else {
|
||||
$(tab).tab("show");
|
||||
}
|
||||
} else {
|
||||
window.location.hash = tab.hash;
|
||||
}
|
||||
};
|
||||
|
||||
var tabs = $('#tabs');
|
||||
|
||||
var hashtag = window.location.hash;
|
||||
if (hashtag) {
|
||||
var selectedTab = tabs.find('a[href="' + hashtag + '"]:visible');
|
||||
if (selectedTab.length) {
|
||||
selectedTab.tab("show");
|
||||
selectTab(selectedTab[0]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var firstTab = tabs.find('a[data-toggle=tab]:visible').eq(0);
|
||||
if (firstTab.length) {
|
||||
var firstHash = firstTab[0].hash;
|
||||
if (firstHash !== exports.selectedTab) {
|
||||
firstTab.tab("show");
|
||||
} else {
|
||||
window.location.hash = firstHash;
|
||||
}
|
||||
selectTab(firstTab[0]);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -170,11 +176,6 @@ $(function() {
|
||||
}
|
||||
});
|
||||
|
||||
// send the current UI API key with any request
|
||||
$.ajaxSetup({
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
|
||||
//~~ Initialize file upload plugin
|
||||
|
||||
$.widget("blueimp.fileupload", $.blueimp.fileupload, {
|
||||
@@ -538,27 +539,17 @@ $(function() {
|
||||
};
|
||||
|
||||
// Allow components to react to tab change
|
||||
var onTabChange = function(current, previous) {
|
||||
log.debug("Selected OctoPrint tab changed: previous = " + previous + ", current = " + current);
|
||||
OctoPrint.coreui.selectedTab = current;
|
||||
callViewModels(allViewModels, "onTabChange", [current, previous]);
|
||||
};
|
||||
|
||||
var onAfterTabChange = function(current, previous) {
|
||||
callViewModels(allViewModels, "onAfterTabChange", [current, previous]);
|
||||
};
|
||||
|
||||
var tabs = $('#tabs').find('a[data-toggle="tab"]');
|
||||
tabs.on('show', function (e) {
|
||||
var current = e.target.hash;
|
||||
var previous = e.relatedTarget ? e.relatedTarget.hash : undefined;
|
||||
onTabChange(current, previous);
|
||||
OctoPrint.coreui.onTabChange(current, previous);
|
||||
});
|
||||
|
||||
tabs.on('shown', function (e) {
|
||||
var current = e.target.hash;
|
||||
var previous = e.relatedTarget ? e.relatedTarget.hash : undefined;
|
||||
onAfterTabChange(current, previous);
|
||||
OctoPrint.coreui.onAfterTabChange(current, previous);
|
||||
|
||||
// make sure we also update the hash but stick to the current scroll position
|
||||
var scrollmem = $('body').scrollTop() || $('html').scrollTop();
|
||||
@@ -713,7 +704,7 @@ $(function() {
|
||||
|
||||
// this will also allow selecting any tabs that will be hidden later due to overflowing since our
|
||||
// overflow plugin tabdrop hasn't run yet
|
||||
OctoPrint.coreui.updateTab();
|
||||
OctoPrint.coreui.updateTab(true);
|
||||
|
||||
// Use bootstrap tabdrop for tabs and pills
|
||||
$('.nav-pills, .nav-tabs').tabdrop();
|
||||
|
||||
@@ -235,6 +235,10 @@ $(function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onEventDisconnected = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
var connectionTab = $("#connection");
|
||||
connectionTab.on("show", function() {
|
||||
|
||||
@@ -73,7 +73,7 @@ $(function() {
|
||||
tools[extruder]["name"](gettext("Tool") + " " + extruder);
|
||||
tools[extruder]["key"]("tool" + extruder);
|
||||
}
|
||||
} else {
|
||||
} else if (numExtruders === 1) {
|
||||
// only one extruder, no need to add numbers
|
||||
tools[0] = self._createToolEntry();
|
||||
tools[0]["name"](gettext("Hotend"));
|
||||
|
||||
@@ -1139,10 +1139,12 @@ $(function() {
|
||||
}).sort();
|
||||
extensions = extensions.join(", ");
|
||||
var error = "<p>"
|
||||
+ _.sprintf(gettext("Could not upload the file. Make sure that it is a valid file with one of these extensions: %(extensions)s"),
|
||||
+ _.sprintf(gettext("Could not upload the file. Make sure that it is a readable, valid file with one of these extensions: %(extensions)s"),
|
||||
{extensions: extensions})
|
||||
+ "</p>";
|
||||
error += pnotifyAdditionalInfo("<pre>" + data.jqXHR.responseText + "</pre>");
|
||||
if (data.jqXHR.responseText) {
|
||||
error += pnotifyAdditionalInfo("<pre>" + data.jqXHR.responseText + "</pre>");
|
||||
}
|
||||
new PNotify({
|
||||
title: "Upload failed",
|
||||
text: error,
|
||||
|
||||
@@ -140,34 +140,27 @@ $(function() {
|
||||
var currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
if (!currentProfileData) return;
|
||||
|
||||
var options = {
|
||||
reader: {},
|
||||
renderer: {}
|
||||
};
|
||||
var dirty = false;
|
||||
|
||||
var toolOffsets = self._retrieveToolOffsets(currentProfileData);
|
||||
if (toolOffsets) {
|
||||
GCODE.ui.updateOptions({
|
||||
reader: {
|
||||
toolOffsets: toolOffsets
|
||||
}
|
||||
});
|
||||
options.reader.toolOffsets = toolOffsets;
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
var bedDimensions = self._retrieveBedDimensions(currentProfileData);
|
||||
if (bedDimensions) {
|
||||
GCODE.ui.updateOptions({
|
||||
renderer: {
|
||||
bed: bedDimensions
|
||||
},
|
||||
reader: {
|
||||
bed: bedDimensions
|
||||
}
|
||||
});
|
||||
options.renderer.bed = bedDimensions;
|
||||
options.reader.bed = bedDimensions;
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
var axesConfiguration = self._retrieveAxesConfiguration(currentProfileData);
|
||||
if (axesConfiguration) {
|
||||
GCODE.ui.updateOptions({
|
||||
renderer: {
|
||||
invertAxes: axesConfiguration
|
||||
}
|
||||
});
|
||||
if (dirty) {
|
||||
GCODE.ui.updateOptions(options);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ $(function() {
|
||||
custom_box: false
|
||||
},
|
||||
heatedBed: true,
|
||||
heatedChamber: false,
|
||||
axes: {
|
||||
x: {speed: 6000, inverted: false},
|
||||
y: {speed: 6000, inverted: false},
|
||||
@@ -60,6 +61,7 @@ $(function() {
|
||||
});
|
||||
|
||||
self.heatedBed = ko.observable();
|
||||
self.heatedChamber = ko.observable();
|
||||
|
||||
self.nozzleDiameter = ko.observable();
|
||||
self.extruders = ko.observable();
|
||||
@@ -209,6 +211,7 @@ $(function() {
|
||||
}
|
||||
|
||||
self.heatedBed(data.heatedBed);
|
||||
self.heatedChamber(data.heatedChamber);
|
||||
|
||||
self.nozzleDiameter(data.extruder.nozzleDiameter);
|
||||
self.sharedNozzle(data.extruder.sharedNozzle);
|
||||
@@ -269,6 +272,7 @@ $(function() {
|
||||
origin: self.volumeOrigin()
|
||||
},
|
||||
heatedBed: self.heatedBed(),
|
||||
heatedChamber: self.heatedChamber(),
|
||||
extruder: {
|
||||
count: parseInt(self.extruders()),
|
||||
offsets: [
|
||||
|
||||
@@ -108,8 +108,6 @@ $(function() {
|
||||
})));
|
||||
self.locale_languages = _.keys(AVAILABLE_LOCALES);
|
||||
|
||||
self.api_enabled = ko.observable(undefined);
|
||||
self.api_keyEnforced = ko.observable(undefined);
|
||||
self.api_key = ko.observable(undefined);
|
||||
self.api_allowCrossOrigin = ko.observable(undefined);
|
||||
|
||||
@@ -156,6 +154,7 @@ $(function() {
|
||||
|
||||
self.serial_port = ko.observable();
|
||||
self.serial_baudrate = ko.observable();
|
||||
self.serial_exclusive = ko.observable();
|
||||
self.serial_portOptions = ko.observableArray([]);
|
||||
self.serial_baudrateOptions = ko.observableArray([]);
|
||||
self.serial_autoconnect = ko.observable(undefined);
|
||||
@@ -175,10 +174,12 @@ $(function() {
|
||||
self.serial_additionalBaudrates = ko.observable(undefined);
|
||||
self.serial_longRunningCommands = ko.observable(undefined);
|
||||
self.serial_checksumRequiringCommands = ko.observable(undefined);
|
||||
self.serial_blockedCommands = ko.observable(undefined);
|
||||
self.serial_pausingCommands = ko.observable(undefined);
|
||||
self.serial_emergencyCommands = ko.observable(undefined);
|
||||
self.serial_helloCommand = ko.observable(undefined);
|
||||
self.serial_serialErrorBehaviour = ko.observable("cancel");
|
||||
self.serial_triggerOkForM29 = ko.observable(undefined);
|
||||
self.serial_blockM0M1 = ko.observable(undefined);
|
||||
self.serial_waitForStart = ko.observable(undefined);
|
||||
self.serial_sendChecksum = ko.observable("print");
|
||||
self.serial_sdRelativePath = ko.observable(undefined);
|
||||
@@ -302,7 +303,7 @@ $(function() {
|
||||
});
|
||||
|
||||
self.addTemperatureProfile = function() {
|
||||
self.temperature_profiles.push({name: "New", extruder:0, bed:0});
|
||||
self.temperature_profiles.push({name: "New", extruder:0, bed:0, chamber:0});
|
||||
};
|
||||
|
||||
self.removeTemperatureProfile = function(profile) {
|
||||
@@ -784,6 +785,9 @@ $(function() {
|
||||
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) },
|
||||
blockedCommands: function() { return splitTextToArray(self.serial_blockedCommands(), ",", true) },
|
||||
pausingCommands: function() { return splitTextToArray(self.serial_pausingCommands(), ",", true) },
|
||||
emergencyCommands: function() {return splitTextToArray(self.serial_emergencyCommands(), ",", true) },
|
||||
externalHeatupDetection: function() { return !self.serial_disableExternalHeatupDetection()},
|
||||
alwaysSendChecksum: function() { return self.serial_sendChecksum() === "always"},
|
||||
neverSendChecksum: function() { return self.serial_sendChecksum() === "never"},
|
||||
@@ -821,7 +825,8 @@ $(function() {
|
||||
result.push({
|
||||
name: profile.name,
|
||||
extruder: Math.floor(_.isNumber(profile.extruder) ? profile.extruder : parseInt(profile.extruder)),
|
||||
bed: Math.floor(_.isNumber(profile.bed) ? profile.bed : parseInt(profile.bed))
|
||||
bed: Math.floor(_.isNumber(profile.bed) ? profile.bed : parseInt(profile.bed)),
|
||||
chamber: Math.floor(_.isNumber(profile.chamber) ? profile.chamber : (_.isNumber(parseInt(profile.chamber)) ? parseInt(profile.chamber) : 0))
|
||||
});
|
||||
} catch (ex) {
|
||||
// ignore
|
||||
@@ -920,6 +925,9 @@ $(function() {
|
||||
additionalBaudrates: function(value) { self.serial_additionalBaudrates(value.join(", "))},
|
||||
longRunningCommands: function(value) { self.serial_longRunningCommands(value.join(", "))},
|
||||
checksumRequiringCommands: function(value) { self.serial_checksumRequiringCommands(value.join(", "))},
|
||||
blockedCommands: function(value) { self.serial_blockedCommands(value.join(", "))},
|
||||
pausingCommands: function(value) { self.serial_pausingCommands(value.join(", "))},
|
||||
emergencyCommands: function(value) { self.serial_emergencyCommands(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")}},
|
||||
|
||||
@@ -72,13 +72,24 @@ $(function() {
|
||||
self.loginStateSubscription = undefined;
|
||||
|
||||
self.tools = ko.observableArray([]);
|
||||
|
||||
self.hasTools = ko.pureComputed(function() {
|
||||
return self.tools().length > 0;
|
||||
});
|
||||
self.hasBed = ko.observable(true);
|
||||
self.hasChamber = ko.observable(false);
|
||||
|
||||
self.visible = ko.pureComputed(function() {
|
||||
return self.hasTools() || self.hasBed();
|
||||
});
|
||||
|
||||
self.bedTemp = self._createToolEntry();
|
||||
self.bedTemp["name"](gettext("Bed"));
|
||||
self.bedTemp["key"]("bed");
|
||||
|
||||
self.chamberTemp = self._createToolEntry();
|
||||
self.chamberTemp["name"](gettext("Chamber"));
|
||||
self.chamberTemp["key"]("chamber");
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
@@ -139,6 +150,14 @@ $(function() {
|
||||
self.hasBed(false);
|
||||
}
|
||||
|
||||
// heated chamber
|
||||
if (currentProfileData && currentProfileData.heatedChamber()) {
|
||||
self.hasChamber(true);
|
||||
heaterOptions["chamber"] = {name: gettext("Chamber"), color: "black"};
|
||||
} else {
|
||||
self.hasChamber(false);
|
||||
}
|
||||
|
||||
// write back
|
||||
self.heaterOptions(heaterOptions);
|
||||
self.tools(tools);
|
||||
@@ -154,6 +173,7 @@ $(function() {
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated);
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().extruder.sharedNozzle.subscribe(self._printerProfileUpdated);
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().heatedBed.subscribe(self._printerProfileUpdated);
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().heatedChamber.subscribe(self._printerProfileUpdated);
|
||||
});
|
||||
|
||||
self.temperatures = [];
|
||||
@@ -229,6 +249,14 @@ $(function() {
|
||||
self.bedTemp["target"](0);
|
||||
}
|
||||
|
||||
if (lastData.hasOwnProperty("chamber")) {
|
||||
self.chamberTemp["actual"](lastData.chamber.actual);
|
||||
self.chamberTemp["target"](lastData.chamber.target);
|
||||
} else {
|
||||
self.chamberTemp["actual"](0);
|
||||
self.chamberTemp["target"](0);
|
||||
}
|
||||
|
||||
if (!CONFIG_TEMPERATURE_GRAPH) return;
|
||||
|
||||
self.temperatures = self._processTemperatureData(serverTime, data, self.temperatures);
|
||||
@@ -255,6 +283,12 @@ $(function() {
|
||||
} else {
|
||||
self.bedTemp["offset"](0);
|
||||
}
|
||||
|
||||
if (data.hasOwnProperty("chamber")) {
|
||||
self.chamberTemp["offset"](data["chamber"]);
|
||||
} else {
|
||||
self.chamberTemp["offset"](0);
|
||||
}
|
||||
};
|
||||
|
||||
self._processTemperatureData = function(serverTime, data, result) {
|
||||
@@ -300,6 +334,27 @@ $(function() {
|
||||
return result;
|
||||
};
|
||||
|
||||
self.profileText = function(heater, profile) {
|
||||
var text = gettext("Set %(name)s (%(value)s)");
|
||||
|
||||
var value;
|
||||
if (heater.key() === "bed") {
|
||||
value = profile.bed;
|
||||
} else if (heater.key() === "chamber") {
|
||||
value = profile.chamber;
|
||||
} else {
|
||||
value = profile.extruder;
|
||||
}
|
||||
|
||||
if (value === 0 || value === undefined) {
|
||||
value = gettext("Off");
|
||||
} else {
|
||||
value = "" + value + "°C";
|
||||
}
|
||||
|
||||
return _.sprintf(text, {name: profile.name, value: value});
|
||||
};
|
||||
|
||||
self.updatePlot = function() {
|
||||
var graph = $("#temperature-graph");
|
||||
if (!graph.length) return; // no graph
|
||||
@@ -565,7 +620,18 @@ $(function() {
|
||||
if (!profile) return OctoPrintClient.createRejectedDeferred();
|
||||
|
||||
self.clearAutosendTarget(item);
|
||||
return self.setTargetToValue(item, (item.key() === "bed" ? profile.bed : profile.extruder));
|
||||
|
||||
var target;
|
||||
if (item.key() === "bed") {
|
||||
target = profile.bed;
|
||||
} else if (item.key() === "chamber") {
|
||||
target = profile.chamber;
|
||||
} else {
|
||||
target = profile.extruder;
|
||||
}
|
||||
|
||||
if (target === undefined) target = 0;
|
||||
return self.setTargetToValue(item, target);
|
||||
};
|
||||
|
||||
self.setTargetToZero = function(item) {
|
||||
@@ -592,6 +658,9 @@ $(function() {
|
||||
if (item.key() === "bed") {
|
||||
return self._setBedTemperature(value)
|
||||
.done(onSuccess);
|
||||
} else if (item.key() === "chamber") {
|
||||
return self._setChamberTemperature(value)
|
||||
.done(onSuccess);
|
||||
} else {
|
||||
return self._setToolTemperature(item.key(), value)
|
||||
.done(onSuccess);
|
||||
@@ -679,6 +748,9 @@ $(function() {
|
||||
if (item.key() === "bed") {
|
||||
return self._setBedOffset(value)
|
||||
.done(onSuccess);
|
||||
} else if (item.key() === "chamber") {
|
||||
return self._setChamberOffset(value)
|
||||
.done(onSuccess);
|
||||
} else {
|
||||
return self._setToolOffset(item.key(), value)
|
||||
.done(onSuccess);
|
||||
@@ -705,6 +777,14 @@ $(function() {
|
||||
return OctoPrint.printer.setBedTemperatureOffset(parseInt(offset));
|
||||
};
|
||||
|
||||
self._setChamberTemperature = function(temperature) {
|
||||
return OctoPrint.printer.setChamberTargetTemperature(parseInt(temperature));
|
||||
};
|
||||
|
||||
self._setChamberOffset = function(offset) {
|
||||
return OctoPrint.printer.setChamberTemperatureOffset(parseInt(offset));
|
||||
};
|
||||
|
||||
self._replaceLegendLabel = function(index, series, value, emph) {
|
||||
var showFahrenheit = self._shallShowFahrenheit();
|
||||
|
||||
|
||||
@@ -193,30 +193,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onSettingsPreventRefresh = function() {
|
||||
if (!self.finishing && self.isDialogActive()
|
||||
&& hasDataChanged(self.settingsViewModel.getLocalData(), self.settingsViewModel.lastReceivedSettings)) {
|
||||
var preventSettingsRefreshDialog = false;
|
||||
callViewModels(self.allViewModels, "onWizardPreventSettingsRefreshDialog", function(method) {
|
||||
// if any of our methods returns that it wants to prevent the dialog
|
||||
// we'll need to set preventSettingsRefreshDialog to true
|
||||
//
|
||||
// order is important here - the method call needs to happen
|
||||
// first, or it won't happen after the flag has been
|
||||
// set once due to the || making further evaluation unnecessary
|
||||
// then
|
||||
preventSettingsRefreshDialog = (method() === true) || preventSettingsRefreshDialog;
|
||||
});
|
||||
|
||||
// we have local changes, show update dialog
|
||||
if (preventSettingsRefreshDialog) {
|
||||
return false;
|
||||
} else {
|
||||
self.settingsViewModel.settingsUpdatedDialog.modal("show");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
return self.isDialogActive();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+44
-40
@@ -1,5 +1,5 @@
|
||||
/* ===========================================================
|
||||
* bootstrap-modal.js v2.1
|
||||
* bootstrap-modal.js v2.2.5
|
||||
* ===========================================================
|
||||
* Copyright 2012 Jordan Schroter
|
||||
*
|
||||
@@ -33,12 +33,17 @@
|
||||
constructor: Modal,
|
||||
|
||||
init: function (element, options) {
|
||||
var that = this;
|
||||
|
||||
this.options = options;
|
||||
|
||||
this.$element = $(element)
|
||||
.delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this));
|
||||
|
||||
this.options.remote && this.$element.find('.modal-body').load(this.options.remote);
|
||||
this.options.remote && this.$element.find('.modal-body').load(this.options.remote, function () {
|
||||
var e = $.Event('loaded');
|
||||
that.$element.trigger(e);
|
||||
});
|
||||
|
||||
var manager = typeof this.options.manager === 'function' ?
|
||||
this.options.manager.call(this) : this.options.manager;
|
||||
@@ -76,7 +81,7 @@
|
||||
|
||||
this.$element.trigger(e);
|
||||
|
||||
if (!this.isShown || e.isDefaultPrevented()) return (this.isShown = false);
|
||||
if (!this.isShown || e.isDefaultPrevented()) return;
|
||||
|
||||
this.isShown = false;
|
||||
|
||||
@@ -126,8 +131,6 @@
|
||||
.css(prop, '')
|
||||
.css('min-height', '');
|
||||
|
||||
var modalOverflow = $(window).height() - 10 < this.$element.height();
|
||||
|
||||
if (value){
|
||||
this.$element.find('.modal-body')
|
||||
.css('overflow', 'auto')
|
||||
@@ -139,6 +142,8 @@
|
||||
.css('min-height', minHeight);
|
||||
}
|
||||
|
||||
var modalOverflow = $(window).height() - 10 < this.$element.height();
|
||||
|
||||
if (modalOverflow || this.options.modalOverflow) {
|
||||
this.$element
|
||||
.css('margin-top', 0)
|
||||
@@ -156,23 +161,24 @@
|
||||
if (this.isShown && this.options.consumeTab) {
|
||||
this.$element.on('keydown.tabindex.modal', '[data-tabindex]', function (e) {
|
||||
if (e.keyCode && e.keyCode == 9){
|
||||
var $next = $(this),
|
||||
$rollover = $(this);
|
||||
var elements = [],
|
||||
tabindex = Number($(this).data('tabindex'));
|
||||
|
||||
that.$element.find('[data-tabindex]:enabled:not([readonly])').each(function (e) {
|
||||
if (!e.shiftKey){
|
||||
$next = $next.data('tabindex') < $(this).data('tabindex') ?
|
||||
$next = $(this) :
|
||||
$rollover = $(this);
|
||||
} else {
|
||||
$next = $next.data('tabindex') > $(this).data('tabindex') ?
|
||||
$next = $(this) :
|
||||
$rollover = $(this);
|
||||
}
|
||||
that.$element.find('[data-tabindex]:enabled:visible:not([readonly])').each(function (ev) {
|
||||
elements.push(Number($(this).data('tabindex')));
|
||||
});
|
||||
elements.sort(function(a,b){return a-b});
|
||||
|
||||
$next[0] !== $(this)[0] ?
|
||||
$next.focus() : $rollover.focus();
|
||||
var arrayPos = $.inArray(tabindex, elements);
|
||||
if (!e.shiftKey){
|
||||
arrayPos < elements.length-1 ?
|
||||
that.$element.find('[data-tabindex='+elements[arrayPos+1]+']').focus() :
|
||||
that.$element.find('[data-tabindex='+elements[0]+']').focus();
|
||||
} else {
|
||||
arrayPos == 0 ?
|
||||
that.$element.find('[data-tabindex='+elements[elements.length-1]+']').focus() :
|
||||
that.$element.find('[data-tabindex='+elements[arrayPos-1]+']').focus();
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
}
|
||||
@@ -209,10 +215,6 @@
|
||||
},
|
||||
|
||||
hideModal: function () {
|
||||
this.$element
|
||||
.hide()
|
||||
.trigger('hidden');
|
||||
|
||||
var prop = this.options.height ? 'height' : 'max-height';
|
||||
var value = this.options.height || this.options.maxHeight;
|
||||
|
||||
@@ -222,6 +224,9 @@
|
||||
.css(prop, '');
|
||||
}
|
||||
|
||||
this.$element
|
||||
.hide()
|
||||
.trigger('hidden');
|
||||
},
|
||||
|
||||
removeLoading: function () {
|
||||
@@ -297,28 +302,26 @@
|
||||
|
||||
destroy: function () {
|
||||
var e = $.Event('destroy');
|
||||
|
||||
this.$element.trigger(e);
|
||||
|
||||
if (e.isDefaultPrevented()) return;
|
||||
|
||||
this.teardown();
|
||||
},
|
||||
|
||||
teardown: function () {
|
||||
if (!this.$parent.length){
|
||||
this.$element.remove();
|
||||
this.$element = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.$parent !== this.$element.parent()){
|
||||
this.$element.appendTo(this.$parent);
|
||||
}
|
||||
|
||||
this.$element.off('.modal');
|
||||
this.$element.removeData('modal');
|
||||
this.$element
|
||||
.off('.modal')
|
||||
.removeData('modal')
|
||||
.removeClass('in')
|
||||
.attr('aria-hidden', true);
|
||||
|
||||
if (this.$parent !== this.$element.parent()) {
|
||||
this.$element.appendTo(this.$parent);
|
||||
} else if (!this.$parent.length) {
|
||||
// modal is not part of the DOM so remove it.
|
||||
this.$element.remove();
|
||||
this.$element = null;
|
||||
}
|
||||
|
||||
this.$element.trigger('destroyed');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -354,7 +357,8 @@
|
||||
resize: false,
|
||||
attentionAnimation: 'shake',
|
||||
manager: 'body',
|
||||
spinner: '<div class="loading-spinner" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>'
|
||||
spinner: '<div class="loading-spinner" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>',
|
||||
backdropTemplate: '<div class="modal-backdrop" />'
|
||||
};
|
||||
|
||||
$.fn.modal.Constructor = Modal;
|
||||
|
||||
+60
-49
@@ -1,5 +1,5 @@
|
||||
/* ===========================================================
|
||||
* bootstrap-modalmanager.js v2.1
|
||||
* bootstrap-modalmanager.js v2.2.5
|
||||
* ===========================================================
|
||||
* Copyright 2012 Jordan Schroter.
|
||||
*
|
||||
@@ -79,15 +79,14 @@
|
||||
modal.$element.appendTo(modal.$container);
|
||||
|
||||
that.backdrop(modal, function () {
|
||||
|
||||
modal.$element.show();
|
||||
|
||||
if (transition) {
|
||||
//modal.$element[0].style.display = 'run-in';
|
||||
if (transition) {
|
||||
//modal.$element[0].style.display = 'run-in';
|
||||
modal.$element[0].offsetWidth;
|
||||
//modal.$element.one($.support.transition.end, function () { modal.$element[0].style.display = 'block' });
|
||||
//modal.$element.one($.support.transition.end, function () { modal.$element[0].style.display = 'block' });
|
||||
}
|
||||
|
||||
|
||||
modal.layout();
|
||||
|
||||
modal.$element
|
||||
@@ -111,48 +110,40 @@
|
||||
}));
|
||||
|
||||
modal.$element.on('hidden.modalmanager', targetIsSelf(function (e) {
|
||||
|
||||
that.backdrop(modal);
|
||||
|
||||
if (modal.$backdrop){
|
||||
$.support.transition && modal.$element.hasClass('fade') ?
|
||||
modal.$backdrop.one($.support.transition.end, function () { that.destroyModal(modal) }) :
|
||||
that.destroyModal(modal);
|
||||
} else {
|
||||
// handle the case when a modal may have been removed from the dom before this callback executes
|
||||
if (!modal.$element.parent().length) {
|
||||
that.destroyModal(modal);
|
||||
} else if (modal.$backdrop){
|
||||
var transition = $.support.transition && modal.$element.hasClass('fade');
|
||||
|
||||
// trigger a relayout due to firebox's buggy transition end event
|
||||
if (transition) { modal.$element[0].offsetWidth; }
|
||||
$.support.transition && modal.$element.hasClass('fade') ?
|
||||
modal.$backdrop.one($.support.transition.end, function () { modal.destroy(); }) :
|
||||
modal.destroy();
|
||||
} else {
|
||||
modal.destroy();
|
||||
}
|
||||
|
||||
}));
|
||||
|
||||
modal.$element.on('destroy.modalmanager', targetIsSelf(function (e) {
|
||||
that.removeModal(modal);
|
||||
modal.$element.on('destroyed.modalmanager', targetIsSelf(function (e) {
|
||||
that.destroyModal(modal);
|
||||
}));
|
||||
|
||||
},
|
||||
|
||||
destroyModal: function (modal) {
|
||||
|
||||
modal.destroy();
|
||||
|
||||
var hasOpenModal = this.hasOpenModal();
|
||||
|
||||
this.$element.toggleClass('modal-open', hasOpenModal);
|
||||
|
||||
if (!hasOpenModal){
|
||||
this.$element.removeClass('page-overflow');
|
||||
getOpenModals: function () {
|
||||
var openModals = [];
|
||||
for (var i = 0; i < this.stack.length; i++){
|
||||
if (this.stack[i].isShown) openModals.push(this.stack[i]);
|
||||
}
|
||||
|
||||
this.removeContainer(modal);
|
||||
|
||||
this.setFocus();
|
||||
return openModals;
|
||||
},
|
||||
|
||||
hasOpenModal: function () {
|
||||
for (var i = 0; i < this.stack.length; i++){
|
||||
if (this.stack[i].isShown) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
return this.getOpenModals().length > 0;
|
||||
},
|
||||
|
||||
setFocus: function () {
|
||||
@@ -165,13 +156,24 @@
|
||||
if (!topModal) return;
|
||||
|
||||
topModal.focus();
|
||||
|
||||
},
|
||||
|
||||
removeModal: function (modal) {
|
||||
destroyModal: function (modal) {
|
||||
modal.$element.off('.modalmanager');
|
||||
if (modal.$backdrop) this.removeBackdrop.call(modal);
|
||||
if (modal.$backdrop) this.removeBackdrop(modal);
|
||||
this.stack.splice(this.getIndexOfModal(modal), 1);
|
||||
|
||||
var hasOpenModal = this.hasOpenModal();
|
||||
|
||||
this.$element.toggleClass('modal-open', hasOpenModal);
|
||||
|
||||
if (!hasOpenModal){
|
||||
this.$element.removeClass('page-overflow');
|
||||
}
|
||||
|
||||
this.removeContainer(modal);
|
||||
|
||||
this.setFocus();
|
||||
},
|
||||
|
||||
getModalAt: function (index) {
|
||||
@@ -209,11 +211,12 @@
|
||||
modal.$backdrop = null;
|
||||
},
|
||||
|
||||
createBackdrop: function (animate) {
|
||||
createBackdrop: function (animate, tmpl) {
|
||||
var $backdrop;
|
||||
|
||||
if (!this.$backdropHandle) {
|
||||
$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
|
||||
$backdrop = $(tmpl)
|
||||
.addClass(animate)
|
||||
.appendTo(this.$element);
|
||||
} else {
|
||||
$backdrop = this.$backdropHandle;
|
||||
@@ -222,7 +225,7 @@
|
||||
this.isLoading && this.removeSpinner();
|
||||
}
|
||||
|
||||
return $backdrop
|
||||
return $backdrop;
|
||||
},
|
||||
|
||||
removeContainer: function (modal) {
|
||||
@@ -234,8 +237,7 @@
|
||||
var $container;
|
||||
|
||||
$container = $('<div class="modal-scrollable">')
|
||||
.css('z-index', getzIndex( 'modal',
|
||||
modal ? this.getIndexOfModal(modal) : this.stack.length ))
|
||||
.css('z-index', getzIndex('modal', this.getOpenModals().length))
|
||||
.appendTo(this.$element);
|
||||
|
||||
if (modal && modal.options.backdrop != 'static') {
|
||||
@@ -260,9 +262,9 @@
|
||||
if (modal.isShown && showBackdrop) {
|
||||
var doAnimate = $.support.transition && animate && !this.$backdropHandle;
|
||||
|
||||
modal.$backdrop = this.createBackdrop(animate);
|
||||
modal.$backdrop = this.createBackdrop(animate, modal.options.backdropTemplate);
|
||||
|
||||
modal.$backdrop.css('z-index', getzIndex( 'backdrop', this.getIndexOfModal(modal) ));
|
||||
modal.$backdrop.css('z-index', getzIndex( 'backdrop', this.getOpenModals().length ));
|
||||
|
||||
if (doAnimate) modal.$backdrop[0].offsetWidth; // force reflow
|
||||
|
||||
@@ -311,16 +313,18 @@
|
||||
|
||||
if (!this.isLoading) {
|
||||
|
||||
this.$backdropHandle = this.createBackdrop('fade');
|
||||
this.$backdropHandle = this.createBackdrop('fade', this.options.backdropTemplate);
|
||||
|
||||
this.$backdropHandle[0].offsetWidth; // force reflow
|
||||
|
||||
var openModals = this.getOpenModals();
|
||||
|
||||
this.$backdropHandle
|
||||
.css('z-index', getzIndex('backdrop', this.stack.length))
|
||||
.css('z-index', getzIndex('backdrop', openModals.length + 1))
|
||||
.addClass('in');
|
||||
|
||||
var $spinner = $(this.options.spinner)
|
||||
.css('z-index', getzIndex('modal', this.stack.length))
|
||||
.css('z-index', getzIndex('modal', openModals.length + 1))
|
||||
.appendTo(this.$element)
|
||||
.addClass('in');
|
||||
|
||||
@@ -381,7 +385,7 @@
|
||||
// if Boostsrap namespaced events, this would not be needed.
|
||||
function targetIsSelf(callback){
|
||||
return function (e) {
|
||||
if (this === e.target){
|
||||
if (e && this === e.target){
|
||||
return callback.apply(this, arguments);
|
||||
}
|
||||
}
|
||||
@@ -404,9 +408,16 @@
|
||||
$.fn.modalmanager.defaults = {
|
||||
backdropLimit: 999,
|
||||
resize: true,
|
||||
spinner: '<div class="loading-spinner fade" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>'
|
||||
spinner: '<div class="loading-spinner fade" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>',
|
||||
backdropTemplate: '<div class="modal-backdrop" />'
|
||||
};
|
||||
|
||||
$.fn.modalmanager.Constructor = ModalManager
|
||||
|
||||
// ModalManager handles the modal-open class so we need
|
||||
// to remove conflicting bootstrap 3 event handlers
|
||||
$(function () {
|
||||
$(document).off('show.bs.modal').off('hidden.bs.modal');
|
||||
});
|
||||
|
||||
}(jQuery);
|
||||
@@ -1,19 +1,4 @@
|
||||
<form class="form-horizontal" onsubmit="return false;">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-apiEnabled" data-bind="checked: api_enabled"> {{ _('Enable') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-apiEnforcedKey" data-bind="checked: api_keyEnforced"> {{ _('Enforce key') }}
|
||||
</label>
|
||||
<span class="help-block">{{ _('If you check this, requests to any of OctoPrint\'s APIs without an API key will be denied instead of handled like an anonymous/not logged in user. This is OctoPrint\'s old default behaviour.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
<div class="tab-content">
|
||||
<div id="settings_serial_general" class="tab-pane active">
|
||||
<fieldset>
|
||||
<fieldset id="settings_serial_general_connection">
|
||||
<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>
|
||||
@@ -43,8 +43,16 @@
|
||||
<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.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: serial_exclusive" id="settings-serialExclusive"> {{ _('Request exclusive access to the serial port') }}
|
||||
<span class="help-block">{{ _('Uncheck this if you are having problems connecting to your printer.') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<fieldset id="settings_serial_general_logging">
|
||||
<legend>{{ _('Serial logging') }}</legend>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
@@ -329,13 +337,27 @@
|
||||
<span class="help-block">{{ _('Try checking this if you run into connection timeouts due to your printer taking too long to respond to OctoPrint\'s handshake attempts on connect.') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-serialBlockedCommands">{{ _('Blocked commands') }}</label>
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: serial_blockM0M1" id="settings-serialBlockM0M1"> {{ _('Do not send <code>M0</code>/<code>M1</code> commands to the firmware, only pause') }}
|
||||
<span class="help-block">{{ _('Most firmware will block and wait for the user to press the button on the controller when an <code>M0</code> or <code>M1</code> is received. Due to that OctoPrint will normally not send those commands to the printer and only pause any ongoing prints. If you want OctoPrint to send those commands to your printer, uncheck this option.') }}</span>
|
||||
</label>
|
||||
<input type="text" class="input-block-level" id="settings-serialBlockedCommands" data-bind="value: serial_blockedCommands">
|
||||
<span class="help-inline">{{ _('Use this to specify commands that should never be sent to the printer. Just the G or M code, comma separated. Defaults to <code>M0</code> and <code>M1</code> since most firmware will block until a button on the controller has been pressed if it receives either of those two commands.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-serialPausingCommands">{{ _('Pausing commands') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialPausingCommands" data-bind="value: serial_pausingCommands">
|
||||
<span class="help-inline">{{ _('Use this to specify commands on which OctoPrint should pause the print job. Just the G or M code, comma separated. Defaults to <code>M0</code>, <code>M1</code> and <code>M25</code>.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-serialEmergencyCommands">{{ _('Emergency commands') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialEmergencyCommands" data-bind="value: serial_emergencyCommands">
|
||||
<span class="help-inline">{{ _('Use this to specify emergency commands which should jump any queues and - if supported by the firmware - be force sent. Just the G or M code, comma separated. Defaults to <code>M112</code>, <code>M118</code> and <code>M410</code>.') }}</span> </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">
|
||||
|
||||
@@ -118,7 +118,7 @@
|
||||
</ul>
|
||||
<ul id="footer_links" class="pull-right">
|
||||
<li><a href="https://octoprint.org" target="_blank" rel="noreferrer noopener"><i class="fa fa-home"></i> {{ _('Homepage') }}</a></li>
|
||||
<li><a href="https://discourse.octoprint.org" target="_blank" rel="noreferrer noopener"><i class="fa fa-users"></i> {{ _('Forum') }}</a></li>
|
||||
<li><a href="https://community.octoprint.org" target="_blank" rel="noreferrer noopener"><i class="fa fa-users"></i> {{ _('Forum') }}</a></li>
|
||||
<li><a href="https://faq.octoprint.org" target="_blank" rel="noreferrer noopener"><i class="fa fa-question-circle"></i> {{ _('FAQ') }}</a></li>
|
||||
<li><a href="http://docs.octoprint.org" target="_blank" rel="noreferrer noopener"><i class="fa fa-book"></i> {{ _('Docs') }}</a></li>
|
||||
<li id="footer_about"><a href="javascript:void(0)" data-bind="click: show"><i class="fa fa-info-circle"></i> {{ _('About') }}</a></li>
|
||||
|
||||
@@ -26,9 +26,7 @@
|
||||
// sockjs should define CLOSE_NORMAL for us, but they don't (from ws spec)
|
||||
var SOCKJS_CLOSE_NORMAL = 1000;
|
||||
|
||||
// only needed if API keys are enforced, only provides anonymous access on its own
|
||||
var UI_API_KEY = "{{ uiApiKey|e }}";
|
||||
|
||||
var UI_API_KEY = ""; // deprecated, only left for compatibility reasons
|
||||
var VERSION = "{{ version.number|e }}";
|
||||
var DISPLAY_VERSION = "{{ version.display|e }}";
|
||||
var BRANCH = "{{ version.branch|e }}";
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
<span class="fa fa-wrench"></span>
|
||||
</a>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilterSearch(); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.filterSearch() ? 'visible' : 'hidden'}"></i> {{ _('Apply filters to search results') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('name'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'name' ? 'visible' : 'hidden'}"></i> {{ _('Sort by name') }} ({{ _('ascending') }})</a></li>
|
||||
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('upload'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'upload' ? 'visible' : 'hidden'}"></i> {{ _('Sort by upload date') }} ({{ _('descending') }})</a></li>
|
||||
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('size'); }"><i class="fa fa-check" data-bind="style: {visibility: listHelper.currentSorting() == 'size' ? 'visible' : 'hidden'}"></i> {{ _('Sort by file size') }} ({{ _('descending') }})</a></li>
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
<th class="settings_users_details_key">{{ _('Permissions') }}</th>
|
||||
<td class="settings_users_details_value" data-bind="text: $root.access.permissionList($data)"></td>
|
||||
</tr>
|
||||
<tr data-bind="visible: $root.api_enabled() && apikey">
|
||||
<tr data-bind="visible: apikey">
|
||||
<th class="settings_users_details_key">{{ _('API Key') }}</th>
|
||||
<td class="settings_users_details_value"><span data-bind="text: apikey"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(apikey) }"><i class="fa fa-copy"></i></a></td>
|
||||
</tr>
|
||||
@@ -150,7 +150,7 @@
|
||||
<span class="help-inline" data-bind="visible: $root.access.users.editor.passwordMismatch()">{{ _('Passwords do not match') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<fieldset data-bind="visible: api_enabled">
|
||||
<fieldset>
|
||||
<legend>API Key</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Current API Key') }}</label>
|
||||
|
||||
+6
@@ -23,6 +23,12 @@
|
||||
<input type="checkbox" data-bind="checked: heatedBed">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Heated Chamber') }}</label>
|
||||
<div class="controls">
|
||||
<input type="checkbox" data-bind="checked: heatedChamber">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
|
||||
@@ -85,7 +85,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<!-- Extrusion control panel -->
|
||||
<div id="control-jog-extrusion" class="jog-panel" style="display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.CONTROL)">
|
||||
<div id="control-jog-extrusion" class="jog-panel" style="display: none;" data-bind="visible: loginState.hasPermissionKo(access.permissions.CONTROL) && tools().length > 0">
|
||||
<h1>Tool (E)</h1>
|
||||
<div>
|
||||
<div class="btn-group control-box">
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
<tr data-bind="template: { name: 'temprow-template' }"></tr>
|
||||
<!-- /ko -->
|
||||
<tr data-bind="template: { name: 'temprow-template', data: bedTemp }, visible: hasBed"></tr>
|
||||
<tr data-bind="template: { name: 'temprow-template', data: chamberTemp }, visible: hasChamber"></tr>
|
||||
</table>
|
||||
|
||||
<script type="text/html" id="temprow-template">
|
||||
@@ -41,7 +42,7 @@
|
||||
<li class="divider"></li>
|
||||
<!-- ko foreach: $root.temperature_profiles -->
|
||||
<li>
|
||||
<a href="javascript:void(0)" data-bind="click: function() {$root.setTargetFromProfile($parent, $data);}, text: 'Set ' + name + ' (' + ($parent.key() == 'bed' ? bed : extruder) + '°C)'"></a>
|
||||
<a href="javascript:void(0)" data-bind="click: function() { $root.setTargetFromProfile($parent, $data);}, text: $root.profileText($parent, $data)"></a>
|
||||
</li>
|
||||
<!-- /ko -->
|
||||
</ul>
|
||||
|
||||
@@ -88,7 +88,9 @@ def valid_timelapse(path):
|
||||
continue
|
||||
extensions += result
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional timelapse extensions from hook {name}".format(name=name))
|
||||
logging.getLogger(__name__).exception("Exception while retrieving additional timelapse "
|
||||
"extensions from hook {name}".format(name=name),
|
||||
extra=dict(plugin=name))
|
||||
|
||||
_extensions = list(set(extensions))
|
||||
|
||||
@@ -399,7 +401,6 @@ class Timelapse(object):
|
||||
self._capture_success = 0
|
||||
|
||||
self._post_roll = post_roll
|
||||
self._post_roll_start = None
|
||||
self._on_post_roll_done = None
|
||||
|
||||
self._capture_dir = settings().getBaseFolder("timelapse_tmp")
|
||||
@@ -555,7 +556,6 @@ class Timelapse(object):
|
||||
dict(postroll_duration=self.calculate_post_roll(),
|
||||
postroll_length=self.post_roll,
|
||||
postroll_fps=self.fps))
|
||||
self._post_roll_start = time.time()
|
||||
if do_create_movie:
|
||||
self._on_post_roll_done = create_wait_for_captures(reset_and_create)
|
||||
else:
|
||||
@@ -563,7 +563,6 @@ class Timelapse(object):
|
||||
self.process_post_roll()
|
||||
else:
|
||||
# no post roll? perfect, render
|
||||
self._post_roll_start = None
|
||||
if do_create_movie:
|
||||
wait_for_captures(reset_and_create)
|
||||
else:
|
||||
|
||||
Binary file not shown.
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user