diff --git a/.versioneer-lookup b/.versioneer-lookup index 1f56523dd..b2236eb28 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -18,16 +18,16 @@ prerelease HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.3.9 +# maintenance is currently the branch for preparation of maintenance release 1.3.11 # so are any fix/... and improve/... branches -maintenance 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev -fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev -improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev +maintenance 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev +fix/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 pep440-dev +improve/.* 1.3.11 e14c00f135bf2a955e54ac3f0a2928d8440055d2 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.11rc3 # so is regressionfix/... -staging/maintenance 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b pep440-dev -regressionfix/.* 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b pep440-dev +staging/maintenance 1.3.11rc3 18e7d2b72ad73c5d8e522cebbc001d0e8a3dff14 pep440-dev +regressionfix/.* 1.3.11rc3 18e7d2b72ad73c5d8e522cebbc001d0e8a3dff14 pep440-dev # every other branch is a development branch and thus gets resolved to 1.4.0-dev for now .* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev diff --git a/AUTHORS.md b/AUTHORS.md index d7cf88fea..ae9b33cf7 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -94,6 +94,11 @@ date of first contribution): * [Gaston Dombiak](https://github.com/gdombiak) * [Brad Fisher](https://github.com/bradcfisher) * [Aldo Hoeben](https://github.com/fieldofview) + * [Henning Groß](https://github.com/hgross) + * [Jubaleth](https://github.com/jubaleth) + * [Daniel Joyce](https://github.com/DanielJoyce) + * [Andy Qua](https://github.com/AndyQ) + * [Fabio Santos](https://github.com/Fabi0San) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/CHANGELOG.md b/CHANGELOG.md index 27f4b8065..d364c1ab8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 ` 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 diff --git a/README.md b/README.md index c3144cd5b..9f150d366 100644 --- a/README.md +++ b/README.md @@ -143,5 +143,8 @@ be edited from OctoPrint's settings dialog. ## Special Thanks -Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/). -Profiling is done with the help of [PyVmMonitor](http://www.pyvmmonitor.com). +Cross-browser testing services are kindly provided by [BrowserStack](https://www.browserstack.com/). + +Profiling is done with the help of [PyVmMonitor](https://www.pyvmmonitor.com). + +Error tracking is powered and sponsored by [Sentry](https://sentry.io). diff --git a/SUPPORTERS.md b/SUPPORTERS.md index aae0022bb..8ca7d23b7 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -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)! \ No newline at end of file +and 1544 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! diff --git a/THIRDPARTYLICENSES.md b/THIRDPARTYLICENSES.md index 6cc67867c..14423b11d 100644 --- a/THIRDPARTYLICENSES.md +++ b/THIRDPARTYLICENSES.md @@ -36,7 +36,6 @@ * [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3 * [chainmap](https://bitbucket.org/jeunice/chainmap): Python * [Click](http://click.pocoo.org/): BSD - * [dateutil](https://dateutil.readthedocs.io/): BSD * [emoji](https://github.com/carpedm20/emoji/): BSD * [feedparser](https://github.com/kurtmckee/feedparser): BSD * [Flask](http://flask.pocoo.org/): BSD diff --git a/docs/api/apps.rst b/docs/api/apps.rst index 46ee73c8c..6015d3359 100644 --- a/docs/api/apps.rst +++ b/docs/api/apps.rst @@ -11,6 +11,10 @@ Apps Session Keys ============ +.. deprecated:: 1.3.11 + + This functionality will be removed in 1.4.0. Use the :ref:`Application Keys Plugin workflow ` instead. + OctoPrint offers a special API key type for apps to use, the so called App Session Key. These keys have a time based validity and are generated by OctoPrint for requesting apps. diff --git a/docs/api/general.rst b/docs/api/general.rst index edc54ed78..3c404724c 100644 --- a/docs/api/general.rst +++ b/docs/api/general.rst @@ -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 ` (since 1.3.10). +If :ref:`Access Control ` is enabled OctoPrint's API expects an API key to be supplied with each request. This API +key can be either the globally configured one, a user specific one or an app and user specific one as generated by the +authorization workflow implemented by the bundled :ref:`Application Keys Plugin ` (since 1.3.10). Clients are advised to implement the :ref:`Application Keys Plugin workflow ` first and fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used. @@ -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 ` is active (which is the default), that means +that any requests without or with an invalid API key targeting other API endpoints than :ref:`Login ` +will be denied with a :http:statuscode:`403`. + +.. warning:: + + If :ref:`Access Control ` is disabled, OctoPrint will treat any unauthenticated anonymous requests and thus also requests + with an invalid or outright missing API key as requests with full admin rights! + +.. note:: + + The API key requirements changed in 1.3.11. Up to that version, even if Access Control was disabled, all requests needed to + be supplied with an API Key. To make the webinterface work under these circumstances, an unauthenticated anonymous API key was injected into the + HTML page and also available on the :ref:`Push API `. The presence and ready availability of this unauthenticated + anonymous "UI API key" caused confusion and false alarm among users and didn't contribute to the security of the platform in a + meaningful way, so it was finally abandoned in 1.3.11. + .. _fig-api-general-globalapikey: .. figure:: ../images/settings-global-api-key.png :align: center @@ -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 diff --git a/docs/api/job.rst b/docs/api/job.rst index 338a10ea7..0c43e2b3b 100644 --- a/docs/api/job.rst +++ b/docs/api/job.rst @@ -212,7 +212,8 @@ Retrieve information about the current job "filepos": 337942, "printTime": 276, "printTimeLeft": 912 - } + }, + "state": "Printing" } :statuscode 200: No error @@ -243,4 +244,8 @@ Job information response - 1 - :ref:`sec-api-datamodel-jobs-progress` - Information regarding the progress of the current print job - + * - ``state`` + - 1 + - String + - A textual representation of the current state of the job, i.e. "Operational", "Printing", "Pausing", "Paused", + "Cancelling", "Error" or "Offline". diff --git a/docs/api/printer.rst b/docs/api/printer.rst index 1c8483a55..82f86cc91 100644 --- a/docs/api/printer.rst +++ b/docs/api/printer.rst @@ -22,6 +22,11 @@ Bed corresponding resource returns temperature information including an optional history. Note that Bed commands are only available if the currently selected printer profile has a heated bed. See :ref:`sec-api-printer-bedcommand`. +Chamber + Chamber commands allow setting the temperature and temperature offset for the printer's heated chamber. Querying + the corresponding resource returns temperature information including an option history. Note that Chamber commands + are only available if the currently selected printer profile has a heated chamber. + See :ref:`sec-api-printer-chambercommand`. SD card SD commands allow initialization, refresh and release of the printer's SD card (if available). Querying the corresponding resource returns the current SD card state. @@ -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 `. **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 `. + + **Example** + + Query the chamber temperature data and also include the temperature history but limit it to two entries. + + .. sourcecode:: http + + GET /api/printer/chamber?history=true&limit=2 HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "chamber": { + "actual": 50.221, + "target": 70.0, + "offset": 5 + }, + "history": [ + { + "time": 1395651928, + "chamber": { + "actual": 50.221, + "target": 70.0 + } + }, + { + "time": 1395651926, + "chamber": { + "actual": 49.1123, + "target": 70.0 + } + } + ] + } + + :query history: If set to ``true`` (or: ``yes``, ``y``, ``1``), history information will be included in the response + too. If no ``limit`` parameter is given, all available temperature history data will be returned. + :query limit: If set to an integer (``n``), only the last ``n`` data points from the printer's temperature history + will be returned. Will be ignored if ``history`` is not enabled. + :statuscode 200: No error + :statuscode 409: If the printer is not operational or the selected printer profile + does not have a heated chamber. + .. _sec-api-printer-sdcommand: Issue an SD command diff --git a/docs/api/printerprofiles.rst b/docs/api/printerprofiles.rst index 8db1b51ae..9f2f163e2 100644 --- a/docs/api/printerprofiles.rst +++ b/docs/api/printerprofiles.rst @@ -52,6 +52,7 @@ Retrieve all printer profiles "height": 200 }, "heatedBed": true, + "heatedChamber": false, "axes": { "x": { "speed": 6000, @@ -93,6 +94,7 @@ Retrieve all printer profiles "height": 200 }, "heatedBed": true, + "heatedChamber": true, "axes": { "x": { "speed": 6000, @@ -184,6 +186,7 @@ Add a new printer profile "height": 200 }, "heatedBed": true, + "heatedChamber": false, "axes": { "x": { "speed": 6000, @@ -267,6 +270,7 @@ Add a new printer profile "height": 300 }, "heatedBed": false, + "heatedChamber": false, "axes": { "x": { "speed": 6000, @@ -352,6 +356,7 @@ Update an existing printer profile "height": 200 }, "heatedBed": true, + "heatedChamber": false, "axes": { "x": { "speed": 6000, @@ -578,6 +583,10 @@ Profile - 0..1 - ``boolean`` - Whether the printer has a heated bed (``true``) or not (``false``) + * - ``heatedChamber`` + - 0..1 + - ``boolean`` + - Whether the printer has a heated chamber (``true``) or not (``false``) * - ``axes`` - 0..1 - Object diff --git a/docs/api/settings.rst b/docs/api/settings.rst index c485f0a95..be249e877 100644 --- a/docs/api/settings.rst +++ b/docs/api/settings.rst @@ -274,10 +274,10 @@ Fetch template data "plugin_name": "Action Command Prompt Support" }, { - "id": "plugin_cura", - "name": "CuraEngine (<= 15.04)", - "plugin_id": "cura", - "plugin_name": "CuraEngine (<= 15.04)" + "id": "plugin_curalegacy", + "name": "Cura Legacy", + "plugin_id": "curalegacy", + "plugin_name": "Cura Legacy" } ], "sidebar": [ diff --git a/docs/api/slicing.rst b/docs/api/slicing.rst index 129653171..c49cb4cd5 100644 --- a/docs/api/slicing.rst +++ b/docs/api/slicing.rst @@ -42,22 +42,22 @@ List All Slicers and Slicing Profiles Content-Type: application/json { - "cura": { - "key": "cura", - "displayName": "CuraEngine", + "curalegacy": { + "key": "curalegacy", + "displayName": "Cura Legacy", "default": true, "profiles": { "high_quality": { "key": "high_quality", "displayName": "High Quality", "default": false, - "resource": "http://example.com/api/slicing/cura/profiles/high_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality" }, "medium_quality": { "key": "medium_quality", "displayName": "Medium Quality", "default": true, - "resource": "http://example.com/api/slicing/cura/profiles/medium_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality" } } } @@ -81,7 +81,7 @@ List Slicing Profiles of a Specific Slicer .. sourcecode:: http - GET /api/slicing/cura/profiles HTTP/1.1 + GET /api/slicing/curalegacy/profiles HTTP/1.1 Host: example.com X-Api-Key: abcdef... @@ -95,13 +95,13 @@ List Slicing Profiles of a Specific Slicer "key": "high_quality", "displayName": "High Quality", "default": false, - "resource": "http://example.com/api/slicing/cura/profiles/high_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality" }, "medium_quality": { "key": "medium_quality", "displayName": "Medium Quality", "default": true, - "resource": "http://example.com/api/slicing/cura/profiles/medium_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality" } } @@ -125,7 +125,7 @@ Retrieve Specific Profile .. sourcecode:: http - GET /api/slicing/cura/profiles/quick_test HTTP/1.1 + GET /api/slicing/curalegacy/profiles/quick_test HTTP/1.1 Host: example.com X-Api-Key: abcdef... @@ -137,7 +137,7 @@ Retrieve Specific Profile { "displayName": "Just a test", "description": "This is just a test", - "resource": "http://example.com/api/slicing/cura/profiles/quick_test", + "resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test", "data": { "bottom_layer_speed": 20.0, "bottom_thickness": 0.3, @@ -174,14 +174,14 @@ Add Slicing Profile .. sourcecode:: http - PUT /api/slicing/cura/profiles/quick_test HTTP/1.1 + PUT /api/slicing/curalegacy/profiles/quick_test HTTP/1.1 Host: example.com X-Api-Key: abcdef... Content-Type: application/json { "displayName": "Just a test", - "description": "This is just a test to show how to create a cura profile with a different layer height and skirt count", + "description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count", "data": { "layer_height": 0.2, "skirt_line_count": 3 @@ -197,8 +197,8 @@ Add Slicing Profile { "displayName": "Just a test", - "description": "This is just a test to show how to create a cura profile with a different layer height and skirt count", - "resource": "http://example.com/api/slicing/cura/profiles/quick_test" + "description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count", + "resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test" } :param slicer: The identifying key of the slicer for which to add the profile diff --git a/docs/api/version.rst b/docs/api/version.rst index 47b0c56e0..9716139c4 100644 --- a/docs/api/version.rst +++ b/docs/api/version.rst @@ -7,7 +7,8 @@ Version information .. http:get:: /api/version Retrieve information regarding server and API version. Returns a JSON object with two keys, ``api`` containing - the API version, ``server`` containing the server version. + the API version, ``server`` containing the server version, ``text`` containing the server version including + the prefix ``OctoPrint `` (to determine that this is indeed a genuine OctoPrint instance). **Example Request** @@ -26,7 +27,8 @@ Version information { "api": "0.1", - "server": "1.1.0" + "server": "1.3.10", + "text": "OctoPrint 1.3.10" } :statuscode 200: No error diff --git a/docs/bundledplugins/cura.rst b/docs/bundledplugins/cura.rst deleted file mode 100644 index 7c47d620a..000000000 --- a/docs/bundledplugins/cura.rst +++ /dev/null @@ -1,130 +0,0 @@ -.. _sec-bundledplugins-cura: - -Cura -==== - -The Cura Plugin allows slicing of STL files uploaded to OctoPrint directly via -the `CuraEngine `_ **up to and -including version 15.04.x** and supersedes the slicing support integrated into -OctoPrint so far. It comes bundled with OctoPrint starting with version 1.2.0. - -.. note:: - - Versions of CuraEngine later than 15.04.x have changed their calling - parameters in such a way that the current implementation of OctoPrint's Cura plugin - is not compatible to it. For this reason, please use only CuraEngine versions up to - and including 15.04 for now, as available in the ``legacy`` branch of the CuraEngine - repository on Github. - -The plugin offers a settings module that allows configuring the path to the -CuraEngine executable to use, as well as importing and managing slicing -profiles to be used. Please note that the Cura Plugin will use the printer -parameters you configured within OctoPrint (meaning bed size and extruder -count and offsets) for slicing. - -.. _sec-bundledplugins-cura-firststeps: - -First Steps ------------ - -Before you can slice from within OctoPrint, you'll need to - - #. :ref:`Install CuraEngine ` - #. :ref:`Configure the path to CuraEngine within OctoPrint ` - #. :ref:`Export a slicing profile from Cura and import it within OctoPrint ` - -.. note:: - - OctoPi 0.12.0 and later ships with steps 1 and 2 already done, you only need to - supply one or more slicing profiles to get going :) - -.. _sec-bundledplugins-cura-installing: - -Installing CuraEngine ---------------------- - -You'll need a build of ``legacy`` branch of `CuraEngine `_ -in order to be able to use the Cura OctoPrint plugin. You can find the ``legacy`` branch -`here `__. - -If you previously used the `old variant of the Cura integration `_, -you probably still have a fully functional binary lying around in the -installation folder of the full install of Cura you used then -- just put the -path to that in the plugin settings. - -.. _sec-bundledplugins-cura-installing-raspbian: - -Compiling for Raspbian -++++++++++++++++++++++ - -Raspbian Jessie and later -~~~~~~~~~~~~~~~~~~~~~~~~~ - -Building on Raspbian Jessie and later is as easy as:: - - sudo apt-get -y install gcc-4.7 g++-4.7 - git clone -b legacy https://github.com/Ultimaker/CuraEngine.git - cd CuraEngine - make - -After this has completed, you'll find your shiny new build of CuraEngine in -the `build` folder (full path for above example: -``~/CuraEngine/build/CuraEngine``). - -Raspbian Wheezy -~~~~~~~~~~~~~~~ - -You'll need to install a new version of gcc and g++ and patch CuraEngine's -Makefile (see `this post `_) -in order for the compilation to work on current Raspbian builds (e.g. OctoPi):: - - sudo apt-get -y install gcc-4.7 g++-4.7 - git clone -b legacy https://github.com/Ultimaker/CuraEngine.git - cd CuraEngine - wget http://bit.ly/curaengine_makefile_patch -O CuraEngine.patch - patch < CuraEngine.patch - make CXX=g++-4.7 - -After this has completed, you'll find your shiny new build of CuraEngine in -the `build` folder (full path for above example: -``~/CuraEngine/build/CuraEngine``). - -.. _sec-bundledplugins-cura-configuring: - -Configuring the plugin ----------------------- - -The Cura plugin needs to be configured with the full path to your copy of the -CuraEngine executable that it's supposed to use. You can do this either via -the Cura plugin settings dialog or by manually configuring the path to the -executable via ``config.yaml``, example: - -.. code-block:: yaml - - plugins: - cura: - cura_engine: /path/to/CuraEngine - -.. _sec-bundledplugins-cura-profiles: - -Using Cura Profiles -------------------- - -The Cura Plugin supports importing your existing profiles for Cura **up to and -including Cura 15.04.x**. Newer Cura releases (e.g. 15.06 or 2.x) use a different -internal format that will *not* work with the current version of the Cura Plugin. - -You can find downloads of Cura 15.04.x for Windows, Mac and Linux `on Ultimaker's download page `_. - -In order to export a slicing profile from the Cura desktop UI, open it, -set up your profile, then click on "File" and there on "Save Profile". You can -import the .ini-file this creates via the "Import Profile" button in the -Cura Settings within OctoPrint. - -.. _sec-bundledplugins-cura-sourcecode: - -Source code ------------ - -The source of the Cura plugin is bundled with OctoPrint and can be found in -its source repository under ``src/octoprint/plugins/cura``. diff --git a/docs/bundledplugins/errortracking.rst b/docs/bundledplugins/errortracking.rst new file mode 100644 index 000000000..f87e7e8b2 --- /dev/null +++ b/docs/bundledplugins/errortracking.rst @@ -0,0 +1,40 @@ +.. _sec-bundledplugins-errortracking: + +Error Tracking Plugin +===================== + +The Error Tracking plugin will cause any logged exceptions in the server and the browser interface to be sent to +OctoPrint's `Sentry instance `_. + +By enabling it you help to gather detailed information on the cause of bugs or other issues. This is especially +valuable on release candidates, which is why this plugin will also prompt you to enable error tracking if it detects +that you are subscribed to an RC release channel. + +By default, even when enabled it will only be active if you are running a released OctoPrint version, so either a stable +release or a release candidate. + +The Error Tracking plugin is using a Sentry instance kindly provided by `sentry.io `_. For information on their service +please refer to their `Security & Compliance documentation `_ +and their `Privacy Policy `_. + +The Error Tracking plugin has been bundled with OctoPrint since version 1.3.11. + +.. _sec-bundledplugins-errortracking-configuration: + +Configuring the plugin +---------------------- + +The plugin supports the following configuration keys: + + * ``enabled``: Whether to enable error tracking. Defaults to ``false``. + * ``enabled_unreleased``: Whether to also enable tracking on unreleased OctoPrint versions (anything not stable releases + or release candidates). Defaults to ``false``. + * ``unique_id``: Unique instance identifier, auto generated on first activation + +.. _sec-bundledplugins-errortracking-sourcecode: + +Source Code +----------- + +The source of the Error Tracking plugin is bundled with OctoPrint and can be +found in its source repository under ``src/octoprint/plugins/errortracking``. diff --git a/docs/bundledplugins/index.rst b/docs/bundledplugins/index.rst index 8bf1d5d35..d82c3eb29 100644 --- a/docs/bundledplugins/index.rst +++ b/docs/bundledplugins/index.rst @@ -9,10 +9,11 @@ Bundled Plugins action_command_prompt.rst announcements.rst + tracking.rst appkeys.rst backup.rst - cura.rst discovery.rst + errortracking.rst forcelogin.rst logging.rst pluginmanager.rst diff --git a/docs/bundledplugins/pluginmanager.rst b/docs/bundledplugins/pluginmanager.rst index dacb3f8ca..2ec1babbb 100644 --- a/docs/bundledplugins/pluginmanager.rst +++ b/docs/bundledplugins/pluginmanager.rst @@ -82,6 +82,45 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``: - hidden - plugins +.. _sec-bundledplugins-pluginmanager-events: + +Events +------ + +plugin_pluginmanager_install_plugin + A plugin was installed. + + Payload: + + * ``id``: the identifier of the installed plugin + * ``version``: the version of the installed plugin + * ``source``: source from which the plugin was installed, can be an URL or a path in the local file system + * ``source_type``: type of source from which the plugin was installed, can be ``url`` or ``path`` + +plugin_pluginmanager_uninstall_plugin + A plugin was uninstalled. + + Payload: + + * ``id``: the identifier of the uninstalled plugin + * ``version``: the version of the uninstalled plugin + +plugin_pluginmanager_enable_plugin + A plugin was enabled. + + Payload: + + * ``id``: the identifier of the enabled plugin + * ``version``: the version of the enabled plugin + +plugin_pluginmanager_disabled_plugin + A plugin was disabled. + + Payload: + + * ``id``: the identifier of the disabled plugin + * ``version``: the version of the disabled plugin + .. _sec-bundledplugins-pluginmanager-hooks: Hooks diff --git a/docs/bundledplugins/printer_safety_check.rst b/docs/bundledplugins/printer_safety_check.rst index 6770056cb..320de9053 100644 --- a/docs/bundledplugins/printer_safety_check.rst +++ b/docs/bundledplugins/printer_safety_check.rst @@ -29,6 +29,20 @@ If you know of further printers/printer firmwares that need to be added here, pl unexpectedly and with `catastrophic `_ `results `_. +.. _sec-bundledplugins-printer_safety_check-events: + +Events +------ + +warning + A printer safety warning was triggered. + + Payload: + + * ``check_type``: type of check that was triggered (e.g. ``m115``, ``received`` or ``cap``) + * ``check_name``: name of check that was triggered (e.g. ``aneta8``) + * ``warning_type``: type of warning that was triggered (e.g. ``firmware-unsafe``) + .. _sec-bundledplugins-printer_safety_check-source: Source Code diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index de4896b6d..1fd5d3a80 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -325,6 +325,29 @@ The same, but tracking all commits pushed to branch ``devel`` (thus allowing branch: devel pip: 'https://github.com/someUser/OctoPrint-SomePlugin/archive/{target}.zip' +.. _sec-bundledplugins-softwareupdate-events: + +Events +------ + +plugin_softwareupdate_update_succeeded + An update succeeded. + + Payload: + + * ``target``: update target + * ``from_version``: version from which was updated + * ``to_version``: version to which was updated + +plugin_softwareupdate_update_failed + An update failed. + + Payload: + + * ``target``: update target + * ``from_version``: version from which was updated + * ``to_version``: version to which was updated + .. _sec-bundledplugins-softwareupdate-hooks: Hooks diff --git a/docs/bundledplugins/tracking.rst b/docs/bundledplugins/tracking.rst new file mode 100644 index 000000000..4864deb6f --- /dev/null +++ b/docs/bundledplugins/tracking.rst @@ -0,0 +1,45 @@ +.. _sec-bundledplugins-tracking: + +Anonymous Usage Tracking Plugin +=============================== + +The Anonymous Usage Tracking plugin provides valuable insights into how many instances running what versions of +OctoPrint are out there, whether they are successfully completing print jobs and various other metrics. + +By enabling it you help to identify problems with new releases and release candidates early on, and to better tailor +OctoPrint's future development to actual use. + +For details on what gets tracked, please refer to `tracking.octoprint.org `_ +and also the `Privacy Policy at tracking.octoprint.org `_. + +The Anonymous Usage Tracking plugin has been bundled with OctoPrint since version 1.3.10. + +.. _sec-bundledplugins-tracking-configuration: + +Configuring the plugin +---------------------- + +The plugin supports the following configuration keys: + + * ``enabled``: Whether to enable usage tracking. Defaults to ``false``. + * ``unique_id``: Unique instance identifier, auto generated on first activation + * ``server``: The tracking server to track against. Defaults to a tracking endpoint on ``https://tracking.octoprint.org``. + * ``ping``: How often to send a ``ping`` tracking event, in seconds. Defaults to a 15min interval. + * ``events``: Granular configuration of enabled tracking events. All default to ``true``. + + * ``startup``: Whether to track startup/shutdown events + * ``printjob``: Whether to track print job related events (start, completion, cancel, ...) + * ``commerror``: Whether to track communication errors with the printer + * ``plugin``: Whether to track plugin related events (install, uninstall, ...) + * ``update``: Whether to track update related events (update successful or not, ...) + * ``printer``: Whether to track printer related events (connected, firmware, ...) + * ``printer_safety_check``: Whether to track warnings of the :ref:`Printer Safety Check ` + * ``throttled``: Whether to track throttle events detected on the underlying system + +.. _sec-bundledplugins-tracking-sourcecode: + +Source Code +----------- + +The source of the Anonymous Usage Tracking plugin is bundled with OctoPrint and can be +found in its source repository under ``src/octoprint/plugins/tracking``. diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 88fa4545e..d6f049077 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -81,7 +81,8 @@ Settings for the REST API: # Whether to allow cross origin access to the API or not allowCrossOrigin: false - # Additional app api keys, see REST API > Apps in the docs + # Additional app api keys, see REST API > Apps in the docs. + # Deprecated since 1.3.11, to be removed in 1.4.0! apps: "some.app.identifier:some_version": pubkey: @@ -322,6 +323,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 @@ -808,6 +812,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: @@ -934,6 +951,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 @@ -1098,14 +1122,14 @@ Settings for the built-in slicing support: slicing: # Whether to enable slicing support or not - enabled: + enabled: true # Default slicer to use - defaultSlicer: cura + defaultSlicer: null # Default slicing profiles per slicer defaultProfiles: - cura: ... + curalegacy: ... .. _sec-configuration-config_yaml-system: diff --git a/docs/configuration/logging_yaml.rst b/docs/configuration/logging_yaml.rst index 549611884..483e79550 100644 --- a/docs/configuration/logging_yaml.rst +++ b/docs/configuration/logging_yaml.rst @@ -39,8 +39,8 @@ A list of important components for which an increase in logging might be interes * ``octoprint.filemanager``: the file management layer * ``octoprint.plugin``: the plugin sub system * ``octoprint.plugins.``: the plugin ````, e.g. ``octoprint.plugins.discovery`` to change the log level of - the `Discovery plugin `_ or ``octoprint.plugins.cura`` - to change the log level of the `Cura plugin `_. + the :ref:`Discovery plugin ` or ``octoprint.plugins.backup`` + to change the log level of the :ref:`Backup plugin `. * ``octoprint.slicing``: the slicing sub system This list will be expanded when deemed necessary. diff --git a/docs/events/index.rst b/docs/events/index.rst index b1ba10ab6..108cfc20b 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -6,15 +6,6 @@ Events .. contents:: - -.. note:: - - With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events. - Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to - accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer - separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed - to indicate what to do with the command contained. - .. _sec-events-configuration: Configuration @@ -85,6 +76,12 @@ and its origin via the placeholder ``{origin}``. Available Events ================ +.. note:: + + Plugins may add additional events via the :ref:`octoprint.events.register_custom_events hook `. + +.. _sec-events-available_events-server: + Server ------ @@ -118,6 +115,8 @@ ConnectivityChanged * ``old``: Old connectivity value (true for online, false for offline) * ``new``: New connectivity value (true for online, false for offline) +.. _sec-events-available_events-printer_commmunication: + Printer communication --------------------- @@ -141,7 +140,8 @@ Disconnected The server has disconnected from the printer Error - An error has occurred in the printer communication. + An unrecoverable error has been encountered, either as reported by the firmware (e.g. a thermal runaway) or + on the connection. Payload: @@ -156,6 +156,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 ------------- @@ -303,6 +305,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 -------- @@ -314,6 +318,9 @@ PrintStarted * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``user``: the user who started the print job (if available) .. deprecated:: 1.3.0 @@ -328,6 +335,8 @@ PrintFailed * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) * ``time``: the elapsed time of the print when it failed, in seconds (float) * ``reason``: the reason the print failed, either ``cancelled`` or ``error`` @@ -344,6 +353,8 @@ PrintDone * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) * ``time``: the time needed for the print, in seconds (float) .. deprecated:: 1.3.0 @@ -359,6 +370,9 @@ PrintCancelling * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``user``: the user who cancelled the print job (if available) * ``firmwareError``: the firmware error that caused cancelling the print job, if any PrintCancelled @@ -369,7 +383,12 @@ PrintCancelled * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` - * ``position``: the print head position at the time of cancelling, if available + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``time``: the elapsed time of the print when it was cancelled, in seconds (float) + * ``user``: the user who cancelled the print job (if available) + * ``position``: the print head position at the time of cancelling (if available, not available if recording of the + position on cancel is disabled) * ``position.x``: x coordinate, as reported back from the firmware through `M114` * ``position.y``: y coordinate, as reported back from the firmware through `M114` * ``position.z``: z coordinate, as reported back from the firmware through `M114` @@ -394,7 +413,11 @@ PrintPaused * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` - * ``position``: the print head position at the time of pausing, if available + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``user``: the user who paused the print job (if available) + * ``position``: the print head position at the time of pausing (if available, not available if the recording of + the position on pause is disabled or the pause is completely handled by the printer's firmware) * ``position.x``: x coordinate, as reported back from the firmware through `M114` * ``position.y``: y coordinate, as reported back from the firmware through `M114` * ``position.z``: z coordinate, as reported back from the firmware through `M114` @@ -419,12 +442,17 @@ PrintResumed * ``name``: the file's name * ``path``: the file's path within its storage location * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``user``: the user who resumed the print job (if available) .. deprecated:: 1.3.0 * ``file``: the file's full path on disk (``local``) or within its storage (``sdcard``). 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 ---------------- @@ -486,6 +514,8 @@ ToolChange * ``old``: old tool index * ``new``: new tool index +.. _sec-events-available_events-timelapses: + Timelapses ---------- @@ -540,6 +570,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 ------- @@ -611,8 +643,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``. diff --git a/docs/features/accesscontrol.rst b/docs/features/accesscontrol.rst index cb6a1e248..06bcc253e 100644 --- a/docs/features/accesscontrol.rst +++ b/docs/features/accesscontrol.rst @@ -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 `! 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:: diff --git a/docs/index.rst b/docs/index.rst index ac0ed3ec5..cdfa4b217 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -11,7 +11,7 @@ and released under the `GNU Affero General Public License V3 `_. -The community forum is available at `discourse.octoprint.org `_. +The community forum is available at `community.octoprint.org `_. The FAQ can be accessed by following `faq.octoprint.org `_. @@ -23,7 +23,7 @@ If you enjoy OctoPrint, please consider becoming a regular supporter! .. note:: This documentation currently focuses primarily on developers and less on end users. If you are interested in - helping to change this, please get in touch `on the forum `_! + helping to change this, please get in touch `on the forum `_! Contents ======== diff --git a/docs/jsclientlib/printer.rst b/docs/jsclientlib/printer.rst index 14df29834..d79d3d6de 100644 --- a/docs/jsclientlib/printer.rst +++ b/docs/jsclientlib/printer.rst @@ -210,6 +210,64 @@ :param object opts: Additional options for the request :returns Promise: A `jQuery Promise `_ for the request's response +.. js:function:: OctoPrintClient.printer.getChamberState(data, opts) + + Retrieves the current printer chamber state/temperature information, and optionally also the temperature + history. + + The ``flags`` object can be used to specify the data to retrieve further via the following + properties: + + * ``history``: a boolean value to specify whether the temperature history should be included (``true``) + or not (``false``), defaults to it not being included + * ``limit``: an integer value to specify how many history entries to include + + See :ref:`Retrieve the current bed state ` for more details. + + :param object flags: Flags that further specify which data to retrieve, see above for details + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.printer.setChamberTargetTemperature(target, opts) + + Sets the given temperature on the printer's heated chamber (if available). + + ``target`` is expected to be the target temperature as a float value. + + **Example:** + + Set the chamber to 50°C. + + .. code-block:: javascript + + OctoPrint.printer.setChamberTargetTemperature(50.0); + + See the ``target`` command in :ref:`Issue a chamber command ` for more details. + + :param float target: The target to set + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + +.. js:function:: OctoPrintClient.printer.setChamberTemperatureOffset(offset, opts) + + Sets the given temperature offset for the printer's heated chamber (if available). + + ``offset`` is expected to be the temperature offset to set. + + **Example:** + + Set the offset for the chamber to -5°C. + + .. code-block:: javascript + + OctoPrint.printer.setChamberTemperatureOffset(-5); + + See the ``offset`` command in :ref:`Issue a chamber command ` for more details. + + :param object offsets: The offsets to set + :param object opts: Additional options for the request + :returns Promise: A `jQuery Promise `_ for the request's response + .. js:function:: OctoPrintClient.printer.jog(amounts, opts) Jogs the specified axes by the specified ``amounts``. diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 65533a7a4..c5bb1db3a 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -208,6 +208,10 @@ octoprint.accesscontrol.appkey .. py:function:: acl_appkey_hook(*args, **kwargs) + .. deprecated:: 1.3.11 + + This functionality will be removed in 1.4.0. Use the :ref:`Application Keys Plugin workflow ` instead. + By handling this hook plugins may register additional :ref:`App session key providers ` within the system. @@ -903,6 +907,34 @@ octoprint.comm.transport.serial.factory :rtype: A serial instance implementing implementing the methods ``readline(...)``, ``write(...)``, ``close()`` and optionally ``baudrate`` and ``timeout`` attributes as described above. +.. _sec-plugins-hook-events-register_custom_events: + +octoprint.events.register_custom_events +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: register_custom_events_hook(*args, **kwargs) + + Return a list of custom :ref:`events ` to register in the system for your plugin. + + Should return a list of strings which represent the custom events. Their name on the `octoprint.events.Events` object + will be the returned value transformed into upper case ``CAMEL_CASE`` and prefixed with ``PLUGIN_``. Their + value will be prefixed with ``plugin__``. + + Example: + + Consider the following hook part of a plugin with the identifier ``myplugin``. It will register two custom events + in the system, ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_CUSTOM_EVENT`` with value ``plugin_myplugin_my_custom_event`` + and ``octoprint.events.Events.PLUGIN_MYPLUGIN_MY_OTHER_CUSTOM_EVENT`` with value ``plugin_myplugin_my_other_custom_event``. + + .. code-block:: python + :linenos: + + def register_custom_events(*args, **kwargs): + return ["my_custom_event", "my_other_custom_event"] + + :return: A list of custom events to register + :rtype: list + .. _sec-plugins-hook-filemanager-analysis-factory: octoprint.filemanager.analysis.factory @@ -1089,6 +1121,91 @@ octoprint.printer.estimation.factory :return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method :rtype: class or function +.. _sec-plugins-hook-octoprint-printer-sdcardupload: + +octoprint.printer.sdcardupload +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: sd_card_upload_hook(printer, filename, path, start_callback, success_callback, failure_callback, *args, **kwargs) + + Via this hook plugins can change the way files are being uploaded to the sd card of the printer. + + Implementations **must** call the provided ``start_callback`` on start of the file transfer and either the ``success_callback`` + or ``failure_callback`` on the end of the file transfer, depending on whether it was successful or not. + + The ``start_callback`` has the following signature: + + .. code-block:: python + + def start_callback(local_filename, remote_filename): + # ... + + ``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file + to be created on the ``sdcard`` storage. + + ``success_callback`` and ``failure_callback`` both have the following signature: + + .. code-block:: python + + def success_or_failure_callback(local_filename, remote_filename, elapsed): + # ... + + ``local_filename`` must be the name of the file on the ``local`` storage, ``remote_filename`` the name of the file + to be created on the ``sdcard`` storage. ``elapsed`` is the elapsed time in seconds. + + If the hook is going to handle the upload, it must return the (future) remote filename of the file on the ``sdcard`` + storage. If it returns ``None`` (or an otherwise falsy value), OctoPrint will interpret this as the hook not going to + handle the file upload, in which case the next hook or - if no other hook is registered - the default implementation + will be called. + + **Example** + + The following example creates a dummy SD card uploader that does nothing but sleep for ten seconds when a file + is supposed to be uploaded. Note that the long running process of sleeping for ten seconds is extracted into its + own thread, which is important in order to not block the main application! + + .. code-block:: python + + import threading + import logging + import time + + def nop_upload_to_sd(printer, filename, path, sd_upload_started, sd_upload_succeeded, sd_upload_failed, *args, **kwargs): + logger = logging.getLogger(__name__) + + remote_name = printer._get_free_remote_name(filename) + logger.info("Starting dummy SDCard upload from {} to {}".format(filename, remote_name)) + + sd_upload_started(filename, remote_name) + + def process(): + logger.info("Sleeping 10s...") + time.sleep(10) + logger.info("And done!") + sd_upload_succeeded(filename, remote_name, 10) + + thread = threading.Thread(target=process) + thread.daemon = True + thread.start() + + return remote_name + + __plugin_name__ = "No-op SDCard Upload Test" + __plugin_hooks__ = { + "octoprint.printer.sdcardupload": nop_upload_to_sd + } + + .. versionadded:: 1.3.11 + + :param object printer: the :py:class:`~octoprint.printer.PrinterInterface` instance the hook was called from + :param str filename: filename on the ``local`` storage + :param str path: path of the file in the local file system + :param function sd_upload_started: callback for when the upload started + :param function sd_upload_success: callback for successful finish of upload + :param function sd_upload_failure: callback for failure of upload + :return: the name of the file on the ``sdcard`` storage or ``None`` + :rtype: string or ``None`` + .. _sec-plugins-hook-server-http-after_request: octoprint.server.api.after_request @@ -1211,6 +1328,14 @@ octoprint.server.http.routes view of the blueprint will thus not be reachable since processing of the request will directly be handed over to your defined handler class. + .. important:: + + If you want your route to support CORS if it's enabled in OctoPrint, your `RequestHandler `_ + needs to implement the :class:`~octoprint.server.util.tornado.CorsSupportMixin` for this to work. Note that all of + :class:`~octoprint.server.util.tornado.LargeResponseHandler`, :class:`~octoprint.server.util.tornado.UrlProxyHandler`, + :class:`~octoprint.server.util.tornado.StaticDataHandler` and :class:`~octoprint.server.util.tornado.DeprecatedEndpointHandler` + already implement this mixin. + .. important:: Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully. diff --git a/docs/plugins/mixins.rst b/docs/plugins/mixins.rst index fa73c1757..386ff3d26 100644 --- a/docs/plugins/mixins.rst +++ b/docs/plugins/mixins.rst @@ -68,11 +68,14 @@ calls are done is as follows: * Plugins with a return value that is not ``None`` for :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key` for the provided sorting context will be ordered among each other first. If the returned order number is equal for - two or more implementations, the plugin's identifier will be the next sorting criteria. - * After that follow plugins which returned ``None`` (the default). They are sorted by their identifier. + two or more implementations, they will be sorted first by whether they come bundled with OctoPrint or not, then by + their identifier. + * After that follow plugins which returned ``None`` (the default). They are first sorted by whether they come bundled + with OctoPrint or not, then by their identifier. -Example: Consider three plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called -``plugin_a``, ``plugin_b`` and ``plugin_c``. ``plugin_a`` doesn't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`. +Example: Consider four plugin implementations implementing the :class:`~octoprint.plugin.StartupPlugin` mixin, called +``plugin_a``, ``plugin_b``, ``plugin_c`` and ``plugin_d``, the latter coming bundled with OctoPrint. ``plugin_a`` +and ``plugin_d`` don't override :meth:`~octoprint.plugin.core.SortablePlugin.get_sorting_key`. ``plugin_b`` and ``plugin_c`` both return ``1`` for the sorting context ``StartupPlugin.on_startup``, ``None`` otherwise: .. code-block:: python @@ -99,7 +102,7 @@ Example: Consider three plugin implementations implementing the :class:`~octopri class PluginB(octoprint.plugin.StartupPlugin): - def get_sorting_key(context): + def get_sorting_key(self, context): if context == "StartupPlugin.on_startup": return 1 return None @@ -120,7 +123,7 @@ Example: Consider three plugin implementations implementing the :class:`~octopri class PluginC(octoprint.plugin.StartupPlugin): - def get_sorting_key(context): + def get_sorting_key(self, context): if context == "StartupPlugin.on_startup": return 1 return None @@ -134,13 +137,45 @@ Example: Consider three plugin implementations implementing the :class:`~octopri __plugin_implementation__ = PluginC() +.. code-block:: python + :linenos: + :caption: plugin_d.py + + # in this example this is bundled with OctoPrint + import octoprint.plugin + + class PluginD(octoprint.plugin.StartupPlugin): + + def on_startup(self, *args, **kwargs): + self._logger.info("PluginD starting up") + + def on_after_startup(self, *args, **kwargs): + self._logger.info("PluginD started up") + + __plugin_implementation__ = PluginD() + OctoPrint will detect that ``plugin_b`` and ``plugin_c`` define a order number, and since it's identical for both (``1``) -will order both plugins based on their plugin identifier. ``plugin_a`` doesn't define a sort key and hence will be -put after the other two. The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_a``. +will order both plugins based first on their bundling status and then on their plugin identifier. +``plugin_a`` and ``plugin_d`` don't define a sort key and hence will be +put after the other two, with ``plugin_d`` coming *before* ``plugin_a`` since it comes bundled with OctoPrint. +The execution order of the ``on_startup`` method will hence be ``plugin_b``, ``plugin_c``, ``plugin_d``, ``plugin_a``. Now, the execution order of the ``on_after_startup`` method will be determined based on another sorting context, ``StartupPlugin.on_after_startup`` for which all of the plugins return ``None``. Hence, the execution order of the -``on_after_startup`` method will be purely ordered by plugin identifier, ``plugin_a``, ``plugin_b``, ``plugin_c``. +``on_after_startup`` method will be ordered first by bundle status, then by plugin identifier: ``plugin_d``, ``plugin_a``, ``plugin_b``, ``plugin_c``. + +This will result in the following messages to be generated: + +.. code-block:: plain + + Plugin B starting up + Plugin C starting up + Plugin D starting up + Plugin A starting up + Plugin D started up + Plugin A started up + Plugin B started up + Plugin C started up .. _sec-plugins-mixins-injectedproperties: diff --git a/scripts/README.md b/scripts/README.md new file mode 100644 index 000000000..8fbc44621 --- /dev/null +++ b/scripts/README.md @@ -0,0 +1,17 @@ +# init/systemd files for OctoPrint. + +Assumes OctoPrint is installed under user pi at /home/pi/OctoPrint/venv/bin/octoprint. If you have a different +setup you'll need to adjust octoprint.default (init) or octoprint.service (systemd) accordingly. + +## init + +``` +octoprint.default => /etc/default/octoprint +octoprint.init => /etc/init.d/octoprint +``` + +## systemd + +``` +octoprint.service => /etc/systemd/service/octoprint.service +``` diff --git a/scripts/octoprint.service b/scripts/octoprint.service new file mode 100644 index 000000000..e71e07b53 --- /dev/null +++ b/scripts/octoprint.service @@ -0,0 +1,12 @@ +[Unit] +Description=The snappy web interface for your 3D printer +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=pi +ExecStart=/home/pi/OctoPrint/venv/bin/octoprint + +[Install] +WantedBy=multi-user.target diff --git a/setup.py b/setup.py index 39672f3b5..26b1208be 100644 --- a/setup.py +++ b/setup.py @@ -13,49 +13,55 @@ import octoprint_setuptools #----------------------------------------------------------------------------------------------------------------------- # Supported python versions -PYTHON_REQUIRES = ">=2.7.3,<3" # TODO change to >=2.7.9,<3 in 1.3.11 +PYTHON_REQUIRES = ">=2.7.9,<3" # Requirements for our application INSTALL_REQUIRES = [ - "flask>=0.10.1,<0.11", - "Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't - # guarantee backwards compatibility for plugins and such with that - # version, hence we need to pin to a lower version for now. See #1697 - "regex!=2018.11.6", # avoid broken 2018.11.6. See #2874 - "werkzeug>=0.8.3,<0.9", - "tornado==4.5.3", - #"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a - # vendored one - "PyYAML>=3.10,<3.11", - "Flask-Login>=0.2.11,<0.3", - "Flask-Principal>=0.3.5,<0.4", - "Flask-Babel>=0.9,<0.10", - "Flask-Assets>=0.10,<0.11", - "markdown>=2.6.9,<2.7", + # the following dependencies are non trivial to update since later versions introduce backwards incompatible + # changes that might affect plugins, or due to other observed problems + + "flask>=0.10.1,<0.11", # newer versions require newer Jinja versions + "Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't + # guarantee backwards compatibility for plugins and such with that + # version, hence we need to pin to a lower version for now. See #1697 + "tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585 + "Flask-Login>=0.2.11,<0.3", # some functions changed to properties in 0.3 + "regex!=2018.11.6", # avoid broken 2018.11.6. See #2874 + + # anything below this should be checked on releases for new versions + + "Flask-Principal>=0.4,<0.5", + "Flask-Babel>=0.12,<0.13", + "Flask-Assets>=0.12,<0.13", + "werkzeug>=0.15.1,<0.16", + "cachelib>=0.1,<0.2", + "PyYAML>=5.1,<6", + "markdown>=3.0,<3.1", "pyserial>=3.4,<3.5", "netaddr>=0.7.19,<0.8", - "watchdog>=0.8.3,<0.9", + "watchdog>=0.9.0,<0.10", "sarge==0.1.5post0", - "netifaces>=0.10.6,<0.11", - "pylru>=1.0.9,<1.1", - "rsa>=3.2.3,<3.3", - "pkginfo>=1.4.2,<1.5", - "requests>=2.18.4,<3", - "semantic_version>=2.4.2,<2.5", - "psutil>=5.4.6,<5.5", - "Click>=6.2,<6.3", + "netifaces>=0.10.9,<0.11", + "pylru>=1.2,<1.3", + "rsa>=4.0,<5", + "pkginfo>=1.5.0.1,<1.6", + "requests>=2.21.0,<3", + "semantic_version>=2.6,<2.7", + "psutil>=5.6.1,<5.7", + "Click>=7,<8", "awesome-slugify>=1.6.5,<1.7", "feedparser>=5.2.1,<5.3", - "chainmap>=1.0.2,<1.1", - "future>=0.15.2,<0.16", - "scandir>=1.3,<1.4", - "websocket-client>=0.40.0,<0.41", - "python-dateutil>=2.6.1,<2.7", - "wrapt>=1.10.11,<1.11", - "futures>=3.1.1,<3.2", - "emoji>=0.4.5,<0.5", - "monotonic>=1.3,<1.4", - "frozendict>=1.2,<1.3" + "chainmap>=1.0.3,<1.1", + "future>=0.17.1,<0.18", + "scandir>=1.10,<1.11", + "websocket-client>=0.56,<0.57", + "wrapt>=1.11.1,<1.12", + "futures>=3.2,<3.3", + "emoji>=0.5.1,<0.6", + "monotonic>=1.5,<1.6", + "frozendict>=1.2,<1.3", + "sentry-sdk==0.7.7", + "typing>=3.6.6,<4" ] if sys.platform == "darwin": @@ -67,7 +73,7 @@ EXTRA_REQUIRES = dict( develop=[ # Testing dependencies "mock>=2.0.0,<3", - "nose>=1.3.0,<1.4", + "nose>=1.3.7,<1.4", "ddt", # Documentation dependencies @@ -79,7 +85,7 @@ EXTRA_REQUIRES = dict( # Dependencies for developing OctoPrint plugins plugins=[ - "cookiecutter>=1.4,<1.7" + "cookiecutter>=1.6,<1.7" ] ) @@ -189,7 +195,7 @@ def params(): keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint" project_urls={ - "Community Forum": "https://discourse.octoprint.org", + "Community Forum": "https://community.octoprint.org", "Bug Reports": "https://github.com/foosel/OctoPrint/issues", "Source": "https://github.com/foosel/OctoPrint", "Funding": "https://donate.octoprint.org" diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 48cf8f25c..fc8c8f1d2 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -103,8 +103,12 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, if callable(after_logging): after_logging(**kwargs) - settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"]) - safe_mode = safe_mode or settings_safe_mode + settings_start_once_in_safemode = "settings" if settings.getBoolean(["server", "startOnceInSafeMode"]) else None + settings_incomplete_startup_safemode = "incomplete_startup" \ + if settings.getBoolean(["server", "incompleteStartup"]) \ + and not settings.getBoolean(["server", "ignoreIncompleteStartup"]) \ + else None + safe_mode = safe_mode or settings_start_once_in_safemode or settings_incomplete_startup_safemode kwargs["safe_mode"] = safe_mode if callable(after_safe_mode): after_safe_mode(**kwargs) @@ -141,7 +145,7 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, ignore_blacklist=ignore_blacklist, connectivity_checker=connectivity_checker) except Exception as ex: - raise FatalStartupError("Could not initialize settings manager", cause=ex) + raise FatalStartupError("Could not initialize plugin manager", cause=ex) kwargs["plugin_manager"] = plugin_manager if callable(after_plugin_manager): @@ -342,9 +346,12 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti import os + # we need this so that octoprint.plugins is in sys.modules and no warnings are caused when loading bundled plugins + import octoprint.plugins + logger = log.getLogger(__name__ + ".startup") - plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True), + plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), "octoprint.plugins", True), settings.getBaseFolder("plugins")] plugin_entry_points = ["octoprint.plugin"] plugin_disabled_list = settings.get(["plugins", "_disabled"]) diff --git a/src/octoprint/__main__.py b/src/octoprint/__main__.py index 3dd81998d..b794f4798 100644 --- a/src/octoprint/__main__.py +++ b/src/octoprint/__main__.py @@ -2,6 +2,10 @@ # coding=utf-8 from __future__ import absolute_import, division, print_function +import sys +if sys.version_info[0] >= 3: + raise RuntimeError("Sorry, OctoPrint does not yet support Python 3") + if __name__ == "__main__": import octoprint octoprint.main() diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py index 9c9eeab62..5895ced6a 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag @@ -9,13 +11,14 @@ # versioneer-0.15+dev (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" -from __future__ import absolute_import, division, print_function import errno +import io import os import re import subprocess import sys +import logging def get_keywords(): @@ -41,7 +44,7 @@ def get_config(): # _version.py cfg = VersioneerConfig() cfg.VCS = "git" - cfg.style = "pep440-post" + cfg.style = "pep440-tag" cfg.tag_prefix = "" cfg.parentdir_prefix = "" cfg.versionfile_source = "src/octoprint/_version.py" @@ -130,7 +133,7 @@ def git_get_keywords(versionfile_abs): # _version.py. keywords = {} try: - f = open(versionfile_abs, "r") + f = io.open(versionfile_abs, "rt", encoding="utf-8") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) @@ -156,11 +159,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = set(r.strip() for r in refnames.strip("()").split(",")) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = set(r[len(TAG):] for r in refs if r.startswith(TAG)) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -169,7 +172,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = set(r for r in refs if re.search(r'\d', r)) if verbose: print("discarding '%s', no digits" % ",".join(refs-tags)) @@ -254,7 +257,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): abbrev_ref_out = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) - if abbrev_ref_out is not None: + if abbrev_ref_out is not None and abbrev_ref_out != "HEAD": pieces["branch"] = abbrev_ref_out.strip() # now we have TAG-NUM-gHEX or HEX @@ -305,17 +308,18 @@ def git_parse_lookup_file(path): if not os.path.exists(path): return [] + import re lookup = [] - with open(path, "r") as f: + with io.open(path, "rt", encoding="utf-8") as f: for line in f: if '#' in line: - line = line[:line.rindex("#")] + line = line[:line.index("#")] line = line.strip() if not line: continue try: - split_line = map(lambda x: x.strip(), line.split()) + split_line = list(map(lambda x: x.strip(), line.split())) if not len(split_line): continue @@ -336,7 +340,8 @@ def git_parse_lookup_file(path): continue lookup.append(entry) - except: + except Exception: + logging.getLogger(__name__).exception("Versioneer problem") break return lookup @@ -354,6 +359,9 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command): raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed") current_branch = stdout.strip() + if current_branch == "HEAD": + raise NotThisMethod("not on a branch") + for matcher, render, tag, ref_commit in lookup: if matcher.match(current_branch): if tag is None or ref_commit is None: @@ -441,6 +449,31 @@ def render_pep440(pieces): return rendered +def render_pep440_tag(pieces): + """TAG[[.postDISTANCE].dev0+gHEX] -- Just the tag if not dirty, else more info + + Useful for projects that want commit based tracking on some branches + but have the master branch only report tags, to allow for commits that + do not modify actual code (e.g. to .github/* or docs). + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["dirty"]: + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + return rendered + + def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. @@ -591,6 +624,8 @@ def render(pieces, style): rendered = render_pep440_old(pieces) elif style == "pep440-dev": rendered = render_pep440_dev(pieces) + elif style == "pep440-tag": + rendered = render_pep440_tag(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index bb69de05c..d6b5b09c4 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -34,6 +34,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle import time import yaml + from octoprint.util import monotonic_time from octoprint.util.gcodeInterpreter import gcode throttle_callback = None @@ -52,7 +53,7 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle if len(offsets) < maxt: offsets += [(0, 0)] * (maxt - len(offsets)) - start_time = time.time() + start_time = monotonic_time() progress_callback = None if progress: @@ -68,7 +69,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=" ", allow_unicode=True)) diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index facfc80cb..c1a7938f9 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -92,7 +92,8 @@ class OctoPrintPluginCommands(click.MultiCommand): continue result[name + self.sep + command.name] = command except: - 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 diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index dc9ff6cbf..d6768a4ca 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -11,7 +11,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.""" @@ -26,6 +26,15 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi logger.info("Starting OctoPrint {}".format(__display_version__)) if safe_mode: logger.info("Starting in SAFE MODE. Third party plugins will be disabled!") + if safe_mode == "flag": + reason = "command line flag" + elif safe_mode == "settings": + reason = "setting in config.yaml" + elif safe_mode == "incomplete_startup": + reason = "problem during last startup" + else: + reason = "unknown" + logger.info("Reason for safe mode: {}".format(reason)) if recorder and len(recorder): logger.info(get_divider_line("-", "Logged during platform initialization:")) @@ -101,6 +110,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi environment_detector=environment_detector, host=host, port=port, + v6_only=v6_only, debug=debug, safe_mode=safe_mode, allow_root=allow_root, @@ -111,9 +121,13 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi server_options = bulk_options([ click.option("--host", type=click.STRING, callback=set_ctx_obj_option, - help="Specify the host on which to bind the server."), + help="Specify the host address on which to bind the server."), click.option("--port", type=click.INT, callback=set_ctx_obj_option, help="Specify the port on which to bind the server."), + click.option("-4", "--ipv4", "v4", is_flag=True, callback=set_ctx_obj_option, + help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present."), + click.option("-6", "--ipv6", "v6", is_flag=True, callback=set_ctx_obj_option, + help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present."), click.option("--logging", type=click.Path(), callback=set_ctx_obj_option, help="Specify the config file to use for configuring logging."), click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option, @@ -123,7 +137,7 @@ server_options = bulk_options([ click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option, help="Disable processing of the plugin blacklist.") ]) -"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, +"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``-4``, ``-6`` ``--logging``, ``--iknowwhatimdoing`` and ``--debug``.""" daemon_options = bulk_options([ @@ -153,11 +167,11 @@ def enable_safemode(ctx, **kwargs): click.echo(e.message, err=True) click.echo("There was a fatal error initializing the settings manager.", err=True) ctx.exit(-1) + else: + settings.setBoolean(["server", "startOnceInSafeMode"], True) + settings.save() - settings.setBoolean(["server", "startOnceInSafeMode"], True) - settings.save() - - click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.") + click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.") @server_commands.command(name="serve") @@ -172,6 +186,8 @@ def serve_command(ctx, **kwargs): host = get_value("host") port = get_value("port") + v4 = get_value("v4") + v6 = get_value("v6") logging = get_value("logging") allow_root = get_value("allow_root") debug = get_value("debug") @@ -179,10 +195,13 @@ def serve_command(ctx, **kwargs): basedir = get_value("basedir") configfile = get_value("configfile") verbosity = get_value("verbosity") - safe_mode = get_value("safe_mode") + safe_mode = "flag" if get_value("safe_mode") else None ignore_blacklist = get_value("ignore_blacklist") - run_server(basedir, configfile, host, port, debug, + if v4 and not host: + host = "0.0.0.0" + + run_server(basedir, configfile, host, port, v6, debug, allow_root, logging, verbosity, safe_mode, ignore_blacklist) @@ -209,6 +228,8 @@ if sys.platform != "win32" and sys.platform != "darwin": host = get_value("host") port = get_value("port") + v4 = get_value("v4") + v6 = get_value("v6") logging = get_value("logging") allow_root = get_value("allow_root") debug = get_value("debug") @@ -217,9 +238,12 @@ if sys.platform != "win32" and sys.platform != "darwin": basedir = get_value("basedir") configfile = get_value("configfile") verbosity = get_value("verbosity") - safe_mode = get_value("safe_mode") + safe_mode = "flag" if get_value("safe_mode") else None ignore_blacklist = get_value("ignore_blacklist") + if v4 and not host: + host = "0.0.0.0" + if pid is None: click.echo("No path to a pidfile set", file=sys.stderr) @@ -227,14 +251,15 @@ if sys.platform != "win32" and sys.platform != "darwin": from octoprint.daemon import Daemon class OctoPrintDaemon(Daemon): - def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, - safe_mode, ignore_blacklist): + def __init__(self, pidfile, basedir, configfile, host, port, v6_only, debug, allow_root, logging_config, + verbosity, safe_mode, ignore_blacklist): Daemon.__init__(self, pidfile) self._basedir = basedir self._configfile = configfile self._host = host self._port = port + self._v6_only = v6_only self._debug = debug self._allow_root = allow_root self._logging_config = logging_config @@ -243,12 +268,12 @@ if sys.platform != "win32" and sys.platform != "darwin": self._ignore_blacklist = ignore_blacklist def run(self): - run_server(self._basedir, self._configfile, self._host, self._port, self._debug, + run_server(self._basedir, self._configfile, self._host, self._port, self._v6_only, self._debug, self._allow_root, self._logging_config, self._verbosity, self._safe_mode, self._ignore_blacklist, octoprint_daemon=self) - octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity, - safe_mode, ignore_blacklist) + octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, v6, debug, allow_root, logging, + verbosity, safe_mode, ignore_blacklist) if command == "start": octoprint_daemon.start() diff --git a/src/octoprint/environment.py b/src/octoprint/environment.py index 4d539297e..86e673121 100644 --- a/src/octoprint/environment.py +++ b/src/octoprint/environment.py @@ -7,7 +7,6 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms import copy import logging import os -import platform import sys import threading import yaml @@ -16,6 +15,7 @@ import psutil from octoprint.plugin import EnvironmentDetectionPlugin from octoprint.util.platform import get_os +from octoprint.util.version import get_python_version_string class EnvironmentDetector(object): @@ -25,10 +25,15 @@ class EnvironmentDetector(object): self._cache = None self._cache_lock = threading.RLock() - self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin) - self._logger = logging.getLogger(__name__) + try: + self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin) + except Exception: + # just in case, see #3100... + self._logger.exception("There was an error fetching EnvironmentDetectionPlugins from the plugin manager") + self._environment_plugins = [] + @property def environment(self): with self._cache_lock: @@ -70,7 +75,7 @@ class EnvironmentDetector(object): # determine python version try: - result["version"] = platform.python_version() + result["version"] = get_python_version_string() except: self._logger.exception("Error detecting python version") @@ -120,7 +125,8 @@ class EnvironmentDetector(object): result[implementation._identifier] = additional except: 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 diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 4b2e2a12b..74374f7ec 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -14,6 +14,7 @@ except ImportError: import Queue as queue import threading import collections +import re from octoprint.settings import settings import octoprint.plugin @@ -23,7 +24,7 @@ _instance = None def all_events(): - return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("__")] + return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("_") and not name in ("register_event",)] class Events(object): @@ -119,6 +120,23 @@ class Events(object): # Settings SETTINGS_UPDATED = "SettingsUpdated" + @classmethod + def register_event(cls, event, prefix=None): + name = cls._to_identifier(event) + if prefix: + event = prefix + event + name = cls._to_identifier(prefix) + name + setattr(cls, name, event) + return name, event + + # based on https://stackoverflow.com/a/1176023 + _first_cap_re = re.compile('(.)([A-Z][a-z]+)') + _all_cap_re = re.compile('([a-z0-9])([A-Z])') + + @classmethod + def _to_identifier(cls, name): + s1 = cls._first_cap_re.sub(r'\1_\2', name) + return cls._all_cap_re.sub(r'\1_\2', s1).upper() def eventManager(): global _instance @@ -135,6 +153,7 @@ class EventManager(object): def __init__(self): self._registeredListeners = collections.defaultdict(list) self._logger = logging.getLogger(__name__) + self._logger_fire = logging.getLogger("{}.fire".format(__name__)) self._startup_signaled = False self._shutdown_signaled = False @@ -156,19 +175,18 @@ class EventManager(object): self._shutdown_signaled = True eventListeners = self._registeredListeners[event] - self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload)) + self._logger_fire.debug("Firing event: {} (Payload: {!r})".format(event, payload)) for listener in eventListeners: - self._logger.debug("Sending action to %r" % listener) + self._logger.debug("Sending action to {!r}".format(listener)) try: listener(event, payload) except: - self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener)) + self._logger.exception("Got an exception while sending event {} (Payload: {!r}) to {}".format(event, payload, listener)) octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin, "on_event", - args=(event, payload), - initialized=True) + args=(event, payload)) self._logger.info("Event loop shut down") except: self._logger.exception("Ooops, the event bus worker loop crashed") @@ -211,7 +229,7 @@ class EventManager(object): if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables": # when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode" - # TODO v1.3.0 Remove again + # TODO v1.4.0 Remove again import copy legacy_payload = copy.deepcopy(payload) legacy_payload["type"] = "gcode" @@ -227,7 +245,7 @@ class EventManager(object): return self._registeredListeners[event].append(callback) - self._logger.debug("Subscribed listener %r for event %s" % (callback, event)) + self._logger.debug("Subscribed listener {!r} for event {}".format(callback, event)) def unsubscribe (self, event, callback): """ @@ -239,7 +257,7 @@ class EventManager(object): return self._registeredListeners[event].remove(callback) - self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event)) + self._logger.debug("Unsubscribed listener {!r} for event {}".format(callback, event)) def join(self, timeout=None): self._worker.join(timeout) diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 44cd9e4f1..8124c06ce 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -30,10 +30,6 @@ extensions = dict( def full_extension_tree(): result = dict( - # extensions for 3d model files - model=dict( - stl=ContentTypeMapping(["stl"], "application/sla") - ), # extensions for printable machine code machinecode=dict( gcode=ContentTypeMapping(["gcode", "gco", "g"], "text/plain") @@ -74,6 +70,18 @@ def full_extension_tree(): else: return merged + slicer_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin) + for plugin in slicer_plugins: + try: + plugin_result = plugin.get_slicer_extension_tree() + if plugin_result is None or not isinstance(plugin_result, dict): + continue + result = octoprint.util.dict_merge(result, plugin_result, leaf_merger=leaf_merger) + except: + logging.getLogger(__name__).exception("Exception while retrieving additional extension " + "tree entries from SlicerPlugin {name}".format(name=plugin._identifier), + extra=dict(plugin=plugin._identifier)) + extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree") for name, hook in extension_tree_hooks.items(): try: @@ -82,12 +90,14 @@ def full_extension_tree(): continue result = octoprint.util.dict_merge(result, hook_result, leaf_merger=leaf_merger) except: - logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from hook {name}".format(name=name)) + logging.getLogger(__name__).exception("Exception while retrieving additional extension " + "tree entries from hook {name}".format(name=name), + extra=dict(plugin=name)) return result def get_extensions(type, subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() for key, value in subtree.items(): @@ -101,7 +111,7 @@ def get_extensions(type, subtree=None): return None def get_all_extensions(subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() result = [] @@ -120,7 +130,7 @@ def get_all_extensions(subtree=None): return result def get_path_for_extension(extension, subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() for key, value in subtree.items(): @@ -136,11 +146,11 @@ def get_path_for_extension(extension, subtree=None): return None def get_content_type_mapping_for_extension(extension, subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() for key, value in subtree.items(): - content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value. extensions + content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions list_extension_matches = isinstance(value, (list, tuple)) and extension in value if content_extension_matches or list_extension_matches: @@ -345,7 +355,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, @@ -370,8 +380,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, @@ -424,7 +433,8 @@ class FileManager(object): try: plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress) except: - self._logger.exception("Exception while sending slicing progress to plugin %s" % plugin._identifier) + 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)) @@ -459,11 +469,11 @@ class FileManager(object): if printer_profile is None: printer_profile = self._printer_profile_manager.get_current_or_default() - for hook in self._preprocessor_hooks.values(): + for name, hook in self._preprocessor_hooks.items(): try: hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite) except: - self._logger.exception("Error when calling preprocessor hook {}, ignoring".format(hook)) + 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: diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index b8b9dd246..cdb61b5a1 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -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 diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 9cafb0811..1b2b66b8f 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -8,9 +8,10 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging import os -import pylru import shutil import re +import pylru +import copy try: from os import scandir, walk @@ -19,7 +20,6 @@ except ImportError: from octoprint.util import atomic_write from contextlib import contextmanager -from copy import deepcopy from past.builtins import basestring @@ -28,7 +28,7 @@ from slugify import Slugify import octoprint.filemanager -from octoprint.util import is_hidden_path, to_unicode +from octoprint.util import is_hidden_path, to_unicode, timing class StorageInterface(object): """ @@ -485,6 +485,8 @@ class LocalFileStorage(StorageInterface): import threading self._metadata_lock_mutex = threading.RLock() self._metadata_locks = dict() + self._persisted_metadata_lock_mutex = threading.RLock() + self._persisted_metadata_locks = dict() self._metadata_cache = pylru.lrucache(10) @@ -883,6 +885,8 @@ class LocalFileStorage(StorageInterface): if not name in metadata: return + metadata = self._copied_metadata(metadata, name) + if not key in metadata[name] or overwrite: metadata[name][key] = data metadata_dirty = True @@ -907,6 +911,7 @@ class LocalFileStorage(StorageInterface): if not key in metadata[name]: return + metadata = self._copied_metadata(metadata, name) del metadata[name][key] self._save_metadata(path, metadata) @@ -1050,10 +1055,7 @@ class LocalFileStorage(StorageInterface): ##~~ internals def _add_history(self, name, path, data): - metadata = self._get_metadata(path) - - if not name in metadata: - metadata[name] = dict() + metadata = self._copied_metadata(self._get_metadata(path), name) if not "hash" in metadata[name]: metadata[name]["hash"] = self._create_hash(os.path.join(path, name)) @@ -1071,6 +1073,8 @@ class LocalFileStorage(StorageInterface): if not name in metadata or not "history" in metadata[name]: return + metadata = self._copied_metadata(metadata, name) + try: metadata[name]["history"][index].update(data) self._calculate_stats_from_history(name, path, metadata=metadata, save=False) @@ -1084,6 +1088,8 @@ class LocalFileStorage(StorageInterface): if not name in metadata or not "history" in metadata[name]: return + metadata = self._copied_metadata(metadata, name) + try: del metadata[name]["history"][index] self._calculate_stats_from_history(name, path, metadata=metadata, save=False) @@ -1093,9 +1099,9 @@ class LocalFileStorage(StorageInterface): def _calculate_stats_from_history(self, name, path, metadata=None, save=True): if metadata is None: - metadata = self._get_metadata(path) + metadata = self._copied_metadata(self._get_metadata(path), name) - if not name in metadata or not "history" in metadata[name]: + if not "history" in metadata[name]: return # collect data from history @@ -1164,12 +1170,9 @@ class LocalFileStorage(StorageInterface): if file_type: file_type = file_type[0] - metadata = self._get_metadata(path) + metadata = self._copied_metadata(self._get_metadata(path), name) metadata_dirty = False - if not name in metadata: - metadata[name] = dict() - if not "hash" in metadata[name]: metadata[name]["hash"] = self._create_hash(os.path.join(path, name)) @@ -1241,13 +1244,10 @@ class LocalFileStorage(StorageInterface): self._save_metadata(path, metadata) def _remove_links(self, name, path, links): - metadata = self._get_metadata(path) + metadata = self._copied_metadata(self._get_metadata(path), name) metadata_dirty = False - if not name in metadata or not "hash" in metadata[name]: - hash = self._create_hash(os.path.join(path, name)) - else: - hash = metadata[name]["hash"] + hash = metadata[name].get("hash", self._create_hash(os.path.join(path, name))) for rel, data in links: if (rel == "model" or rel == "machinecode") and "name" in data: @@ -1255,6 +1255,7 @@ class LocalFileStorage(StorageInterface): ref_rel = "model" if rel == "machinecode" else "machinecode" for link in metadata[data["name"]]["links"]: if link["rel"] == ref_rel and "name" in link and link["name"] == name and "hash" in link and link["hash"] == hash: + metadata[data["name"]] = copy.deepcopy(metadata[data["name"]]) metadata[data["name"]]["links"].remove(link) metadata_dirty = True @@ -1330,10 +1331,14 @@ class LocalFileStorage(StorageInterface): if entry_name in metadata and isinstance(metadata[entry_name], dict): entry_metadata = metadata[entry_name] if not "display" in entry_metadata and entry_display != entry_name: + if not metadata_dirty: + metadata = self._copied_metadata(metadata, entry_name) metadata[entry_name]["display"] = entry_display entry_metadata["display"] = entry_display metadata_dirty = True else: + if not metadata_dirty: + metadata = self._copied_metadata(metadata, entry_name) entry_metadata = self._add_basic_metadata(path, entry_name, display_name=entry_display, save=False, @@ -1363,10 +1368,14 @@ class LocalFileStorage(StorageInterface): if entry_name in metadata and isinstance(metadata[entry_name], dict): entry_metadata = metadata[entry_name] if not "display" in entry_metadata and entry_display != entry_name: + if not metadata_dirty: + metadata = self._copied_metadata(metadata, entry_name) metadata[entry_name]["display"] = entry_display entry_metadata["display"] = entry_display metadata_dirty = True elif entry_name != entry_display: + if not metadata_dirty: + metadata = self._copied_metadata(metadata, entry_name) entry_metadata = self._add_basic_metadata(path, entry_name, display_name=entry_display, save=False, @@ -1450,6 +1459,8 @@ class LocalFileStorage(StorageInterface): entry_data["display"] = display_name entry_data.update(additional_metadata) + + metadata = copy.copy(metadata) metadata[entry] = entry_data if save: @@ -1481,6 +1492,8 @@ class LocalFileStorage(StorageInterface): if not name in metadata: return + metadata = copy.copy(metadata) + if "hash" in metadata[name]: hash = metadata[name]["hash"] for m in metadata.values(): @@ -1494,7 +1507,7 @@ class LocalFileStorage(StorageInterface): def _update_metadata_entry(self, path, name, data): with self._get_metadata_lock(path): - metadata = self._get_metadata(path) + metadata = copy.copy(self._get_metadata(path)) metadata[name] = data self._save_metadata(path, metadata) @@ -1513,41 +1526,62 @@ class LocalFileStorage(StorageInterface): with self._get_metadata_lock(destination_path): self._update_metadata_entry(destination_path, destination_name, source_data) - def _get_metadata(self, path): - with self._get_metadata_lock(path): - if path in self._metadata_cache: - return deepcopy(self._metadata_cache[path]) + def _get_metadata(self, path, force=False): + import json - self._migrate_metadata(path) + if not force: + metadata = self._metadata_cache.get(path) + if metadata: + return metadata - metadata_path = os.path.join(path, ".metadata.json") + self._migrate_metadata(path) + + metadata_path = os.path.join(path, ".metadata.json") + + metadata = None + with self._get_persisted_metadata_lock(path): if os.path.exists(metadata_path): with open(metadata_path) as f: try: - import json metadata = json.load(f) except: self._logger.exception("Error while reading .metadata.json from {path}".format(**locals())) - else: - if isinstance(metadata, dict): - self._metadata_cache[path] = deepcopy(metadata) - return metadata + + if isinstance(metadata, dict): + old_size = len(metadata) + 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._save_metadata(path, metadata) + else: + with self._get_metadata_lock(path): + self._metadata_cache[path] = metadata + return metadata + else: return dict() def _save_metadata(self, path, metadata): + import json + with self._get_metadata_lock(path): + self._metadata_cache[path] = metadata + + with self._get_persisted_metadata_lock(path): metadata_path = os.path.join(path, ".metadata.json") try: - import json with atomic_write(metadata_path) as f: json.dump(metadata, f, indent=4, separators=(",", ": ")) except: self._logger.exception("Error while writing .metadata.json to {path}".format(**locals())) - else: - self._metadata_cache[path] = deepcopy(metadata) def _delete_metadata(self, path): with self._get_metadata_lock(path): + if path in self._metadata_cache: + del self._metadata_cache[path] + + with self._get_persisted_metadata_lock(path): metadata_files = (".metadata.json", ".metadata.yaml") for metadata_file in metadata_files: metadata_path = os.path.join(path, metadata_file) @@ -1556,15 +1590,19 @@ class LocalFileStorage(StorageInterface): os.remove(metadata_path) except: self._logger.exception("Error while deleting {metadata_file} from {path}".format(**locals())) - if path in self._metadata_cache: - del self._metadata_cache[path] + + @staticmethod + def _copied_metadata(metadata, name): + metadata = copy.copy(metadata) + metadata[name] = copy.deepcopy(metadata.get(name, dict())) + return metadata def _migrate_metadata(self, path): # we switched to json in 1.3.9 - if we still have yaml here, migrate it now import yaml import json - with self._get_metadata_lock(path): + with self._get_persisted_metadata_lock(path): metadata_path_yaml = os.path.join(path, ".metadata.yaml") metadata_path_json = os.path.join(path, ".metadata.json") @@ -1574,7 +1612,10 @@ class LocalFileStorage(StorageInterface): if os.path.exists(metadata_path_json): # already migrated - # TODO 1.3.10 Remove ".metadata.yaml" files + try: + os.remove(metadata_path_yaml) + except: + self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals())) return with open(metadata_path_yaml) as f: @@ -1591,7 +1632,10 @@ class LocalFileStorage(StorageInterface): with atomic_write(metadata_path_json) as f: json.dump(metadata, f, indent=4, separators=(",", ": ")) - # TODO 1.3.10 Remove ".metadata.yaml" files + try: + os.remove(metadata_path_yaml) + except: + self._logger.exception("Error while removing .metadata.yaml from {path}".format(**locals())) @contextmanager def _get_metadata_lock(self, path): @@ -1613,3 +1657,24 @@ class LocalFileStorage(StorageInterface): del self._metadata_locks[path] else: self._metadata_locks[path] = (counter, lock) + + @contextmanager + def _get_persisted_metadata_lock(self, path): + with self._persisted_metadata_lock_mutex: + if path not in self._persisted_metadata_locks: + import threading + self._persisted_metadata_locks[path] = (0, threading.RLock()) + + counter, lock = self._persisted_metadata_locks[path] + counter += 1 + self._persisted_metadata_locks[path] = (counter, lock) + + yield lock + + with self._persisted_metadata_lock_mutex: + counter = self._persisted_metadata_locks[path][0] + counter -= 1 + if counter <= 0: + del self._persisted_metadata_locks[path] + else: + self._persisted_metadata_locks[path] = (counter, lock) diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 9bcdcd625..500e1090a 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -33,16 +33,6 @@ from octoprint.util import deprecated _instance = None def _validate_plugin(phase, plugin_info): - if phase == "after_load": - if plugin_info.implementation is not None and isinstance(plugin_info.implementation, AppPlugin): - # transform app plugin into hook - import warnings - warnings.warn("{name} uses deprecated plugin mixin AppPlugin, use octoprint.accesscontrol.appkey hook instead".format(name=plugin_info.key), DeprecationWarning) - - hooks = plugin_info.hooks - if not "octoprint.accesscontrol.appkey" in hooks: - hooks["octoprint.accesscontrol.appkey"] = plugin_info.implementation.get_additional_apps - setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks) return True def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None, @@ -206,8 +196,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)): @@ -221,7 +210,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): @@ -231,7 +220,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) @@ -307,6 +296,17 @@ class PluginSettings(object): .. method:: set_boolean(path, value, force=False) Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it. + + .. method:: save(force=False, trigger_event=False) + + Saves the settings to ``config.yaml`` if there are active changes. If ``force`` is set to ``True`` the settings + will be saved even if there are no changes. Settings ``trigger_event`` to ``True`` will cause a ``SettingsUpdated`` + :ref:`event ` to get triggered. + + :param force: Force saving to ``config.yaml`` even if there are no changes. + :type force: boolean + :param trigger_event: Trigger the ``SettingsUpdated`` :ref:`event ` on save. + :type trigger_event: boolean """ def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None): diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 54566de4f..a269c9dc4 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -37,7 +37,9 @@ import inspect import pkg_resources import pkginfo -from past.builtins import basestring +from past.builtins import unicode + +from octoprint.util import to_unicode try: from os import scandir @@ -46,6 +48,7 @@ except ImportError: EntryPointOrigin = namedtuple("EntryPointOrigin", "type, entry_point, module_name, package_name, package_version") FolderOrigin = namedtuple("FolderOrigin", "type, folder") +ModuleOrigin = namedtuple("PackageOrigin", "type, module_name, folder") class PluginInfo(object): """ @@ -207,13 +210,13 @@ class PluginInfo(object): def __str__(self): if self.version: - return "{name} ({version})".format(name=self.name, version=self.version) + return u"{name} ({version})".format(name=self.name, version=self.version) else: - return self.name + return to_unicode(self.name) - def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""), - show_location=False, location_str=" - {location}", - show_enabled=False, enabled_strs=("* ", " ", "X ")): + def long_str(self, show_bundled=False, bundled_strs=(u" [B]", u""), + show_location=False, location_str=u" - {location}", + show_enabled=False, enabled_strs=(u"* ", u" ", u"X ")): """ Long string representation of the plugin's information. Will return a string of the format ````. @@ -242,17 +245,19 @@ class PluginInfo(object): str: The long string representation of the plugin as described above """ if show_enabled: - ret = enabled_strs[2] if self.blacklisted else (enabled_strs[0] if self.enabled else enabled_strs[1]) + ret = to_unicode(enabled_strs[2]) if self.blacklisted \ + else (to_unicode(enabled_strs[0]) if self.enabled + else to_unicode(enabled_strs[1])) else: - ret = "" + ret = u"" - ret += str(self) + ret += unicode(self) if show_bundled: - ret += bundled_strs[0] if self.bundled else bundled_strs[1] + ret += to_unicode(bundled_strs[0]) if self.bundled else to_unicode(bundled_strs[1]) if show_location and self.location: - ret += location_str.format(location=self.location) + ret += to_unicode(location_str).format(location=self.location) return ret @@ -652,7 +657,7 @@ class PluginManager(object): result_added.update(added) result_found += found except: - self.logger.exception("Error fetching plugins from folders") + self.logger.exception(u"Error fetching plugins from folders") if self.plugin_entry_points: existing.update(result_added) @@ -663,7 +668,7 @@ class PluginManager(object): result_added.update(added) result_found += found except: - self.logger.exception("Error fetching plugins from entry points") + self.logger.exception(u"Error fetching plugins from entry points") return result_added, result_found @@ -674,15 +679,18 @@ class PluginManager(object): for folder in folders: try: flagged_readonly = False + package = None if isinstance(folder, (list, tuple)): if len(folder) == 2: folder, flagged_readonly = folder + elif len(folder) == 3: + folder, package, flagged_readonly = folder else: continue actual_readonly = not os.access(folder, os.W_OK) if not os.path.exists(folder): - self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder)) + self.logger.warn(u"Plugin folder {folder} could not be found, skipping it".format(folder=folder)) continue for entry in scandir(folder): @@ -714,16 +722,23 @@ class PluginManager(object): bundled = flagged_readonly - plugin = self._import_plugin_from_module(key, folder=folder, bundled=bundled) + module_name = None + if package: + module_name = "{}.{}".format(package, key) + + plugin = self._import_plugin_from_module(key, module_name=module_name, folder=folder, bundled=bundled) if plugin: - plugin.origin = FolderOrigin("folder", folder) + if module_name: + plugin.origin = ModuleOrigin("module", module_name, folder) + else: + plugin.origin = FolderOrigin("folder", folder) plugin.managable = not flagged_readonly and not actual_readonly plugin.enabled = False added[key] = plugin except: - self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder)) + self.logger.exception(u"Error processing folder entry {!r} from folder {}".format(entry, folder)) except: - self.logger.exception("Error processing folder {}".format(folder)) + self.logger.exception(u"Error processing folder {}".format(folder)) return added, found @@ -753,8 +768,8 @@ class PluginManager(object): try: yield entry except: - self.logger.exception("Something went wrong while processing the entry points of a package in the " - "Python environment - broken entry_points.txt in some package?") + self.logger.exception(u"Something went wrong while processing the entry points of a package in the " + u"Python environment - broken entry_points.txt in some package?") for group in groups: for entry_point in wrapped(working_set.iter_entry_points(group=group, name=None)): @@ -773,7 +788,7 @@ class PluginManager(object): try: entry_point_metadata = EntryPointMetadata(entry_point) except: - self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name)) + self.logger.exception(u"Something went wrong while retrieving metadata for module {}".format(module_name)) else: kwargs.update(dict( name=entry_point_metadata.name, @@ -803,7 +818,7 @@ class PluginManager(object): added[key] = plugin except: - self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group)) + self.logger.exception(u"Error processing entry point {!r} for group {}".format(entry_point, group)) return added, found @@ -818,7 +833,7 @@ class PluginManager(object): else: return None except: - self.logger.warn("Could not locate plugin {key}".format(key=key)) + self.logger.warn(u"Could not locate plugin {key}".format(key=key)) return None # Create a simple dummy entry first ... @@ -827,11 +842,11 @@ class PluginManager(object): plugin.bundled = bundled if self._is_plugin_disabled(key): - self.logger.info("Plugin {} is disabled.".format(plugin)) + self.logger.info(u"Plugin {} is disabled.".format(plugin)) plugin.forced_disabled = True if self._is_plugin_blacklisted(key) or (plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version)): - self.logger.warn("Plugin {} is blacklisted.".format(plugin)) + self.logger.warn(u"Plugin {} is blacklisted.".format(plugin)) plugin.blacklisted = True if not plugin.validate("before_import", additional_validators=self.plugin_validators): @@ -839,12 +854,15 @@ class PluginManager(object): # ... then create and return the real one return self._import_plugin(key, *module, - name=name, version=version, summary=summary, author=author, url=url, + module_name=module_name, name=name, version=version, summary=summary, author=author, url=url, license=license, bundled=bundled, parsed_metadata=plugin.parsed_metadata) - def _import_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None): + def _import_plugin(self, key, f, filename, description, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None): try: - instance = imp.load_module(key, f, filename, description) + if module_name: + instance = imp.load_module(module_name, f, filename, description) + else: + instance = imp.load_module(key, f, filename, description) plugin = PluginInfo(key, filename, instance, name=name, version=version, @@ -855,13 +873,13 @@ class PluginManager(object): parsed_metadata=parsed_metadata) plugin.bundled = bundled except: - self.logger.exception("Error loading plugin {key}".format(key=key)) + self.logger.exception(u"Error loading plugin {key}".format(key=key)) return None if plugin.check(): return plugin else: - self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin))) + self.logger.info(u"Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin))) return None def _is_plugin_disabled(self, key): @@ -881,7 +899,7 @@ class PluginManager(object): self.plugin_blacklist)) def reload_plugins(self, startup=False, initialize_implementations=True, force_reload=None): - self.logger.info("Loading plugins from {folders} and installed plugin packages...".format( + self.logger.info(u"Loading plugins from {folders} and installed plugin packages...".format( folders=", ".join(map(lambda x: x[0] if isinstance(x, tuple) else str(x), self.plugin_folders)) )) @@ -925,7 +943,7 @@ class PluginManager(object): try: if plugin.loaded and not plugin.forced_disabled: if plugin.blacklisted: - self.logger.warn("Plugin {} is blacklisted. Not enabling it.".format(plugin)) + self.logger.warn(u"Plugin {} is blacklisted. Not enabling it.".format(plugin)) continue self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup) except PluginNeedsRestart: @@ -938,9 +956,9 @@ class PluginManager(object): force_reload=force_reload) if len(self.enabled_plugins) <= 0: - self.logger.info("No plugins found") + self.logger.info(u"No plugins found") else: - self.logger.info("Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format( + self.logger.info(u"Found {count} plugin(s) providing {implementations} mixin implementations, {hooks} hook handlers".format( count=len(self.enabled_plugins) + len(self.disabled_plugins), implementations=len(self.plugin_implementations), hooks=sum(map(lambda x: len(x), self.plugin_hooks.values())) @@ -948,7 +966,7 @@ class PluginManager(object): def mark_plugin(self, name, **kwargs): if not name in self.plugins: - self.logger.debug("Trying to mark an unknown plugin {name}".format(**locals())) + self.logger.debug(u"Trying to mark an unknown plugin {name}".format(**locals())) for key, value in kwargs.items(): if value is None: @@ -967,7 +985,7 @@ class PluginManager(object): def load_plugin(self, name, plugin=None, startup=False, initialize_implementation=True): if not name in self.plugins: - self.logger.warn("Trying to load an unknown plugin {name}".format(**locals())) + self.logger.warn(u"Trying to load an unknown plugin {name}".format(**locals())) return if plugin is None: @@ -982,15 +1000,15 @@ class PluginManager(object): self.on_plugin_loaded(name, plugin) plugin.loaded = True - self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals())) + self.logger.debug(u"Loaded plugin {name}: {plugin}".format(**locals())) except PluginLifecycleException as e: raise e except: - self.logger.exception("There was an error loading plugin %s" % name) + self.logger.exception(u"There was an error loading plugin %s" % name) def unload_plugin(self, name): if not name in self.plugins: - self.logger.warn("Trying to unload unknown plugin {name}".format(**locals())) + self.logger.warn(u"Trying to unload unknown plugin {name}".format(**locals())) return plugin = self.plugins[name] @@ -1010,11 +1028,11 @@ class PluginManager(object): plugin.loaded = False - self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals())) + self.logger.debug(u"Unloaded plugin {name}: {plugin}".format(**locals())) except PluginLifecycleException as e: raise e except: - self.logger.exception("There was an error unloading plugin {name}".format(**locals())) + self.logger.exception(u"There was an error unloading plugin {name}".format(**locals())) # make sure the plugin is NOT in the list of enabled plugins but in the list of disabled plugins if name in self.enabled_plugins: @@ -1024,7 +1042,7 @@ class PluginManager(object): def enable_plugin(self, name, plugin=None, initialize_implementation=True, startup=False): if not name in self.disabled_plugins: - self.logger.warn("Tried to enable plugin {name}, however it is not disabled".format(**locals())) + self.logger.warn(u"Tried to enable plugin {name}, however it is not disabled".format(**locals())) return if plugin is None: @@ -1060,13 +1078,13 @@ class PluginManager(object): plugin.implementation.on_plugin_enabled() self.on_plugin_enabled(name, plugin) - self.logger.debug("Enabled plugin {name}: {plugin}".format(**locals())) + self.logger.debug(u"Enabled plugin {name}: {plugin}".format(**locals())) return True def disable_plugin(self, name, plugin=None): if not name in self.enabled_plugins: - self.logger.warn("Tried to disable plugin {name}, however it is not enabled".format(**locals())) + self.logger.warn(u"Tried to disable plugin {name}, however it is not enabled".format(**locals())) return if plugin is None: @@ -1081,7 +1099,7 @@ class PluginManager(object): except PluginLifecycleException as e: raise e except: - self.logger.exception("There was an error while disabling plugin {name}".format(**locals())) + self.logger.exception(u"There was an error while disabling plugin {name}".format(**locals())) return False else: if name in self.enabled_plugins: @@ -1093,7 +1111,7 @@ class PluginManager(object): plugin.implementation.on_plugin_disabled() self.on_plugin_disabled(name, plugin) - self.logger.debug("Disabled plugin {name}: {plugin}".format(**locals())) + self.logger.debug(u"Disabled plugin {name}: {plugin}".format(**locals())) return True @@ -1105,7 +1123,7 @@ class PluginManager(object): try: callback, order = self._get_callback_and_order(definition) except ValueError as e: - self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) + self.logger.warn(u"There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) continue self._plugin_hooks[hook].append((order, name, callback)) @@ -1124,7 +1142,7 @@ class PluginManager(object): try: callback, order = self._get_callback_and_order(definition) except ValueError as e: - self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) + self.logger.warn(u"There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e))) continue try: @@ -1271,7 +1289,7 @@ class PluginManager(object): additional_pre_inits=additional_pre_inits, additional_post_inits=additional_post_inits) - self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations))) + self.logger.info(u"Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations))) def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None): if plugin.implementation is None: @@ -1326,7 +1344,7 @@ class PluginManager(object): try: return_value = factory(name, implementation) except: - self.logger.exception("Exception while executing injection factory %r" % factory) + self.logger.exception(u"Exception while executing injection factory %r" % factory) else: if return_value is not None: if isinstance(return_value, dict): @@ -1350,12 +1368,12 @@ class PluginManager(object): if isinstance(e, PluginLifecycleException): raise e else: - self.logger.exception("Exception while initializing plugin {name}, disabling it".format(**locals())) + self.logger.exception(u"Exception while initializing plugin {name}, disabling it".format(**locals())) return False else: self.on_plugin_implementations_initialized(name, plugin) - self.logger.debug("Initialized plugin mixin implementation for plugin {name}".format(**locals())) + self.logger.debug(u"Initialized plugin mixin implementation for plugin {name}".format(**locals())) return True @@ -1372,7 +1390,7 @@ class PluginManager(object): self.logger.log(level, message) if len(all_plugins) <= 0: - _log("No plugins available") + _log(u"No plugins available") else: formatted_plugins = "\n".join(map(lambda x: "| " + x.long_str(show_bundled=show_bundled, bundled_strs=bundled_str, @@ -1380,9 +1398,9 @@ class PluginManager(object): location_str=location_str, show_enabled=show_enabled, enabled_strs=enabled_str), - sorted(self.plugins.values(), key=lambda x: str(x).lower()))) - _log("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins), - plugins=formatted_plugins)) + sorted(self.plugins.values(), key=lambda x: unicode(x).lower()))) + _log(u"{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins), + plugins=formatted_plugins)) def get_plugin(self, identifier, require_enabled=True): """ @@ -1474,16 +1492,17 @@ class PluginManager(object): try: sorting_value = impl[1].get_sorting_key(sorting_context) except: - self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0])) + self.logger.exception(u"Error while trying to retrieve sorting order for plugin {}".format(impl[0])) if sorting_value is not None: try: - int(sorting_value) + sorting_value = int(sorting_value) except ValueError: - self.logger.warn("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context)) + self.logger.warn(u"The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context)) sorting_value = None - return sorting_value is None, sorting_value, impl[0] + plugin_info = self.get_plugin_info(impl[0], require_enabled=False) + return sorting_value is None, sorting_value, not plugin_info.bundled if plugin_info else True, impl[0] return [impl[1] for impl in sorted(result, key=sort_func)] @@ -1558,7 +1577,7 @@ class PluginManager(object): for client in self.registered_clients: try: client(plugin, data) - except: self.logger.exception("Exception while sending plugin data to client") + except: self.logger.exception(u"Exception while sending plugin data to client") def _sort_hooks(self, hook): self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook], diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index 2bfd5063f..776b13af5 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -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 @@ -1853,8 +1854,9 @@ class SlicerPlugin(OctoPrintPlugin): The human readable name of the slicer. This will be displayed to the user during slicer selection. same_device True if the slicer runs on the same device as OctoPrint, False otherwise. Slicers running on the same - device will not be allowed to slice while a print is running due to performance reasons. Slice requests - against slicers running on the same device will result in an error. + device will not be allowed to slice on systems with less than two CPU cores (or an unknown number) while a + print is running due to performance reasons. Slice requests against slicers running on the same device and + less than two cores will result in an error. progress_report ``True`` if the slicer can report back slicing progress to OctoPrint ``False`` otherwise. source_file_types @@ -1877,6 +1879,21 @@ class SlicerPlugin(OctoPrintPlugin): destination_extensions=["gco", "gcode", "g"] ) + # noinspection PyMethodMayBeStatic + def get_slicer_extension_tree(self): + """ + Fetch additional entries to put into the extension tree for accepted files + + By default, a subtree for ``model`` files with ``stl`` extension is returned. Slicers who want to support + additional/other file types will want to override this. + + For the extension tree format, take a look at the docs of the :ref:`octoprint.filemanager.extension_tree hook `. + + Returns: (dict) a dictionary containing a valid extension subtree. + """ + from octoprint.filemanager import ContentTypeMapping + return dict(model=dict(stl=ContentTypeMapping(["stl"], "application/sla"))) + def get_slicer_profiles(self, profile_path): """ Fetch all :class:`~octoprint.slicing.SlicingProfile` stored for this slicer. @@ -2059,20 +2076,3 @@ class ProgressPlugin(OctoPrintPlugin): :param int progress: Current progress as a value between 0 and 100 """ pass - - -class AppPlugin(OctoPrintPlugin): - """ - Using the :class:`AppPlugin mixin` plugins may register additional :ref:`App session key providers ` - within the system. - - .. deprecated:: 1.2.0 - - Refer to the :ref:`octoprint.accesscontrol.appkey hook ` instead. - - """ - - # noinspection PyMethodMayBeStatic - def get_additional_apps(self): - return [] - diff --git a/src/octoprint/plugins/__init__.py b/src/octoprint/plugins/__init__.py index 1b0510c60..092cd3e34 100644 --- a/src/octoprint/plugins/__init__.py +++ b/src/octoprint/plugins/__init__.py @@ -1 +1,2 @@ -# make our plugins testable +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 8900c5d7a..467aac652 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms import octoprint.plugin from octoprint.server import user_permission +from octoprint.events import Events import flask from flask_babel import gettext @@ -34,17 +35,28 @@ class Prompt(object): class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, + octoprint.plugin.EventHandlerPlugin, octoprint.plugin.SettingsPlugin, octoprint.plugin.SimpleApiPlugin, octoprint.plugin.TemplatePlugin): + COMMAND = "M876" + CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT" + # noinspection PyMissingConstructor def __init__(self): self._prompt = None - self._selection_command = None + self._enable = "detected" + self._command = None + self._enable_emergency_sending = False + self._enable_signal_support = False + self._cap_prompt_support = False def initialize(self): - self._selection_command = self._settings.get([b"selection_command"]) + self._enable = self._settings.get([b"enable"]) + self._command = self._settings.get([b"command"]) + self._enable_emergency_sending = self._settings.get_boolean([b"enable_emergency_sending"]) + self._enable_signal_support = self._settings.get_boolean([b"enable_signal_support"]) #~ AssetPlugin @@ -52,14 +64,26 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, return dict(js=["js/action_command_prompt.js"], clientjs=["clientjs/action_command_prompt.js"]) + #~ EventHandlerPlugin + + def on_event(self, event, payload): + if event == Events.CONNECTED and self._enable == "always" and self._enable_signal_support: + self._printer.commands(["{command} P1".format(command=self._command)]) + #~ SettingsPlugin def get_settings_defaults(self): - return dict(selection_command=None) + return dict(enable="detected", + command=self.COMMAND, + enable_emergency_sending=True, + enable_signal_support=True) def on_settings_save(self, data): octoprint.plugin.SettingsPlugin.on_settings_save(self, data) - self._selection_command = self._settings.get([b"selection_command"]) + self._enable = self._settings.get([b"enable"]) + self._command = self._settings.get([b"command"]) + self._enable_emergency_sending = self._settings.get_boolean([b"enable_emergency_sending"]) + self._enable_signal_support = self._settings.get_boolean([b"enable_signal_support"]) #~ SimpleApiPlugin @@ -99,10 +123,6 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, if not action.startswith(b"prompt_"): return - if self._selection_command is None: - self._logger.info("Got a prompt command from the printer but no selection command is defined") - return - parts = action.split(None, 1) if len(parts) == 1: action = parts[0] @@ -138,21 +158,55 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, self._close_prompt() self._prompt = None + #~ queuing handling + + def gcode_queuing_handler(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs): + if gcode != self._command: + return + + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support) or not self._enable_emergency_sending: + return + + if not "S" in cmd: + # we only force-send M876 Sx + return + + # noinspection PyProtectedMember + return comm_instance._emergency_force_send(cmd, u"Force-sending {} to the printer".format(self._command), gcode=gcode) + + #~ capability reporting + + def firmware_capability_handler(self, comm_instance, capability, enabled, already_defined, *args, **kwargs): + if capability == self.CAP_PROMPT_SUPPORT and enabled: + self._cap_prompt_support = True + if self._enable == "detected" and self._enable_signal_support: + self._printer.commands(["{command} P1".format(command=self._command)]) + #~ prompt handling def _show_prompt(self): + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): + return + self._prompt.activate() self._plugin_manager.send_plugin_message(self._identifier, dict(action="show", text=self._prompt.text, choices=self._prompt.choices)) def _close_prompt(self): + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): + return + self._prompt = None self._plugin_manager.send_plugin_message(self._identifier, dict(action="close")) def _answer_prompt(self, choice): + if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support): + return + self._close_prompt() - self._printer.commands([self._selection_command.format(choice=choice)]) + self._printer.commands(["{command} S{choice}".format(command=self._command, + choice=choice)]) __plugin_name__ = "Action Command Prompt Support" @@ -163,5 +217,7 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin your printer wil __plugin_license__ = "AGPLv3" __plugin_implementation__ = ActionCommandPromptPlugin() __plugin_hooks__ = { - b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler + b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, + b"octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler, + b"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler } diff --git a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 index a30e7f9b8..df45ff760 100644 --- a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 +++ b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 @@ -2,10 +2,43 @@
- +
- -
{{ _('Use this to define the command to tell the printer about the selection. OctoPrint will replace {choice} with the index of the selected choice. E.g. M876 S{choice} will become M123 S1') }}
+ + + +
+
+
+ +
+
+ +
+ +
{{ _('Use this to define the dialog command. Default is M876. You normally should not have to change this.') }}
+
+
+
+
+ +
+
+
+
+ +
+
diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 8ff8e289a..07799eb25 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -22,7 +22,7 @@ from collections import OrderedDict from octoprint.server import admin_permission from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag -from octoprint.util import utmify +from octoprint.util import utmify, monotonic_time from flask_babel import gettext from octoprint import __version__ as OCTOPRINT_VERSION @@ -351,10 +351,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(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start)) + self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], monotonic_time() - start)) except Exception as e: self._logger.exception( u"Could not fetch channel {} from {}: {}".format(key, config["url"], str(e))) diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index 7de100e79..310638360 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -15,6 +15,7 @@ import octoprint.plugin from octoprint.settings import valid_boolean_trues from octoprint.server.util.flask import restricted_access, no_firstrun_access from octoprint.server import NO_CONTENT, current_user, admin_permission +from octoprint.users import DummyUser from octoprint.util import atomic_write, monotonic_time, ResettableTimer @@ -343,7 +344,10 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, with self._keys_lock: for user_id, data in self._keys.items(): if 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 == "dummy": + return DummyUser() return None def _api_keys_for_user(self, user_id): diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index b00f5faf2..14cacaf08 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -46,6 +46,14 @@ import traceback UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json" +BACKUP_FILE_PREFIX = "octoprint-backup" + +BACKUP_DATE_TIME_FMT = "%Y%m%d-%H%M%S" + +def build_backup_filename(): + return "{}-{}.zip".format(BACKUP_FILE_PREFIX, + time.strftime(BACKUP_DATE_TIME_FMT)) + class BackupPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.TemplatePlugin, @@ -60,7 +68,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, self._in_progress = [] self._in_progress_lock = threading.RLock() - ##~~ StarupPlugin + ##~~ StartupPlugin def on_after_startup(self): self._clean_dir_backup(self._settings._basedir, @@ -74,6 +82,11 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, css=["css/backup.css"], less=["less/backup.less"]) + ##~~ TemplatePlugin + + def get_template_configs(self): + return [dict(type="settings", name=gettext(u"Backup & Restore"))] + ##~~ BlueprintPlugin @octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"]) @@ -117,7 +130,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, @admin_permission.require(403) @restricted_access def create_backup(self): - backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S")) + backup_file = build_backup_filename() data = flask.request.json exclude = data.get("exclude", []) @@ -330,7 +343,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, Creates a new backup. """ - backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S")) + backup_file = build_backup_filename() settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings) datafolder = os.path.join(settings.getBaseFolder("data"), "backup") @@ -514,11 +527,17 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, thread.start() @classmethod - def _get_disk_size(cls, path): + def _get_disk_size(cls, path, ignored=None): + if ignored is None: + ignored = [] + + if path in ignored: + return 0 + total = 0 for entry in scandir(path): if entry.is_dir(): - total += cls._get_disk_size(entry.path) + total += cls._get_disk_size(entry.path, ignored=ignored) elif entry.is_file(): total += entry.stat().st_size return total @@ -595,24 +614,38 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, on_backup_start=None, on_backup_done=None, on_backup_error=None): + exclude_by_default = ("generated", "logs", "watched",) + try: if exclude is None: exclude = [] + if "timelapse" in exclude: + exclude.append("timelapse_tmp") + configfile = settings._configfile basedir = settings._basedir temporary_path = os.path.join(datafolder, ".{}".format(name)) final_path = os.path.join(datafolder, name) - size = cls._get_disk_size(basedir) - if not cls._free_space(os.path.dirname(temporary_path), size): - raise InsufficientSpace() - own_folder = datafolder defaults = [os.path.join(basedir, "config.yaml"),] + \ [os.path.join(basedir, folder) for folder in default_settings["folder"].keys()] + # check how much many bytes we are about to backup + size = os.stat(configfile).st_size + for folder in default_settings["folder"].keys(): + if folder in exclude or folder in exclude_by_default: + continue + size += cls._get_disk_size(settings.global_get_basefolder(folder), + ignored=[own_folder,]) + size += cls._get_disk_size(basedir, ignored=defaults + [own_folder,]) + + # since we can't know the compression ratio beforehand, we assume we need the same amount of space + if not cls._free_space(os.path.dirname(temporary_path), size): + raise InsufficientSpace() + compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED if callable(on_backup_start): @@ -642,10 +675,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, # backup configured folder paths for folder in default_settings["folder"].keys(): - if folder in exclude: - continue - - if folder in ("generated", "logs", "watched",): + if folder in exclude or folder in exclude_by_default: continue add_to_zip(settings.global_get_basefolder(folder), @@ -670,7 +700,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, if len(plugins): zip.writestr("plugin_list.json", json.dumps(plugins)) - os.rename(temporary_path, final_path) + shutil.move(temporary_path, final_path) if callable(on_backup_done): on_backup_done(name, final_path, exclude) @@ -779,8 +809,11 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, on_log_progress(u"Unpacked") # install available plugins - with codecs.open(os.path.join(temp, "plugin_list.json"), "r") as f: - plugins = json.load(f) + plugins = [] + plugin_list_file = os.path.join(temp, "plugin_list.json") + if os.path.exists(plugin_list_file): + with codecs.open(plugin_list_file, "r") as f: + plugins = json.load(f) known_plugins = [] unknown_plugins = [] @@ -820,18 +853,18 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, if callable(on_log_progress): on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup)) - os.rename(basedir, basedir_backup) + shutil.move(basedir, basedir_backup) try: if callable(on_log_progress): on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir)) - os.rename(basedir_extracted, basedir) + shutil.move(basedir_extracted, basedir) except: if callable(on_log_error): on_log_error(u"Error while restoring config data", exc_info=sys.exc_info()) on_log_error(u"Rolling back old config data") - os.rename(basedir_backup, basedir) + shutil.move(basedir_backup, basedir) if callable(on_restore_failed): on_restore_failed(path) @@ -911,7 +944,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, class InsufficientSpace(Exception): pass -__plugin_name__ = gettext(u"Backup & Restore") +__plugin_name__ = u"Backup & Restore" __plugin_author__ = u"Gina Häußge" __plugin_description__ = u"Backup & restore your OctoPrint settings and data" __plugin_disabling_discouraged__ = gettext(u"Without this plugin you will no longer be able to backup " diff --git a/src/octoprint/plugins/corewizard/static/js/corewizard.js b/src/octoprint/plugins/corewizard/static/js/corewizard.js index 1c8f41b7d..5f3dfa7d0 100644 --- a/src/octoprint/plugins/corewizard/static/js/corewizard.js +++ b/src/octoprint/plugins/corewizard/static/js/corewizard.js @@ -170,10 +170,6 @@ $(function() { return false; }; - self.onWizardPreventSettingsRefreshDialog = function() { - return self.active; - }; - self.onWizardDetails = function(response) { self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.onlinecheck && response.corewizard.details.onlinecheck.required; }; @@ -252,10 +248,6 @@ $(function() { return false; }; - self.onWizardPreventSettingsRefreshDialog = function() { - return self.active; - }; - self.onWizardDetails = function(response) { self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.pluginblacklist && response.corewizard.details.pluginblacklist.required; }; diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py deleted file mode 100644 index c78cfc0d0..000000000 --- a/src/octoprint/plugins/cura/__init__.py +++ /dev/null @@ -1,532 +0,0 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function - -__author__ = "Gina Häußge " -__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" -__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" - -import logging -import logging.handlers -import os -import flask -import math - -import octoprint.plugin -import octoprint.util -import octoprint.slicing -import octoprint.settings - -from octoprint.util.paths import normalize as normalize_path -from octoprint.util import to_unicode - -from .profile import Profile -from .profile import GcodeFlavors -from .profile import parse_gcode_flavor - -class CuraPlugin(octoprint.plugin.SlicerPlugin, - octoprint.plugin.SettingsPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.BlueprintPlugin, - octoprint.plugin.StartupPlugin, - octoprint.plugin.WizardPlugin): - - # noinspection PyMissingConstructor - def __init__(self): - self._logger = logging.getLogger("octoprint.plugins.cura") - self._cura_logger = logging.getLogger("octoprint.plugins.cura.engine") - - # setup job tracking across threads - import threading - self._slicing_commands = dict() - self._cancelled_jobs = [] - self._job_mutex = threading.Lock() - - def _is_engine_configured(self, cura_engine=None): - if cura_engine is None: - cura_engine = normalize_path(self._settings.get(["cura_engine"])) - return cura_engine is not None and os.path.isfile(cura_engine) and os.access(cura_engine, os.X_OK) - - def _is_profile_available(self): - return bool(self._slicing_manager.all_profiles("cura", require_configured=False)) - - ##~~ TemplatePlugin API - - def get_template_vars(self): - return dict( - homepage=__plugin_url__ - ) - - ##~~ WizardPlugin API - - def is_wizard_required(self): - return not self._is_engine_configured() or not self._is_profile_available() - - def get_wizard_details(self): - return dict( - engine=self._is_engine_configured(), - profile=self._is_profile_available() - ) - - ##~~ StartupPlugin API - - def on_startup(self, host, port): - # setup our custom logger - from octoprint.logging.handlers import CleaningTimedRotatingFileHandler - cura_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="engine"), when="D", backupCount=3) - cura_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) - cura_logging_handler.setLevel(logging.DEBUG) - - self._cura_logger.addHandler(cura_logging_handler) - self._cura_logger.setLevel(logging.DEBUG if self._settings.get_boolean(["debug_logging"]) else logging.CRITICAL) - self._cura_logger.propagate = False - - engine = self._settings.get(["cura_engine"]) - if not self._is_engine_configured(cura_engine=engine): - self._logger.info(u"Path to CuraEngine has not been configured or does not exist (currently set to %r), " - u"Cura will not be selectable for slicing" % engine) - - ##~~ BlueprintPlugin API - - @octoprint.plugin.BlueprintPlugin.route("/import", methods=["POST"]) - def import_cura_profile(self): - import datetime - - input_name = "file" - input_upload_name = input_name + "." + self._settings.global_get(["server", "uploads", "nameSuffix"]) - input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"]) - - if input_upload_name in flask.request.values and input_upload_path in flask.request.values: - filename = flask.request.values[input_upload_name] - try: - profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path]) - except Exception as e: - self._logger.exception(u"Error while converting the imported profile") - return flask.make_response(u"Something went wrong while converting imported profile: {message}".format(message=str(e)), 500) - - else: - self._logger.warn(u"No profile file included for importing, aborting") - return flask.make_response(u"No file included", 400) - - if profile_dict is None: - self._logger.warn(u"Could not convert profile, aborting") - return flask.make_response(u"Could not convert Cura profile", 400) - - name, _ = os.path.splitext(filename) - - # default values for name, display name and description - profile_name = _sanitize_name(name) - profile_display_name = name - profile_description = u"Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now())) - profile_allow_overwrite = False - profile_make_default = False - - # overrides - from octoprint.server.api import valid_boolean_trues - if "name" in flask.request.values: - profile_name = flask.request.values["name"] - if "displayName" in flask.request.values: - profile_display_name = flask.request.values["displayName"] - if "description" in flask.request.values: - profile_description = flask.request.values["description"] - if "allowOverwrite" in flask.request.values: - profile_allow_overwrite = flask.request.values["allowOverwrite"] in valid_boolean_trues - if "default" in flask.request.values: - profile_make_default = flask.request.values["default"] in valid_boolean_trues - - try: - self._slicing_manager.save_profile("cura", - profile_name, - profile_dict, - allow_overwrite=profile_allow_overwrite, - display_name=profile_display_name, - description=profile_description) - except octoprint.slicing.ProfileAlreadyExists: - self._logger.warn(u"Profile {profile_name} already exists, aborting".format(**locals())) - return flask.make_response(u"A profile named {profile_name} already exists for slicer cura".format(**locals()), 409) - - if profile_make_default: - try: - self._slicing_manager.set_default_profile("cura", profile_name) - except octoprint.slicing.UnknownProfile: - self._logger.warn(u"Profile {profile_name} could not be set as default, aborting".format(**locals())) - return flask.make_response(u"The profile {profile_name} for slicer cura could not be set as default".format(**locals()), 500) - - result = dict( - resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True), - name=profile_name, - displayName=profile_display_name, - description=profile_description - ) - r = flask.make_response(flask.jsonify(result), 201) - r.headers["Location"] = result["resource"] - return r - - ##~~ AssetPlugin API - - def get_assets(self): - return { - "js": ["js/cura.js"], - "less": ["less/cura.less"], - "css": ["css/cura.css"] - } - - ##~~ SettingsPlugin API - - def on_settings_save(self, data): - old_engine = self._settings.get(["cura_engine"]) - old_debug_logging = self._settings.get_boolean(["debug_logging"]) - - octoprint.plugin.SettingsPlugin.on_settings_save(self, data) - - new_engine = self._settings.get(["cura_engine"]) - new_debug_logging = self._settings.get_boolean(["debug_logging"]) - - if old_engine != new_engine and not self._is_engine_configured(new_engine): - self._logger.info(u"Path to CuraEngine has not been configured or does not exist (currently set to %r), " - u"Cura will not be selectable for slicing" % new_engine) - - if old_debug_logging != new_debug_logging: - if new_debug_logging: - self._cura_logger.setLevel(logging.DEBUG) - else: - self._cura_logger.setLevel(logging.CRITICAL) - - def get_settings_defaults(self): - return dict( - cura_engine=None, - default_profile=None, - debug_logging=False - ) - - ##~~ SlicerPlugin API - - def is_slicer_configured(self): - cura_engine = normalize_path(self._settings.get(["cura_engine"])) - return self._is_engine_configured(cura_engine=cura_engine) - - def get_slicer_properties(self): - return dict( - type="cura", - name="CuraEngine", - same_device=True, - progress_report=True, - source_file_types=["stl"], - destination_extensions=["gco", "gcode", "g"] - ) - - def get_slicer_default_profile(self): - path = self._settings.get(["default_profile"]) - if not path: - path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "profiles", "default.profile.yaml") - return self.get_slicer_profile(path) - - def get_slicer_profile(self, path): - profile_dict = self._load_profile(path) - - display_name = None - description = None - if "_display_name" in profile_dict: - display_name = profile_dict["_display_name"] - del profile_dict["_display_name"] - if "_description" in profile_dict: - description = profile_dict["_description"] - del profile_dict["_description"] - - properties = self.get_slicer_properties() - return octoprint.slicing.SlicingProfile(properties["type"], "unknown", profile_dict, display_name=display_name, description=description) - - def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None): - new_profile = Profile.merge_profile(profile.data, overrides=overrides) - - if profile.display_name is not None: - new_profile["_display_name"] = profile.display_name - if profile.description is not None: - new_profile["_description"] = profile.description - - self._save_profile(path, new_profile, allow_overwrite=allow_overwrite) - - def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, - on_progress=None, on_progress_args=None, on_progress_kwargs=None): - try: - with self._job_mutex: - if not profile_path: - profile_path = self._settings.get(["default_profile"]) - if not machinecode_path: - path, _ = os.path.splitext(model_path) - machinecode_path = path + ".gco" - - if position and isinstance(position, dict) and "x" in position and "y" in position: - pos_x = position["x"] - pos_y = position["y"] - else: - pos_x = None - pos_y = None - - if on_progress: - if not on_progress_args: - on_progress_args = () - if not on_progress_kwargs: - on_progress_kwargs = dict() - - self._cura_logger.info(u"### Slicing {} to {} using profile stored at {}" - .format(to_unicode(model_path, errors="replace"), - to_unicode(machinecode_path, errors="replace"), - to_unicode(profile_path, errors="replace"))) - - executable = normalize_path(self._settings.get(["cura_engine"])) - if not executable: - return False, u"Path to CuraEngine is not configured " - - working_dir = os.path.dirname(executable) - - slicing_profile = Profile(self._load_profile(profile_path), printer_profile, pos_x, pos_y) - - # NOTE: We can assume an extruder count of 1 here since the only way we currently - # support dual extrusion in this implementation is by using the second extruder for support (which - # the engine conversion will automatically detect and adapt accordingly). - # - # We currently do only support STL files as sliceables, which by default can only contain one mesh, - # so no risk of having to slice multi-objects at the moment, which would necessitate a full analysis - # of the objects to slice to determine amount of needed extruders to use here. If we ever decide to - # also support dual extrusion slicing (including composition from multiple STLs or support for OBJ or - # AMF files and the like), this code needs to be adapted! - # - # The extruder count is needed to decide which start/end gcode will be used from the Cura profile. - # Stock Cura implementation counts the number of objects in the scene for this (and also takes a look - # at the support usage, like the engine conversion here does). We only ever have one object. - engine_settings = self._convert_to_engine(profile_path, printer_profile, - pos_x=pos_x, pos_y=pos_y, - used_extruders=1) - - # Start building the argument list for the CuraEngine command execution - args = [executable, '-v', '-p'] - - # Add the settings (sorted alphabetically) to the command - for k, v in sorted(engine_settings.items(), key=lambda s: s[0]): - args += ["-s", "%s=%s" % (k, str(v))] - args += ["-o", machinecode_path, model_path] - - self._logger.info(u"Running {!r} in {}".format(u" ".join(map(lambda x: to_unicode(x, errors="replace"), - args)), - working_dir)) - - import sarge - p = sarge.run(args, cwd=working_dir, async_=True, stdout=sarge.Capture(), stderr=sarge.Capture()) - p.wait_events() - self._slicing_commands[machinecode_path] = p.commands[0] - - try: - layer_count = None - step_factor = dict( - inset=0, - skin=1, - export=2 - ) - analysis = None - while p.returncode is None: - line = p.stderr.readline(timeout=0.5) - if not line: - p.commands[0].poll() - continue - - line = to_unicode(line, errors="replace") - self._cura_logger.debug(line.strip()) - - if on_progress is not None: - # The Cura slicing process has three individual steps, each consisting of substeps: - # - # - inset - # - skin - # - export - # - # So each layer will be processed three times, once for each step, resulting in a total amount of - # substeps of 3 * . - # - # The CuraEngine reports the calculated layer count and the continuous progress on stderr. - # The layer count gets reported right at the beginning in a line of the format: - # - # Layer count: - # - # The individual progress per each of the three steps gets reported on stderr in a line of - # the format: - # - # Progress::: - # - # Thus, for determining the overall progress the following formula applies: - # - # progress = * + / * 3 - # - # with being 0 for "inset", 1 for "skin" and 2 for "export". - - if line.startswith(u"Layer count:") and layer_count is None: - try: - layer_count = float(line[len(u"Layer count:"):].strip()) - except: - pass - - elif line.startswith(u"Progress:"): - split_line = line[len(u"Progress:"):].strip().split(":") - if len(split_line) == 3: - step, current_layer, _ = split_line - try: - current_layer = float(current_layer) - except: - pass - else: - if not step in step_factor: - continue - on_progress_kwargs["_progress"] = (step_factor[step] * layer_count + current_layer) / (layer_count * 3) - on_progress(*on_progress_args, **on_progress_kwargs) - - elif line.startswith(u"Print time:"): - try: - print_time = int(line[len(u"Print time:"):].strip()) - if analysis is None: - analysis = dict() - analysis["estimatedPrintTime"] = print_time - except: - pass - - # Get the filament usage - - elif line.startswith(u"Filament:") or line.startswith(u"Filament2:"): - if line.startswith(u"Filament:"): - filament_str = line[len(u"Filament:"):].strip() - tool_key = "tool0" - else: - filament_str = line[len(u"Filament2:"):].strip() - tool_key = "tool1" - - try: - filament = int(filament_str) - - if analysis is None: - analysis = dict() - if not "filament" in analysis: - analysis["filament"] = dict() - if not tool_key in analysis["filament"]: - analysis["filament"][tool_key] = dict() - - if slicing_profile.get_float("filament_diameter") is not None: - if slicing_profile.get("gcode_flavor") == GcodeFlavors.ULTIGCODE or slicing_profile.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME: - analysis["filament"][tool_key] = _get_usage_from_volume(filament, slicing_profile.get_float("filament_diameter")) - else: - analysis["filament"][tool_key] = _get_usage_from_length(filament, slicing_profile.get_float("filament_diameter")) - - except: - pass - finally: - p.close() - - with self._job_mutex: - if machinecode_path in self._cancelled_jobs: - self._cura_logger.info(u"### Cancelled") - raise octoprint.slicing.SlicingCancelled() - - self._cura_logger.info(u"### Finished, returncode %d" % p.returncode) - if p.returncode == 0: - return True, dict(analysis=analysis) - else: - self._logger.warn(u"Could not slice via Cura, got return code %r" % p.returncode) - return False, "Got returncode %r" % p.returncode - - except octoprint.slicing.SlicingCancelled as e: - raise e - except: - self._logger.exception(u"Could not slice via Cura, got an unknown error") - return False, "Unknown error, please consult the log file" - - finally: - with self._job_mutex: - if machinecode_path in self._cancelled_jobs: - self._cancelled_jobs.remove(machinecode_path) - if machinecode_path in self._slicing_commands: - del self._slicing_commands[machinecode_path] - - self._cura_logger.info("-" * 40) - - def cancel_slicing(self, machinecode_path): - with self._job_mutex: - if machinecode_path in self._slicing_commands: - self._cancelled_jobs.append(machinecode_path) - command = self._slicing_commands[machinecode_path] - if command is not None: - command.terminate() - self._logger.info(u"Cancelled slicing of {}" - .format(to_unicode(machinecode_path, errors="replace"))) - - def _load_profile(self, path): - import yaml - profile_dict = dict() - with open(path, "r") as f: - try: - profile_dict = yaml.safe_load(f) - except: - raise IOError(u"Couldn't read profile from {path}".format(path=path)) - - if "gcode_flavor" in profile_dict and not isinstance(profile_dict["gcode_flavor"], (list, tuple)): - profile_dict["gcode_flavor"] = parse_gcode_flavor(profile_dict["gcode_flavor"]) - self._save_profile(path, profile_dict) - - return profile_dict - - def _save_profile(self, path, profile, allow_overwrite=True): - import yaml - with octoprint.util.atomic_write(path, "wb", max_permissions=0o666) as f: - yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True) - - def _convert_to_engine(self, profile_path, printer_profile, pos_x=None, pos_y=None, used_extruders=1): - profile = Profile(self._load_profile(profile_path), printer_profile, pos_x, pos_y) - return profile.convert_to_engine(used_extruders=used_extruders) - -def _sanitize_name(name): - if name is None: - return None - - if "/" in name or "\\" in name: - raise ValueError(u"name must not contain / or \\") - - import string - valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits) - sanitized_name = ''.join(c for c in name if c in valid_chars) - sanitized_name = sanitized_name.replace(" ", "_") - return sanitized_name.lower() - -def _get_usage_from_volume(filament_volume, filament_diameter): - - # filament_volume is expressed in mm^3 - # usage["volume"] is in cm^3 and usage["length"] is in mm - - usage = dict() - usage["volume"] = filament_volume / 1000.0 - - radius_in_mm = filament_diameter / 2.0 - usage["length"] = filament_volume / (math.pi * radius_in_mm * radius_in_mm) - - return usage - -def _get_usage_from_length(filament_length, filament_diameter): - - # filament_length is expressed in mm - # usage["volume"] is in cm^3 and usage["length"] is in mm - - usage = dict() - usage["length"] = filament_length - - radius_in_cm = (filament_diameter / 10.0) / 2.0 - length_in_cm = filament_length / 10.0 - usage["volume"] = length_in_cm * math.pi * radius_in_cm * radius_in_cm - - return usage - - -__plugin_name__ = "CuraEngine (<= 15.04)" -__plugin_author__ = "Gina Häußge" -__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/cura.html" -__plugin_description__ = "Adds support for slicing via CuraEngine versions up to and including version 15.04 from within OctoPrint" -__plugin_license__ = "AGPLv3" -__plugin_implementation__ = CuraPlugin() - - - diff --git a/src/octoprint/plugins/cura/profile.py b/src/octoprint/plugins/cura/profile.py deleted file mode 100644 index ac60d7074..000000000 --- a/src/octoprint/plugins/cura/profile.py +++ /dev/null @@ -1,1033 +0,0 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function - -__author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' -__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" - - -import re - -# noinspection PyCompatibility -from builtins import range -# noinspection PyCompatibility -from past.builtins import basestring - -class SupportLocationTypes(object): - NONE = "none" - TOUCHING_BUILDPLATE = "buildplate" - EVERYWHERE = "everywhere" - -class SupportDualTypes(object): - BOTH = "both" - FIRST = "first" - SECOND = "second" - -class SupportTypes(object): - GRID = "grid" - LINES = "lines" - -class PlatformAdhesionTypes(object): - NONE = "none" - BRIM = "brim" - RAFT = "raft" - -class MachineShapeTypes(object): - SQUARE = "square" - CIRCULAR = "circular" - -class RetractionCombingTypes(object): - OFF = "off" - ALL = "all" - NO_SKIN = "no skin" - -class GcodeFlavors(object): - REPRAP = (0, "reprap") - ULTIGCODE = (1, "ultigcode") - MAKERBOT = (2, "makerbot") - BFB = (3, "bfb") - MACH3 = (4, "mach3") - REPRAP_VOLUME = (5, "reprap_volume") - - -defaults = dict( - layer_height=0.1, - wall_thickness=0.8, - solid_layer_thickness=0.6, - print_temperature=[220, 0, 0, 0], - print_bed_temperature=0, - platform_adhesion=PlatformAdhesionTypes.NONE, - filament_diameter=[2.85, 0, 0, 0], - filament_flow=100.0, - bottom_thickness=0.3, - first_layer_width_factor=100.0, - object_sink=0.0, - - fill_density=20, - solid_top=True, - solid_bottom=True, - fill_overlap=15, - perimeter_before_infill=False, - - # speeds - print_speed=50.0, - travel_speed=150.0, - bottom_layer_speed=20.0, - infill_speed=0.0, - solidarea_speed=0.0, - outer_shell_speed=0.0, - inner_shell_speed=0.0, - - # dual extrusion - overlap_dual=0.15, - wipe_tower=False, - wipe_tower_volume=15, - ooze_shield=False, - - # retraction - retraction_enable=True, - retraction_speed=40.0, - retraction_amount=4.5, - retraction_dual_amount=16.5, - retraction_min_travel=1.5, - retraction_combing=True, - retraction_minimal_extrusion=0.02, - retraction_hop=0.0, - - # cooling - cool_min_layer_time=5, - fan_enabled=True, - fan_full_height=0.5, - fan_speed=100, - fan_speed_max=100, - cool_min_feedrate=10, - cool_head_lift=False, - - # support - support=SupportLocationTypes.NONE, - support_type=SupportTypes.GRID, - support_angle=60.0, - support_fill_rate=15, - support_xy_distance=0.7, - support_z_distance=0.15, - support_dual_extrusion=SupportDualTypes.BOTH, - - # platform adhesion - skirt_line_count=1, - skirt_gap=3.0, - skirt_minimal_length=150.0, - brim_line_count=20, - raft_margin=5.0, - raft_line_spacing=3.0, - raft_base_thickness=0.3, - raft_base_linewidth=1.0, - raft_interface_thickness=0.27, - raft_interface_linewidth=0.4, - raft_airgap_all=0.0, - raft_airgap=0.22, - raft_surface_layers=2, - raft_surface_thickness=0.27, - raft_surface_linewidth=0.4, - - # repairing - fix_horrible_union_all_type_a=True, - fix_horrible_union_all_type_b=False, - fix_horrible_use_open_bits=False, - fix_horrible_extensive_stitching=False, - - # extras - spiralize=False, - follow_surface=False, - - machine_width=205, - machine_depth=205, - machine_center_is_zero=False, - has_heated_bed=False, - gcode_flavor=GcodeFlavors.REPRAP, - extruder_amount=1, - steps_per_e=0, - start_gcode=[ - # 1 extruder - """;Sliced at: {day} {date} {time} -;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} -;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line -;M109 S{print_temperature} ;Uncomment to add your own temperature line -G21 ;metric values -G90 ;absolute positioning -M82 ;set extruder to absolute mode -M107 ;start with the fan off - -G28 X0 Y0 ;move X/Y to min endstops -G28 Z0 ;move Z to min endstops - -G1 Z15.0 F{travel_speed} ;move the platform down 15mm - -G92 E0 ;zero the extruded length -G1 F200 E3 ;extrude 3mm of feed stock -G92 E0 ;zero the extruded length again -G1 F{travel_speed} -;Put printing message on LCD screen -M117 Printing... -""", - # 2 extruders - """;Sliced at: {day} {date} {time} -;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} -;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line -;M104 S{print_temperature} ;Uncomment to add your own temperature line -;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line -;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line -G21 ;metric values -G90 ;absolute positioning -M107 ;start with the fan off - -G28 X0 Y0 ;move X/Y to min endstops -G28 Z0 ;move Z to min endstops - -G1 Z15.0 F{travel_speed} ;move the platform down 15mm - -T1 ;Switch to the 2nd extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F200 E-{retraction_dual_amount} - -T0 ;Switch to the first extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F{travel_speed} -;Put printing message on LCD screen -M117 Printing... -""", - # 3 extruders - """;Sliced at: {day} {date} {time} -;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} -;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line -;M104 S{print_temperature} ;Uncomment to add your own temperature line -;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line -;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line -G21 ;metric values -G90 ;absolute positioning -M107 ;start with the fan off - -G28 X0 Y0 ;move X/Y to min endstops -G28 Z0 ;move Z to min endstops - -G1 Z15.0 F{travel_speed} ;move the platform down 15mm - -T2 ;Switch to the 2nd extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F200 E-{retraction_dual_amount} - -T1 ;Switch to the 2nd extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F200 E-{retraction_dual_amount} - -T0 ;Switch to the first extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F{travel_speed} -;Put printing message on LCD screen -M117 Printing... -""", - # 4 extruders - """;Sliced at: {day} {date} {time} -;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} -;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line -;M104 S{print_temperature} ;Uncomment to add your own temperature line -;M109 T2 S{print_temperature2} ;Uncomment to add your own temperature line -;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line -;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line -G21 ;metric values -G90 ;absolute positioning -M107 ;start with the fan off - -G28 X0 Y0 ;move X/Y to min endstops -G28 Z0 ;move Z to min endstops - -G1 Z15.0 F{travel_speed} ;move the platform down 15mm - -T3 ;Switch to the 4th extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F200 E-{retraction_dual_amount} - -T2 ;Switch to the 3th extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F200 E-{retraction_dual_amount} - -T1 ;Switch to the 2nd extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F200 E-{retraction_dual_amount} - -T0 ;Switch to the first extruder -G92 E0 ;zero the extruded length -G1 F200 E10 ;extrude 10mm of feed stock -G92 E0 ;zero the extruded length again -G1 F{travel_speed} -;Put printing message on LCD screen -M117 Printing... -""" - ], - end_gcode=[ - # 1 extruder - """;End GCode -M104 S0 ;extruder heater off -M140 S0 ;heated bed heater off (if you have it) - -G91 ;relative positioning -G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure -G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more -G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way - -M84 ;steppers off -G90 ;absolute positioning -;{profile_string} -""", - # 2 extruders - """;End GCode -M104 T0 S0 ;extruder heater off -M104 T1 S0 ;extruder heater off -M140 S0 ;heated bed heater off (if you have it) - -G91 ;relative positioning -G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure -G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more -G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way - -M84 ;steppers off -G90 ;absolute positioning -;{profile_string} -""", - # 3 extruders - """;End GCode -M104 T0 S0 ;extruder heater off -M104 T1 S0 ;extruder heater off -M104 T2 S0 ;extruder heater off -M140 S0 ;heated bed heater off (if you have it) - -G91 ;relative positioning -G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure -G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more -G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way - -M84 ;steppers off -G90 ;absolute positioning -;{profile_string} -""", - # 4 extruders - """;End GCode -M104 T0 S0 ;extruder heater off -M104 T1 S0 ;extruder heater off -M104 T2 S0 ;extruder heater off -M104 T3 S0 ;extruder heater off -M140 S0 ;heated bed heater off (if you have it) - -G91 ;relative positioning -G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure -G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more -G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way - -M84 ;steppers off -G90 ;absolute positioning -;{profile_string} -""" - ], - preSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders. -;This code is added before the T(n) -""", - postSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders. -;This code is added after the T(n) -""" -) - - -class Profile(object): - - regex_extruder_offset = re.compile("extruder_offset_([xy])(\d)") - regex_filament_diameter = re.compile("filament_diameter(\d?)") - regex_print_temperature = re.compile("print_temperature(\d?)") - regex_strip_comments = re.compile(";.*$", flags=re.MULTILINE) - - regex_broken_replacements = re.compile("\?([a-zA-Z0-9_]*)\?") - - @classmethod - def from_cura_ini(cls, path): - import logging - logger = logging.getLogger("octoprint.plugin.cura.profile") - - import os - if not os.path.exists(path) or not os.path.isfile(path): - logger.warn("Path {path} does not exist or is not a file, cannot import".format(**locals())) - return None - - import ConfigParser - config = ConfigParser.ConfigParser() - try: - config.read(path) - except: - logger.exception("Error while reading profile INI file from {path}".format(**locals())) - return None - - arrayified_options = ["print_temperature", "filament_diameter", "start.gcode", "end.gcode"] - translated_options = dict( - inset0_speed="outer_shell_speed", - insetx_speed="inner_shell_speed", - layer0_width_factor="first_layer_width_factor", - simple_mode="follow_surface", - ) - translated_options["start.gcode"] = "start_gcode" - translated_options["end.gcode"] = "end_gcode" - value_conversions = dict( - platform_adhesion={ - "None": PlatformAdhesionTypes.NONE, - "Brim": PlatformAdhesionTypes.BRIM, - "Raft": PlatformAdhesionTypes.RAFT - }, - support={ - "None": SupportLocationTypes.NONE, - "Touching buildplate": SupportLocationTypes.TOUCHING_BUILDPLATE, - "Everywhere": SupportLocationTypes.EVERYWHERE - }, - support_type={ - "Lines": SupportTypes.LINES, - "Grid": SupportTypes.GRID - }, - support_dual_extrusion={ - "Both": SupportDualTypes.BOTH, - "First extruder": SupportDualTypes.FIRST, - "Second extruder": SupportDualTypes.SECOND - }, - retraction_combing={ - "Off": RetractionCombingTypes.OFF, - "All": RetractionCombingTypes.ALL, - "No Skin": RetractionCombingTypes.NO_SKIN - } - ) - - result = dict() - for section in config.sections(): - - if not section in ("profile", "alterations", "machine"): - continue - - for option in config.options(section): - ignored = False - key = option - - if section == "machine" and key != "gcode_flavor": - continue - - # try to fetch the value in the correct type - try: - value = config.getboolean(section, option) - except: - # no boolean, try int - try: - value = config.getint(section, option) - except: - # no int, try float - try: - value = config.getfloat(section, option) - except: - # no float, use str - value = config.get(section, option) - index = None - - for opt in arrayified_options: - # if there's a period, the index comes before it - optsplit = opt.split('.') - keysplit = key.split('.') - if key.startswith(optsplit[0]) and keysplit[1:] == optsplit[1:]: - if key == opt: - index = 0 - else: - try: - # try to convert the target index, e.g. print_temperature2 => print_temperature[1] - index = int(keysplit[0][len(optsplit[0]):]) - 1 - except ValueError: - # ignore entries for which that fails - ignored = True - key = opt - break - if ignored: - continue - - if key in translated_options: - # if the key has to be translated to a new value, do that now - key = translated_options[key] - - if key in value_conversions and value in value_conversions[key]: - value = value_conversions[key][value] - - if key == "gcode_flavor": - value = parse_gcode_flavor(value) - - if index is not None: - # if we have an array to fill, make sure the target array exists and has the right size - if not key in result: - result[key] = [] - if len(result[key]) <= index: - for n in range(index - len(result[key]) + 1): - result[key].append(None) - result[key][index] = value - else: - # just set the value if there's no array to fill - result[key] = value - - # merge it with our default settings, the imported profile settings taking precedence - return cls.merge_profile(result) - - - @classmethod - def merge_profile(cls, profile, overrides=None): - result = dict() - for key in defaults.keys(): - r = cls.merge_profile_key(key, profile, overrides=overrides) - if r is not None: - result[key] = r - return result - - @classmethod - def merge_profile_key(cls, key, profile, overrides=None): - profile_value = None - override_value = None - - if not key in defaults: - return None - import copy - result = copy.deepcopy(defaults[key]) - - if key in profile: - profile_value = profile[key] - if overrides and key in overrides: - override_value = overrides[key] - - if profile_value is None and override_value is None: - # neither override nor profile, no need to handle this key further - return None - - if key in ("filament_diameter", "print_temperature", "start_gcode", "end_gcode"): - # the array fields need some special treatment. Basically something like this: - # - # override_value: [None, "b"] - # profile_value : ["a" , None, "c"] - # default_value : ["d" , "e" , "f", "g"] - # - # should merge to something like this: - # - # ["a" , "b" , "c", "g"] - # - # So override > profile > default, if neither override nor profile value are available - # the default value should just be left as is - - for x in range(len(result)): - if override_value is not None and x < len(override_value) and override_value[x] is not None: - # we have an override value for this location, so we use it - result[x] = override_value[x] - elif profile_value is not None and x < len(profile_value) and profile_value[x] is not None: - # we have a profile value for this location, so we use it - result[x] = profile_value[x] - - else: - # just change the result value to the override_value if available, otherwise to the profile_value if - # that is given, else just leave as is - if override_value is not None: - result = override_value - elif profile_value is not None: - result = profile_value - - return result - - def __init__(self, profile, printer_profile, posX, posY, overrides=None): - self._profile = self.__class__.merge_profile(profile, overrides=overrides) - self._printer_profile = printer_profile - self._posX = posX - self._posY = posY - - def profile(self): - import copy - return copy.deepcopy(self._profile) - - def get(self, key): - if key in ("machine_width", "machine_depth", "machine_center_is_zero"): - if key == "machine_width": - return self._printer_profile["volume"]["width"] - elif key == "machine_depth": - return self._printer_profile["volume"]["depth"] - elif key == "machine_height": - return self._printer_profile["volume"]["height"] - elif key == "machine_center_is_zero": - return self._printer_profile["volume"]["formFactor"] == "circular" or self._printer_profile["volume"]["origin"] == "center" - else: - return None - - elif key == "extruder_amount": - return self._printer_profile["extruder"]["count"] - - elif key.startswith("extruder_offset_"): - extruder_offsets = self._printer_profile["extruder"]["offsets"] - match = Profile.regex_extruder_offset.match(key) - if not match: - return 0.0 - - axis, number = match.groups() - axis = axis.lower() - number = int(number) - - if not axis in ("x", "y"): - return 0.0 - if number >= len(extruder_offsets): - return 0.0 - - if axis == "x": - return extruder_offsets[number][0] - elif axis == "y": - return extruder_offsets[number][1] - else: - return 0.0 - - elif key == "has_heated_bed": - return self._printer_profile["heatedBed"] - - elif key.startswith("filament_diameter"): - match = Profile.regex_filament_diameter.match(key) - if not match: - return 0.0 - - diameters = self._get("filament_diameter") - if not match.group(1): - return diameters[0] - index = int(match.group(1)) - 1 - if index >= len(diameters) or index < 0: - return 0.0 - return diameters[index] - - elif key.startswith("print_temperature"): - match = Profile.regex_print_temperature.match(key) - if not match: - return 0.0 - - temperatures = self._get("print_temperature") - if not match.group(1): - return temperatures[0] - index = int(match.group(1)) - 1 - if index >= len(temperatures) or index < 0: - return 0.0 - return temperatures[index] - - else: - return self._get(key) - - def _get(self, key): - if key in self._profile: - return self._profile[key] - elif key in defaults: - return defaults[key] - else: - return None - - def get_int(self, key, default=None): - value = self.get(key) - if value is None: - return default - - try: - return int(value) - except ValueError: - return default - - def get_float(self, key, default=None): - value = self.get(key) - if value is None: - return default - - if isinstance(value, (str, unicode, basestring)): - value = value.replace(",", ".").strip() - - try: - return float(value) - except ValueError: - return default - - def get_boolean(self, key, default=None): - value = self.get(key) - if value is None: - return default - - if isinstance(value, bool): - return value - elif isinstance(value, (str, unicode, basestring)): - return value.lower() == "true" or value.lower() == "yes" or value.lower() == "on" or value == "1" - elif isinstance(value, (int, float)): - return value > 0 - else: - return value == True - - def get_microns(self, key, default=None): - value = self.get_float(key, default=None) - if value is None: - return default - return int(value * 1000) - - def get_gcode_template(self, key, extruder_count=1): - if key in self._profile: - gcode = self._profile[key] - else: - gcode = defaults[key] - - if key in ("start_gcode", "end_gcode"): - return self.regex_broken_replacements.sub("{\\1}", gcode[extruder_count-1]) - else: - return self.regex_broken_replacements.sub("{\\1}", gcode) - - def get_profile_string(self): - import base64 - import zlib - - import copy - profile = copy.deepcopy(defaults) - profile.update(self._profile) - for key in ("print_temperature", "print_temperature2", "print_temperature3", "print_temperature4", - "filament_diameter", "filament_diameter2", "filament_diameter3", "filament_diameter4"): - profile[key] = self.get(key) - - result = [] - for k, v in profile.items(): - if isinstance(v, (str, unicode)): - result.append("{k}={v}".format(k=k, v=v.encode("utf-8"))) - else: - result.append("{k}={v}".format(k=k, v=v)) - - return base64.b64encode(zlib.compress("\b".join(result), 9)) - - def replaceTagMatch(self, m): - import time - - pre = m.group(1) - tag = m.group(2) - - if tag == 'time': - return pre + time.strftime('%H:%M:%S') - if tag == 'date': - return pre + time.strftime('%d-%m-%Y') - if tag == 'day': - return pre + ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][int(time.strftime('%w'))] - if tag == 'profile_string': - return pre + 'CURA_OCTO_PROFILE_STRING:%s' % (self.get_profile_string()) - - if pre == 'F' and tag == 'max_z_speed': - f = self.get_float("travel_speed") * 60 - elif pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'bottom_layer_speed', 'cool_min_feedrate']: - f = self.get_float(tag) * 60 - elif self.get(tag): - f = self.get(tag) - else: - return '%s?%s?' % (pre, tag) - - if (f % 1) == 0: - return pre + str(int(f)) - - return pre + str(f) - - def get_gcode(self, key, extruder_count=1): - prefix = "" - postfix = "" - - if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE: - if key == "end_gcode": - return "M25 ;Stop reading from this point on.\n;CURA_OCTO_PROFILE_STRING:%s\n" % (self.get_profile_string()) - return "" - - if key == "start_gcode": - contents = self.get_gcode_template("start_gcode", extruder_count=extruder_count) - prefix += self.get_start_gcode_prefix(contents, extruder_count=extruder_count) - - else: - contents = self.get_gcode_template(key, extruder_count=extruder_count) - - return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n' - - def get_start_gcode_prefix(self, contents, extruder_count=1): - prefix = "" - without_comments = Profile.regex_strip_comments.sub("", contents) - - gcode_parameter_key = "S" - if self.get("gcode_flavor") == GcodeFlavors.MACH3: - gcode_parameter_key = "P" - - e_steps = self.get_float("steps_per_e") - if e_steps > 0: - prefix += "M92 E{e_steps}\n".format(e_steps=e_steps) - temp = self.get_float("print_temperature") - - bed_temp = 0 - if self.get_boolean("has_heated_bed"): - bed_temp = self.get_float("print_bed_temperature") - include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in without_comments - - if include_bed_temp: - prefix += "M140 {param}{bed_temp}\n".format(param=gcode_parameter_key, bed_temp=bed_temp) - - if temp > 0 and not "{print_temperature}" in without_comments: - if extruder_count > 0: - def temp_line(temp, extruder, param, template): - t = temp - if extruder > 0: - print_temp = self.get_float("print_temperature%d" % (extruder + 1)) - if print_temp > 0: - t = print_temp - return template.format(extruder=extruder, temp=t, param=param) - - prefix_preheat = "" - prefix_waitheat = "" - for n in range(0, extruder_count): - if n > 0: - prefix_preheat += temp_line(temp, n, gcode_parameter_key, "M104 T{extruder} {param}{temp}\n") - prefix_waitheat += temp_line(temp, n, gcode_parameter_key, "M109 T{extruder} {param}{temp}\n") - prefix += prefix_preheat + prefix_waitheat + "T0\n" - else: - prefix += "M109 {param}{temp}\n".format(param=gcode_parameter_key, temp=temp) - - if include_bed_temp: - prefix += "M190 {param}{bed_temp}\n".format(param=gcode_parameter_key, bed_temp=bed_temp) - - return prefix - - def calculate_edge_width_and_line_count(self): - wall_thickness = self.get_float("wall_thickness") - nozzle_size = self._printer_profile["extruder"]["nozzleDiameter"] - - if self.get_boolean("spiralize") or self.get_boolean("follow_surface"): - return wall_thickness, 1 - if wall_thickness < 0.01: - return nozzle_size, 0 - if wall_thickness < nozzle_size: - return wall_thickness, 1 - - edge_width = None - line_count = int(wall_thickness / (nozzle_size - 0.0001)) - if line_count < 1: - edge_width = nozzle_size - line_count = 1 - line_width = wall_thickness / line_count - line_width_alt = wall_thickness / (line_count + 1) - if line_width > nozzle_size * 1.5: - return line_width_alt, line_count + 1 - if not edge_width: - edge_width = line_width - return edge_width, line_count - - def calculate_solid_layer_count(self): - layer_height = self.get_float("layer_height") - solid_thickness = self.get_float("solid_layer_thickness") - if layer_height == 0.0: - return 1 - import math - return int(math.ceil((solid_thickness - 0.0001) / layer_height)) - - def calculate_minimal_extruder_count(self): - extruder_count = self.get("extruder_amount") - if extruder_count < 2: - return 1 - if self.get("support") == SupportLocationTypes.NONE: - return 1 - if self.get("support_dual_extrusion") == SupportDualTypes.SECOND: - return 2 - return 1 - - def get_pos_x(self): - if self._posX is not None: - try: - return int(float(self._posX)) - except ValueError: - pass - - return int(self.get_float("machine_width") / 2.0 ) if not self.get_boolean("machine_center_is_zero") else 0.0 - - def get_pos_y(self): - if self._posY is not None: - try: - return int(float(self._posY)) - except ValueError: - pass - - return int(self.get_float("machine_depth") / 2.0) if not self.get_boolean("machine_center_is_zero") else 0.0 - - def convert_to_engine(self, used_extruders=1): - - edge_width, line_count = self.calculate_edge_width_and_line_count() - solid_layer_count = self.calculate_solid_layer_count() - - extruder_count = self.get_int("extruder_amount") - minimal_extruder_count = self.calculate_minimal_extruder_count() - actual_extruder_count = max(minimal_extruder_count, used_extruders) - - settings = { - "layerThickness": self.get_microns("layer_height"), - "initialLayerThickness": self.get_microns("bottom_thickness") if self.get_float("bottom_thickness") > 0.0 else self.get_microns("layer_height"), - "filamentDiameter": self.get_microns("filament_diameter"), - "filamentFlow": self.get_int("filament_flow"), - "extrusionWidth": edge_width * 1000, - "layer0extrusionWidth": int(edge_width * self.get_float("first_layer_width_factor") / 100 * 1000), - "insetCount": line_count, - "downSkinCount": solid_layer_count if self.get_boolean("solid_bottom") else 0, - "upSkinCount": solid_layer_count if self.get_boolean("solid_top") else 0, - "infillOverlap": self.get_int("fill_overlap"), - "perimeterBeforeInfill": 1 if self.get_boolean("perimeter_before_infill") else 0, - "initialSpeedupLayers": int(4), - "initialLayerSpeed": self.get_int("bottom_layer_speed"), - "printSpeed": self.get_int("print_speed"), - "infillSpeed": self.get_int("infill_speed") if self.get_int("infill_speed") > 0 else self.get_int("print_speed"), - "inset0Speed": self.get_int("outer_shell_speed") if self.get_int("outer_shell_speed") > 0 else self.get_int("print_speed"), - "insetXSpeed": self.get_int("inner_shell_speed") if self.get_int("inner_shell_speed") > 0 else self.get_int("print_speed"), - "skinSpeed": self.get_int("solidarea_speed") if self.get_int("solidarea_speed") > 0 > 0 else self.get_int("print_speed"), - "moveSpeed": self.get_int("travel_speed"), - "fanSpeedMin": self.get_int("fan_speed") if self.get_boolean("fan_enabled") else 0, - "fanSpeedMax": self.get_int("fan_speed_max") if self.get_boolean("fan_enabled") else 0, - "supportAngle": int(-1) if self.get("support") == SupportLocationTypes.NONE else self.get_int("support_angle"), - "supportEverywhere": int(1) if self.get("support") == SupportLocationTypes.EVERYWHERE else int(0), - "supportLineDistance": int(100 * edge_width * 1000 / self.get_float("support_fill_rate")) if self.get_float("support_fill_rate") > 0 else -1, - "supportXYDistance": int(1000 * self.get_float("support_xy_distance")), - "supportZDistance": int(1000 * self.get_float("support_z_distance")), - "supportExtruder": 0 if self.get("support_dual_extrusion") == SupportDualTypes.FIRST else (1 if self.get("support_dual_extrusion") == SupportDualTypes.SECOND and minimal_extruder_count > 1 else -1), - "retractionAmount": self.get_microns("retraction_amount") if self.get_boolean("retraction_enable") else 0, - "retractionSpeed": self.get_int("retraction_speed"), - "retractionMinimalDistance": self.get_microns("retraction_min_travel"), - "retractionAmountExtruderSwitch": self.get_microns("retraction_dual_amount"), - "retractionZHop": self.get_microns("retraction_hop"), - "minimalExtrusionBeforeRetraction": self.get_microns("retraction_minimal_extrusion"), - "multiVolumeOverlap": self.get_microns("overlap_dual"), - "objectSink": max(0, self.get_microns("object_sink")), - "minimalLayerTime": self.get_int("cool_min_layer_time"), - "minimalFeedrate": self.get_int("cool_min_feedrate"), - "coolHeadLift": 1 if self.get_boolean("cool_head_lift") else 0, - - "enableCombing": 1 if self.get("retraction_combing") == RetractionCombingTypes.ALL else (2 if self.get("retraction_combing") == RetractionCombingTypes.NO_SKIN else 0), - - # model positioning - "posx": self.get_pos_x() * 1000, # in microns - "posy": self.get_pos_y() * 1000, # in microns - - # gcodes - "startCode": self.get_gcode("start_gcode", extruder_count=actual_extruder_count), - "endCode": self.get_gcode("end_gcode", extruder_count=actual_extruder_count), - "preSwitchExtruderCode": self.get_gcode("preSwitchExtruder_gcode", extruder_count=actual_extruder_count), - "postSwitchExtruderCode": self.get_gcode("postSwitchExtruder_gcode", extruder_count=actual_extruder_count), - - # fixing - "fixHorrible": 0, - } - - for extruder in range(1, extruder_count): - for axis in ("x", "y"): - settings["extruderOffset[{extruder}].{axis}".format(extruder=extruder, axis=axis.upper())] = self.get("extruder_offset_{axis}{extruder}".format(extruder=extruder, axis=axis.lower())) - - fanFullHeight = self.get_microns("fan_full_height") - settings["fanFullOnLayerNr"] = (fanFullHeight - settings["initialLayerThickness"] - 1) // settings["layerThickness"] + 1 - if settings["fanFullOnLayerNr"] < 0: - settings["fanFullOnLayerNr"] = 0 - - if self.get("support_type") == SupportTypes.LINES: - settings["supportType"] = 1 - - # infill - if self.get_float("fill_density") == 0: - settings["sparseInfillLineDistance"] = -1 - - elif self.get_float("fill_density") == 100: - settings["sparseInfillLineDistance"] = settings["extrusionWidth"] - settings["downSkinCount"] = 10000 - settings["upSkinCount"] = 10000 - - else: - settings["sparseInfillLineDistance"] = int(100 * edge_width * 1000 / self.get_float("fill_density")) - - # brim/raft/skirt - if self.get("platform_adhesion") == PlatformAdhesionTypes.BRIM: - settings["skirtDistance"] = 0 - settings["skirtLineCount"] = self.get_int("brim_line_count") - - elif self.get("platform_adhesion") == PlatformAdhesionTypes.RAFT: - settings["skirtDistance"] = 0 - settings["skirtLineCount"] = 0 - settings["raftMargin"] = self.get_microns("raft_margin") - settings["raftLineSpacing"] = self.get_microns("raft_line_spacing") - settings["raftBaseThickness"] = self.get_microns("raft_base_thickness") - settings["raftBaseLinewidth"] = self.get_microns("raft_base_linewidth") - settings["raftInterfaceThickness"] = self.get_microns("raft_interface_thickness") - settings["raftInterfaceLinewidth"] = self.get_microns("raft_interface_linewidth") - settings["raftInterfaceLineSpacing"] = self.get_microns("raft_interface_linewidth") * 2 - settings["raftAirGapLayer0"] = self.get_microns("raft_airgap") + self.get_microns("raft_airgap_all") - settings["raftAirGap"] = self.get_microns("raft_airgap_all") - settings["raftBaseSpeed"] = self.get_int("bottom_layer_speed") - settings["raftFanSpeed"] = 0 - settings["raftSurfaceThickness"] = self.get_microns("raft_surface_thickness") - settings["raftSurfaceLinewidth"] = self.get_microns("raft_surface_linewidth") - settings["raftSurfaceLineSpacing"] = self.get_microns("raft_surface_linewidth") - settings["raftSurfaceLayers"] = self.get_int("raft_surface_layers") - settings["raftSurfaceSpeed"] = self.get_int("bottom_layer_speed") - - else: - settings["skirtDistance"] = self.get_microns("skirt_gap") - settings["skirtLineCount"] = self.get_int("skirt_line_count") - settings["skirtMinLength"] = self.get_microns("skirt_minimal_length") - - # fixing - if self.get_boolean("fix_horrible_union_all_type_a"): - settings["fixHorrible"] |= 0x01 - if self.get_boolean("fix_horrible_union_all_type_b"): - settings["fixHorrible"] |= 0x02 - if self.get_boolean("fix_horrible_use_open_bits"): - settings["fixHorrible"] |= 0x10 - if self.get_boolean("fix_horrible_extensive_stitching"): - settings["fixHorrible"] |= 0x04 - - if settings["layerThickness"] <= 0: - settings["layerThickness"] = 1000 - - # gcode flavor - settings["gcodeFlavor"] = self.get("gcode_flavor")[0] - - # extras - if self.get_boolean("spiralize"): - settings["spiralizeMode"] = 1 - if self.get_boolean("follow_surface"): - settings["simpleMode"] = 1 - - # dual extrusion - if self.get_boolean("wipe_tower") and extruder_count > 1: - import math - settings["wipeTowerSize"] = int(math.sqrt(self.get_float("wipe_tower_volume") * 1000 * 1000 * 1000 / settings["layerThickness"])) - if self.get_boolean("ooze_shield"): - settings["enableOozeShield"] = 1 - - return settings - - -def parse_gcode_flavor(value): - - value = value.lower() - - if "reprap" in value and ("volume" in value or "volumatric" in value): - return GcodeFlavors.REPRAP_VOLUME - elif "ultigcode" in value: - return GcodeFlavors.ULTIGCODE - elif "makerbot" in value: - return GcodeFlavors.MAKERBOT - elif "bfb" in value: - return GcodeFlavors.BFB - elif "mach3" in value: - return GcodeFlavors.MACH3 - else: - return GcodeFlavors.REPRAP diff --git a/src/octoprint/plugins/cura/profiles/default.profile.yaml b/src/octoprint/plugins/cura/profiles/default.profile.yaml deleted file mode 100644 index d53fabc61..000000000 --- a/src/octoprint/plugins/cura/profiles/default.profile.yaml +++ /dev/null @@ -1,4 +0,0 @@ -layer_height: 0.2 -print_temperature: -- 220.0 -- 220.0 \ No newline at end of file diff --git a/src/octoprint/plugins/cura/static/css/cura.css b/src/octoprint/plugins/cura/static/css/cura.css deleted file mode 100644 index f35eab40a..000000000 --- a/src/octoprint/plugins/cura/static/css/cura.css +++ /dev/null @@ -1 +0,0 @@ -table th.settings_plugin_cura_profiles_key,table td.settings_plugin_cura_profiles_key{text-overflow:ellipsis;text-align:left;width:200px}table th.settings_plugin_cura_profiles_name,table td.settings_plugin_cura_profiles_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_cura_profiles_actions,table td.settings_plugin_cura_profiles_actions{text-align:center;width:100px}table th.settings_plugin_cura_profiles_actions a,table td.settings_plugin_cura_profiles_actions a{text-decoration:none;color:#000}table th.settings_plugin_cura_profiles_actions a.disabled,table td.settings_plugin_cura_profiles_actions a.disabled{color:#ccc;cursor:default} \ No newline at end of file diff --git a/src/octoprint/plugins/cura/static/js/cura.js b/src/octoprint/plugins/cura/static/js/cura.js deleted file mode 100644 index 9909b3b0a..000000000 --- a/src/octoprint/plugins/cura/static/js/cura.js +++ /dev/null @@ -1,328 +0,0 @@ -$(function() { - function CuraViewModel(parameters) { - var self = this; - - self.loginState = parameters[0]; - self.settingsViewModel = parameters[1]; - self.slicingViewModel = parameters[2]; - - self.pathBroken = ko.observable(false); - self.pathOk = ko.observable(false); - self.pathText = ko.observable(); - self.pathHelpVisible = ko.pureComputed(function() { - return self.pathBroken() || self.pathOk(); - }); - - self.fileName = ko.observable(); - - self.placeholderName = ko.observable(); - self.placeholderDisplayName = ko.observable(); - self.placeholderDescription = ko.observable(); - - self.profileName = ko.observable(); - self.profileDisplayName = ko.observable(); - self.profileDescription = ko.observable(); - self.profileAllowOverwrite = ko.observable(true); - self.profileMakeDefault = ko.observable(false); - self.profileFirst = ko.observable(false); - - // make sure to update form data if any of the metadata changes - self.profileName.subscribe(function() { self.copyProfileMetadata(); }); - self.profileDisplayName.subscribe(function() { - if (self.profileDisplayName()) { - self.placeholderName(self._sanitize(self.profileDisplayName()).toLowerCase()); - } - self.copyProfileMetadata(); - }); - self.profileDescription.subscribe(function() { self.copyProfileMetadata(); }); - self.profileAllowOverwrite.subscribe(function() { self.copyProfileMetadata(); }); - self.profileMakeDefault.subscribe(function() { self.copyProfileMetadata(); }); - - self.unconfiguredCuraEngine = ko.observable(); - self.unconfiguredSlicingProfile = ko.observable(); - - self.uploadDialog = $("#settings_plugin_cura_import"); - self.uploadElement = $("#settings-cura-import"); - self.uploadData = ko.observable(undefined); - self.uploadBusy = ko.observable(false); - - self.uploadEnabled = ko.pureComputed(function() { - return self.fieldsEnabled(); - }); - self.fieldsEnabled = ko.pureComputed(function() { - return self.uploadData() && !self.uploadBusy() - && (self.profileName() || self.placeholderName()) - && (self.profileDisplayName() || self.placeholderDisplayName()) - && (self.profileDescription() || self.placeholderDescription()); - }); - - self.profiles = new ItemListHelper( - "plugin_cura_profiles", - { - "id": function(a, b) { - if (a["key"].toLocaleLowerCase() < b["key"].toLocaleLowerCase()) return -1; - if (a["key"].toLocaleLowerCase() > b["key"].toLocaleLowerCase()) return 1; - return 0; - }, - "name": function(a, b) { - // sorts ascending - var aName = a.name(); - if (aName === undefined) { - aName = ""; - } - var bName = b.name(); - if (bName === undefined) { - bName = ""; - } - - if (aName.toLocaleLowerCase() < bName.toLocaleLowerCase()) return -1; - if (aName.toLocaleLowerCase() > bName.toLocaleLowerCase()) return 1; - return 0; - } - }, - {}, - "id", - [], - [], - 5 - ); - - self._sanitize = function(name) { - return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_"); - }; - - self.performUpload = function() { - if (self.uploadData()) { - self.uploadData().submit(); - } - }; - - self.copyProfileMetadata = function(form) { - form = form || (self.uploadData() ? self.uploadData().formData : {}); - - if (self.profileName() !== undefined) { - form["name"] = self.profileName(); - } else if (self.placeholderName() !== undefined) { - form["name"] = self.placeholderName(); - } - - if (self.profileDisplayName() !== undefined) { - form["displayName"] = self.profileDisplayName(); - } else if (self.placeholderDisplayName() !== undefined) { - form["displayName"] = self.placeholderDisplayName(); - } - - if (self.profileDescription() !== undefined) { - form["description"] = self.profileDescription(); - } else if (self.placeholderDescription() !== undefined) { - form["description"] = self.placeholderDescription(); - } - - if (self.profileMakeDefault()) { - form["default"] = true; - } - - return form; - }; - - self.clearUpload = function() { - self.uploadData(undefined); - self.fileName(undefined); - self.placeholderName(undefined); - self.placeholderDisplayName(undefined); - self.placeholderDescription(undefined); - self.profileName(undefined); - self.profileDisplayName(undefined); - self.profileDescription(undefined); - self.profileAllowOverwrite(true); - - var firstProfile = self.profiles.items().length === 0; - self.profileMakeDefault(firstProfile); - self.profileFirst(firstProfile); - }; - - self.uploadElement.fileupload({ - dataType: "json", - maxNumberOfFiles: 1, - autoUpload: false, - headers: OctoPrint.getRequestHeaders(), - add: function(e, data) { - if (data.files.length == 0) { - // no files? ignore - return false; - } - if (self.uploadData()) { - // data already defined? ignore (should never happen) - return false; - } - - self.fileName(data.files[0].name); - - var name = self.fileName().substr(0, self.fileName().lastIndexOf(".")); - self.placeholderName(self._sanitize(name).toLowerCase()); - self.placeholderDisplayName(name); - self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000)); - - var form = { - allowOverwrite: self.profileAllowOverwrite() - }; - data.formData = self.copyProfileMetadata(form); - - self.uploadData(data); - }, - submit: function(e, data) { - self.copyProfileMetadata(); - self.uploadBusy(true); - }, - done: function(e, data) { - self.uploadBusy(false); - self.clearUpload(); - - self.uploadDialog.modal("hide"); - self.requestData(); - self.slicingViewModel.requestData(); - }, - error: function(jqXHR, textStatus, errorThrown) { - self.uploadBusy(false); - new PNotify({ - title: gettext("Profile import failed"), - text: gettext("Could not import the provided profile, it might be invalid. Check octoprint.log for details"), - type: "error", - hide: false - }); - } - }); - - self.removeProfile = function(data) { - if (!data.resource) { - return; - } - - self.profiles.removeItem(function(item) { - return (item.key == data.key); - }); - - OctoPrint.slicing.deleteProfileForSlicer("cura", data.key, {url: data.resource()}) - .done(function() { - self.requestData(); - self.slicingViewModel.requestData(); - }); - }; - - self.makeProfileDefault = function(data) { - if (!data.resource) { - return; - } - - _.each(self.profiles.items(), function(item) { - item.isdefault(false); - }); - var item = self.profiles.getItem(function(item) { - return item.key == data.key; - }); - if (item !== undefined) { - item.isdefault(true); - } - - OctoPrint.slicing.updateProfileForSlicer("cura", data.key, {default: true}, {url: data.resource()}) - .done(function() { - self.requestData(); - }); - }; - - self.showImportProfileDialog = function() { - self.clearUpload(); - self.uploadDialog.modal("show"); - }; - - self.testEnginePath = function() { - OctoPrint.util.testExecutable(self.settings.plugins.cura.cura_engine()) - .done(function(response) { - if (!response.result) { - if (!response.exists) { - self.pathText(gettext("The path doesn't exist")); - } else if (!response.typeok) { - self.pathText(gettext("The path is not a file")); - } else if (!response.access) { - self.pathText(gettext("The path is not an executable")); - } - } else { - self.pathText(gettext("The path is valid")); - } - self.pathOk(response.result); - self.pathBroken(!response.result); - }); - }; - - self.requestData = function() { - self.slicingViewModel.requestData(); - }; - - self.fromResponse = function(data) { - var profiles = []; - _.each(_.keys(data), function(key) { - profiles.push({ - key: key, - name: ko.observable(data[key].displayName), - description: ko.observable(data[key].description), - isdefault: ko.observable(data[key].default), - resource: ko.observable(data[key].resource) - }); - }); - self.profiles.updateItems(profiles); - }; - - self.onBeforeBinding = function () { - self.settings = self.settingsViewModel.settings; - }; - - self.onAllBound = function() { - self.uploadDialog.on("hidden", function(event) { - if (event.target.id == "settings_plugin_cura_import") { - self.clearUpload(); - } - }); - }; - - self.onSettingsShown = function() { - self.requestData(); - }; - - self.onSettingsHidden = function() { - self.resetPathTest(); - }; - - self.onSlicingData = function(data) { - if (data && data.hasOwnProperty("cura") && data.cura.hasOwnProperty("profiles")) { - self.fromResponse(data.cura.profiles); - } - }; - - self.resetPathTest = function() { - self.pathBroken(false); - self.pathOk(false); - self.pathText(""); - }; - - self.onWizardDetails = function(response) { - if (!response.hasOwnProperty("cura") || !response.cura.required) return; - - if (response.cura.details.hasOwnProperty("engine")) { - self.unconfiguredCuraEngine(!response.cura.details.engine); - } - if (response.cura.details.hasOwnProperty("profile")) { - self.unconfiguredSlicingProfile(!response.cura.details.profile); - } - }; - - self.onWizardFinish = function() { - self.resetPathTest(); - }; - } - - OCTOPRINT_VIEWMODELS.push({ - construct: CuraViewModel, - dependencies: ["loginStateViewModel", "settingsViewModel", "slicingViewModel"], - elements: ["#settings_plugin_cura", "#wizard_plugin_cura"] - }); -}); diff --git a/src/octoprint/plugins/cura/static/less/cura.less b/src/octoprint/plugins/cura/static/less/cura.less deleted file mode 100644 index 0d28da219..000000000 --- a/src/octoprint/plugins/cura/static/less/cura.less +++ /dev/null @@ -1,29 +0,0 @@ -table { - th, td { - &.settings_plugin_cura_profiles_key { - text-overflow: ellipsis; - text-align: left; - width: 200px; - } - - &.settings_plugin_cura_profiles_name { - text-overflow: ellipsis; - text-align: left; - } - - &.settings_plugin_cura_profiles_actions { - text-align: center; - width: 100px; - - a { - text-decoration: none; - color: #000; - - &.disabled { - color: #ccc; - cursor: default; - } - } - } - } -} \ No newline at end of file diff --git a/src/octoprint/plugins/cura/templates/cura_settings.jinja2 b/src/octoprint/plugins/cura/templates/cura_settings.jinja2 deleted file mode 100644 index d5726f2d5..000000000 --- a/src/octoprint/plugins/cura/templates/cura_settings.jinja2 +++ /dev/null @@ -1,25 +0,0 @@ -

{{ _('General') }}

- -

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

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

{{ _('Profiles') }}

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

{{ _('Configure CuraEngine') }}

-

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

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

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

-

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

- -
- {% include "snippets/settings/cura/profiles.jinja2" %} -
- - - -
- {% trans %} - Don't know where to get a profile? In order to export - a slicing profile from the Cura desktop UI up to and including version 15.04.06 (not versions - 2.1 and later which are actually newer than 15.04), open it, set up your profile, then click - on "File" and there on "Save Profile". You can import the .ini file this creates - via the "Import Profile" button. - {% endtrans %} -
-
diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 deleted file mode 100644 index 690f1490d..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 +++ /dev/null @@ -1,7 +0,0 @@ -
-
- -
-
diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 deleted file mode 100644 index b2e6a522d..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 +++ /dev/null @@ -1,10 +0,0 @@ -
- -
-
- - -
- -
-
diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 deleted file mode 100644 index ddf48eb2b..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 +++ /dev/null @@ -1,64 +0,0 @@ - diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 deleted file mode 100644 index f5d85ea3e..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 +++ /dev/null @@ -1,34 +0,0 @@ -
- - - - - - - - - - - - - - - - -
{{ _('Identifier') }}{{ _('Name') }}{{ _('Actions') }}
-  |  -
- -
diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index d5fb2fb41..50d8fad7b 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -562,9 +562,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 @@ -603,7 +602,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, except: pass - self._ssdp_last_notify = time.time() + self._ssdp_last_notify = octoprint.util.monotonic_time() def _ssdp_monitor(self, timeout=5): """ diff --git a/src/octoprint/plugins/errortracking/__init__.py b/src/octoprint/plugins/errortracking/__init__.py new file mode 100644 index 000000000..341adf66b --- /dev/null +++ b/src/octoprint/plugins/errortracking/__init__.py @@ -0,0 +1,205 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import octoprint.plugin +import logging + +from octoprint.util.version import get_octoprint_version_string, is_released_octoprint_version + +from flask import jsonify +from flask_babel import gettext + +SENTRY_URL_SERVER = "https://4069187705ab4e76921eb19db2e9ccbb@sentry.io/1373987" +SENTRY_URL_COREUI = "https://a4ab48f27daf4c129392b78be15412b8@sentry.io/1374096" + +SETTINGS_DEFAULTS = dict(enabled=False, + enabled_unreleased=False, + unique_id=None, + url_server=SENTRY_URL_SERVER, + url_coreui=SENTRY_URL_COREUI) + +import serial +import requests.exceptions +import errno +import octoprint.util.avr_isp.ispBase +import tornado.websocket + +IGNORED_EXCEPTIONS = [ + # serial exceptions in octoprint.util.comm + (serial.SerialException, lambda exc, logger, plugin: 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, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.SimpleApiPlugin): + + def get_template_configs(self): + return [ + dict(type="settings", + name=gettext("Error Tracking"), + template="errortracking_settings.jinja2", + custom_bindings=False), + dict(type="generic", template="errortracking_javascripts.jinja2") + ] + + def get_template_vars(self): + enabled = self._settings.get_boolean(["enabled"]) + enabled_unreleased = self._settings.get_boolean(["enabled_unreleased"]) + + return dict(enabled=_is_enabled(enabled, enabled_unreleased), + unique_id=self._settings.get(["unique_id"]), + url_coreui=self._settings.get(["url_coreui"])) + + def get_assets(self): + return dict(js=["js/sentry.min.js", "js/errortracking.js"]) + + def get_settings_defaults(self): + return SETTINGS_DEFAULTS + + def on_settings_save(self, data): + old_enabled = _is_enabled(self._settings.get_boolean(["enabled"]), + self._settings.get_boolean(["enabled_unreleased"])) + + octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + + enabled = _is_enabled(self._settings.get_boolean(["enabled"]), + self._settings.get_boolean(["enabled_unreleased"])) + + if old_enabled != enabled: + _enable_errortracking() + + def on_api_get(self, request): + return jsonify(**self.get_template_vars()) + + +_enabled = False +def _enable_errortracking(): + # this is a bit hackish, but we want to enable error tracking as early in the platform lifecycle as possible + # and hence can't wait until our implementation is initialized and injected with settings + + from octoprint.settings import settings + global _enabled + + if _enabled: + return + + version = get_octoprint_version_string() + + s = settings() + plugin_defaults = dict(plugins=dict(errortracking=SETTINGS_DEFAULTS)) + + enabled = s.getBoolean(["plugins", "errortracking", "enabled"], defaults=plugin_defaults) + enabled_unreleased = s.getBoolean(["plugins", "errortracking", "enabled_unreleased"], defaults=plugin_defaults) + url_server = s.get(["plugins", "errortracking", "url_server"], defaults=plugin_defaults) + unique_id = s.get(["plugins", "errortracking", "unique_id"], defaults=plugin_defaults) + if unique_id is None: + import uuid + unique_id = str(uuid.uuid4()) + s.set(["plugins", "errortracking", "unique_id"], unique_id, defaults=plugin_defaults) + s.save() + + if _is_enabled(enabled, enabled_unreleased): + import sentry_sdk + from octoprint.plugin import plugin_manager + + def _before_send(event, hint): + if not "exc_info" in hint: + # we only want exceptions + return None + + handled = True + logger = event.get("logger", "") + plugin = event.get("extra", dict()).get("plugin", None) + + 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, + before_send=_before_send) + + with sentry_sdk.configure_scope() as scope: + scope.user = dict(id=unique_id) + + logging.getLogger("octoprint.plugins.errortracking").info("Initialized error tracking") + _enabled = True + + +def _is_enabled(enabled, enabled_unreleased): + return enabled and (enabled_unreleased or is_released_octoprint_version()) + + +def __plugin_enable__(): + _enable_errortracking() + + +__plugin_name__ = "Error Tracking" +__plugin_author__ = "Gina Häußge" +__plugin_implementation__ = ErrorTrackingPlugin() diff --git a/src/octoprint/plugins/errortracking/static/js/errortracking.js b/src/octoprint/plugins/errortracking/static/js/errortracking.js new file mode 100644 index 000000000..32ed05e0b --- /dev/null +++ b/src/octoprint/plugins/errortracking/static/js/errortracking.js @@ -0,0 +1,103 @@ +$(function() { + function ErrorTrackingViewModel(parameters) { + var self = this; + + self.settings = parameters[0]; + self.loginState = parameters[1]; + + var notification = undefined; + var performCheck = function() { + if (!self.loginState.isAdmin()) return; + + // already enabled? + if (self.settings.settings.plugins.errortracking.enabled()) return; + + // RC release channel? + var releaseChannel = self.settings.settings.plugins.softwareupdate.octoprint_release_channel(); + if (releaseChannel === "rc/maintenance" || releaseChannel === "rc/devel") { + if (notification !== undefined) return; + + // ignored? + try { + var ignoredString = localStorage["plugin.errortracking.notification_ignored"]; + var ignored = false; + + if (ignoredString) { + ignored = JSON.parse(ignoredString); + } + + if (ignored) return; + } catch (ex) { + log.error("Error while reading plugin.errortracking.notification_ignored from local storage"); + } + + // show notification + notification = new PNotify({ + title: gettext("Enable error reporting?"), + text: gettext("

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

" + + "

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

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

{{ _('Error Tracking') }}

+ +{% trans %} +

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

+

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

+

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

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

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

+{% endtrans %} diff --git a/src/octoprint/plugins/forcelogin/__init__.py b/src/octoprint/plugins/forcelogin/__init__.py index 0f6ea9cdd..03b0083ac 100644 --- a/src/octoprint/plugins/forcelogin/__init__.py +++ b/src/octoprint/plugins/forcelogin/__init__.py @@ -23,21 +23,40 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin, self._message_backlog = defaultdict(list) self._message_backlog_mutex = threading.RLock() + @property + def active(self): + # we are only active if ACL is enabled AND configured + return self._user_manager.enabled and self._user_manager.hasBeenCustomized() + def get_assets(self): return dict( js=["js/viewmodel.js"] ) def will_handle_ui(self, request): - if self._user_manager.enabled and not self._user_manager.hasBeenCustomized(): - # ACL hasn't been configured yet, make an exception + if not self.active: + # not active, not responsible return False + from octoprint.server.util import loginUserFromApiKey, loginUserFromAuthorizationHeader, InvalidApiKeyException from octoprint.server.util.flask import passive_login + # first try to login via api key & authorization header, just in case that's set + try: + if loginUserFromApiKey(): + # successful? No need for handling the UI + return False + except InvalidApiKeyException: + pass # ignored + + if loginUserFromAuthorizationHeader(): + # successful? No need for handling the UI + return False + + # then try a passive login result = passive_login() if hasattr(result, "status_code") and result.status_code == 200: - # passive login successful, no need to handle that + # successful? No need for handling the UI return False else: return True @@ -68,7 +87,8 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin, if isinstance(assets, (tuple, list)): additional_assets += assets except: - self._logger.exception("Error fetching theming CSS to include from plugin {}".format(name)) + self._logger.exception("Error fetching theming CSS to include from plugin {}".format(name), + extra=dict(plugin=name)) render_kwargs.update(dict(forcelogin_theming=additional_assets)) return make_response(render_template("forcelogin_index.jinja2", **render_kwargs)) @@ -89,18 +109,26 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin, def get_ui_preemptive_caching_enabled(self): return False - def get_before_request_handlers(self): + def get_sorting_key(self, context=None): + if context == "UiPlugin.on_ui_render": + # If a plugin *really* wants to come before this plugin, it'll have to turn to negative numbers. + # + # This is obviously discouraged for security reasons, but very specific setups might make it necessary, + # so we make it possible. If this should get abused long term we can always turn this into -inf. + return 0 + + def get_before_request_handlers(self, plugin=None, *args, **kwargs): def check_login_required(): - if self._user_manager.enabled and not self._user_manager.hasBeenCustomized(): - # ACL hasn't been configured yet, make an exception - return - elif not self._user_manager.enabled: - # ACL isn't enabled + if not self.active: + # not active, no handling return if flask.request.endpoint in ("api.login",): return + if plugin is not None and not plugin.is_blueprint_protected(): + return + user = flask_login.current_user if user is None or user.is_anonymous() or not user.is_active(): return flask.make_response("Forbidden", 403) @@ -108,11 +136,8 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin, return [check_login_required] def access_validator(self, request): - if self._user_manager.enabled and not self._user_manager.hasBeenCustomized(): - # ACL hasn't been configured yet, make an exception - return - elif not self._user_manager.enabled: - # ACL isn't enabled + if not self.active: + # not active, no handling return import tornado.web @@ -123,11 +148,8 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin, raise tornado.web.HTTPError(403) def socket_register_validator(self, socket, user): - if self._user_manager.enabled and not self._user_manager.hasBeenCustomized(): - # ACL hasn't been configured yet, make an exception - return True - elif not self._user_manager.enabled: - # ACL isn't enabled + if not self.active: + # not active, no limitation return True return user is not None and not user.is_anonymous() and user.is_active() @@ -142,11 +164,8 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin, self._logger.debug("Sent backlog of {} message(s) via socket".format(len(backlog))) def socket_emit_validator(self, socket, user, message, payload): - if self._user_manager.enabled and not self._user_manager.hasBeenCustomized(): - # ACL hasn't been configured yet, make an exception - return True - elif not self._user_manager.enabled: - # ACL isn't enabled + if not self.active: + # not active, no limitation return True if message in ("connected", "reauthRequired"): diff --git a/src/octoprint/plugins/forcelogin/static/js/main.js b/src/octoprint/plugins/forcelogin/static/js/main.js index e46bdf840..b053fafa6 100644 --- a/src/octoprint/plugins/forcelogin/static/js/main.js +++ b/src/octoprint/plugins/forcelogin/static/js/main.js @@ -17,7 +17,7 @@ $(function() { var username = usernameElement.val(); var password = passwordElement.val(); - var remember = rememberElement.checked; + var remember = rememberElement.prop("checked"); overlayElement.addClass("in"); errorElement.removeClass("in"); @@ -41,19 +41,6 @@ $(function() { OctoPrint.options.baseurl = BASE_URL; - 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} - }); - }); - OctoPrint.socket.onConnected = function() { buttonElement.prop("disabled", false); offlineElement.removeClass("in"); diff --git a/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2 b/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2 index 3b8b36ce4..c5b6e28dc 100644 --- a/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2 +++ b/src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2 @@ -1,7 +1,14 @@ + OctoPrint Login + + + + + + {% include "parts/forcelogin_css.jinja2" %} {% include "parts/forcelogin_javascripts.jinja2" %} diff --git a/src/octoprint/plugins/logging/static/css/logging.css b/src/octoprint/plugins/logging/static/css/logging.css index 31603a340..ac69c3e52 100644 --- a/src/octoprint/plugins/logging/static/css/logging.css +++ b/src/octoprint/plugins/logging/static/css/logging.css @@ -1 +1 @@ -table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default} \ No newline at end of file +table td.settings_logs_checkbox,table th.settings_logs_checkbox{text-align:center;width:10px}table td.settings_logs_checkbox input[type=checkbox],table th.settings_logs_checkbox input[type=checkbox]{margin-top:0}table td.settings_logs_name,table th.settings_logs_name{text-overflow:ellipsis;text-align:left}table td.settings_logs_size,table th.settings_logs_size{text-align:right;width:70px}table td.settings_logs_date,table th.settings_logs_date{text-align:left;width:130px}table td.settings_logs_action,table th.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table td.settings_logs_action a,table th.settings_logs_action a{text-decoration:none;color:#000}table td.settings_logs_action a.disabled,table th.settings_logs_action a.disabled{color:#ccc;cursor:default} \ No newline at end of file diff --git a/src/octoprint/plugins/logging/static/js/logging.js b/src/octoprint/plugins/logging/static/js/logging.js index 2f0f16988..f465b5fe7 100644 --- a/src/octoprint/plugins/logging/static/js/logging.js +++ b/src/octoprint/plugins/logging/static/js/logging.js @@ -9,6 +9,8 @@ $(function() { self.configuredLoggers = ko.observableArray(); self.configuredLoggersChanged = false; + self.markedForDeletion = ko.observableArray([]); + self.availableLoggersSorted = ko.computed(function() { return _.sortBy(self.availableLoggers()); }); @@ -114,8 +116,37 @@ $(function() { }; self.removeFile = function(filename) { - OctoPrint.plugins.logging.deleteLog(filename) - .done(self.requestData); + var perform = function() { + OctoPrint.plugins.logging.deleteLog(filename) + .done(self.requestData); + }; + + showConfirmationDialog(_.sprintf(gettext("You are about to delete log file \"%(name)s\"."), {name: filename}), + perform); + }; + + self.markFilesOnPage = function() { + self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.listHelper.paginatedItems(), "name")))); + }; + + self.markAllFiles = function() { + self.markedForDeletion(_.map(self.listHelper.allItems, "name")); + }; + + self.clearMarkedFiles = function() { + self.markedForDeletion.removeAll(); + }; + + self.removeMarkedFiles = function() { + var perform = function() { + self._bulkRemove(self.markedForDeletion(), "files") + .done(function() { + self.markedForDeletion.removeAll(); + }); + }; + + showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d log files."), {count: self.markedForDeletion().length}), + perform); }; self.onSettingsShown = function() { @@ -134,6 +165,47 @@ $(function() { console.log("ConfiguredLoggers has not changed. Not saving."); } }; + + self._bulkRemove = function(files) { + var title = gettext("Deleting log files"); + var message = _.sprintf(gettext("Deleting %(count)d log files..."), {count: files.length}); + var handler = function(filename) { + return OctoPrint.plugins.logging.deleteLog(filename) + .done(function() { + deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true); + }) + .fail(function(jqXHR) { + var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename}); + var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText}); + deferred.notify(short, long, false); + }); + }; + + var deferred = $.Deferred(); + + var promise = deferred.promise(); + + var options = { + title: title, + message: message, + max: files.length, + output: true + }; + showProgressModal(options, promise); + + var requests = []; + _.each(files, function(filename) { + var request = handler(filename); + requests.push(request) + }); + $.when.apply($, _.map(requests, wrapPromiseWithAlways)) + .done(function() { + deferred.resolve(); + self.requestData(); + }); + + return promise; + }; } OCTOPRINT_VIEWMODELS.push({ diff --git a/src/octoprint/plugins/logging/static/less/logging.less b/src/octoprint/plugins/logging/static/less/logging.less index dfcb1c1f7..ac8b34dac 100644 --- a/src/octoprint/plugins/logging/static/less/logging.less +++ b/src/octoprint/plugins/logging/static/less/logging.less @@ -1,5 +1,14 @@ table { th, td { + &.settings_logs_checkbox { + text-align: center; + width: 10px; + + input[type="checkbox"] { + margin-top: 0; + } + } + &.settings_logs_name { text-overflow: ellipsis; text-align: left; diff --git a/src/octoprint/plugins/logging/templates/logging_settings.jinja2 b/src/octoprint/plugins/logging/templates/logging_settings.jinja2 index 7a082ec6b..7d427324b 100644 --- a/src/octoprint/plugins/logging/templates/logging_settings.jinja2 +++ b/src/octoprint/plugins/logging/templates/logging_settings.jinja2 @@ -1,13 +1,31 @@

{{ _('Logs') }}

+ + @@ -16,6 +34,7 @@ + diff --git a/src/octoprint/plugins/pi_support/__init__.py b/src/octoprint/plugins/pi_support/__init__.py index 8ea0af7be..4c79b6151 100644 --- a/src/octoprint/plugins/pi_support/__init__.py +++ b/src/octoprint/plugins/pi_support/__init__.py @@ -12,6 +12,7 @@ from flask_babel import gettext from octoprint.util import RepeatedTimer import octoprint.plugin +import octoprint.events _PROC_DT_MODEL_PATH = "/proc/device-tree/model" _OCTOPI_VERSION_PATH = "/etc/octopi_version" @@ -290,7 +291,13 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin, self._plugin_manager.send_plugin_message(self._identifier, dict(type="throttle_state", state=self._throttle_state.as_dict())) - self._event_bus.fire("plugin_pi_support_throttle_state", self._throttle_state.as_dict()) + + # noinspection PyUnresolvedReferences + self._event_bus.fire(octoprint.events.Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE, self._throttle_state.as_dict()) + + +def register_custom_events(*args, **kwargs): + return ["throttle_state",] __plugin_name__ = "Pi Support Plugin" @@ -316,5 +323,10 @@ def __plugin_load__(): global __plugin_implementation__ __plugin_implementation__ = plugin + global __plugin_hooks__ + __plugin_hooks__ = { + "octoprint.events.register_custom_events": register_custom_events + } + global __plugin_helpers__ __plugin_helpers__ = dict(get_throttled=plugin.get_throttle_state) diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index c085c032e..5caa980b6 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -16,6 +16,7 @@ from octoprint.server import admin_permission from octoprint.util.pip import LocalPipCaller from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible from octoprint.util.platform import get_os, is_os_compatible +from octoprint.events import Events from flask import jsonify, make_response from flask_babel import gettext @@ -27,10 +28,11 @@ import requests import re import os import copy -import dateutil.parser import time import threading +from datetime import datetime + _DATA_FORMAT_VERSION = "v2" @@ -363,7 +365,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, raise ValueError("Either URL or path must be provided") self._logger.info("Installing plugin from {}".format(source)) - pip_args = ["install", sarge.shell_quote(source), '--no-cache-dir'] + pip_args = ["--disable-pip-version-check", "install", sarge.shell_quote(source), "--no-cache-dir"] if dependency_links or self._settings.get_boolean(["dependency_links"]): pip_args.append("--process-dependency-links") @@ -485,10 +487,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.log_all_plugins() self._logger.info("The plugin was installed successfully: {}, version {}".format(new_plugin.name, new_plugin.version)) - self._event_bus.fire("plugin_pluginmanager_installplugin", dict(id=new_plugin.key, - version=new_plugin.version, - source=source, - source_type=source_type)) + + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, dict(id=new_plugin.key, + version=new_plugin.version, + source=source, + source_type=source_type)) result = dict(result=True, source=source, @@ -521,7 +525,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if origin is None: origin = plugin.origin[2] - pip_args = ["uninstall", "--yes", origin] + pip_args = ["--disable-pip-version-check", "uninstall", "--yes", origin] try: self._call_pip(pip_args) except: @@ -580,8 +584,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.reload_plugins() - self._event_bus.fire("plugin_pluginmanager_uninstallplugin", dict(id=plugin.key, - version=plugin.version)) + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN, dict(id=plugin.key, + version=plugin.version)) result = dict(result=True, needs_restart=needs_restart, @@ -683,7 +688,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=u"*", stream="message") @@ -723,8 +730,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif not plugin.enabled and plugin.key not in self._pending_enable: self._pending_enable.add(plugin.key) - self._event_bus.fire("plugin_pluginmanager_enableplugin", dict(id=plugin.key, - version=plugin.version)) + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, dict(id=plugin.key, + version=plugin.version)) def _mark_plugin_disabled(self, plugin, needs_restart=False): disabled_list = list(self._settings.global_get(["plugins", "_disabled"], @@ -743,8 +751,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif (plugin.enabled or plugin.forced_disabled or getattr(plugin, "safe_mode_victim", False)) and plugin.key not in self._pending_disable: self._pending_disable.add(plugin.key) - self._event_bus.fire("plugin_pluginmanager_disableplugin", dict(id=plugin.key, - version=plugin.version)) + # noinspection PyUnresolvedReferences + self._event_bus.fire(Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN, dict(id=plugin.key, + version=plugin.version)) def _fetch_all_data(self, do_async=False): def run(): @@ -862,7 +871,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.warn("Error while parsing date {!r} for plugin notice " @@ -888,7 +902,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, reconnect_hooks.extend(filter(lambda x: isinstance(x, basestring), result)) except: 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 @@ -961,6 +976,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, versions=notification.get("versions", []), important=notification.get("important", False)) + +def _register_custom_events(*args, **kwargs): + return ["install_plugin", "uninstall_plugin", "enable_plugin", "disable_plugin"] + + __plugin_name__ = "Plugin Manager" __plugin_author__ = "Gina Häußge" __plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html" @@ -974,5 +994,6 @@ def __plugin_load__(): global __plugin_hooks__ __plugin_hooks__ = { "octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize, - "octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types + "octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types, + "octoprint.events.register_custom_events": _register_custom_events } diff --git a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css index f34d4e990..ea7017ed7 100644 --- a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css +++ b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css @@ -1 +1 @@ -table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009} \ No newline at end of file +#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009} \ No newline at end of file diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 403aae500..8557c4a4b 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -31,7 +31,7 @@ $(function() { "name", [], [], - 5 + 0 ); self.repositoryplugins = new ItemListHelper( diff --git a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less index b828f87fa..39a7bb0a6 100644 --- a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less +++ b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less @@ -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; + } } } } diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 95e9d9077..0e4eef7ee 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -37,42 +37,33 @@

{{ _('Installed Plugins') }}

-
{{ _('Name') }} {{ _('Size') }} {{ _('Date') }}
- - - - - - - - - - - - -
{{ _('Name') }}{{ _('Actions') }}
-
()
-
-
 
-
- {{ _('Homepage') }} - - -   -
-
-  |  -
- -
+
API Key
diff --git a/src/octoprint/templates/dialogs/settings/api.jinja2 b/src/octoprint/templates/dialogs/settings/api.jinja2 index 1a00dc344..723fb3c81 100644 --- a/src/octoprint/templates/dialogs/settings/api.jinja2 +++ b/src/octoprint/templates/dialogs/settings/api.jinja2 @@ -2,14 +2,7 @@
-
-
-
-
-
diff --git a/src/octoprint/templates/dialogs/settings/appearance.jinja2 b/src/octoprint/templates/dialogs/settings/appearance.jinja2 index b20a91573..d1c05e30d 100644 --- a/src/octoprint/templates/dialogs/settings/appearance.jinja2 +++ b/src/octoprint/templates/dialogs/settings/appearance.jinja2 @@ -50,6 +50,13 @@
+
+
+ +
+
-
+
{{ _('Serial logging') }}
@@ -329,11 +337,19 @@ {{ _('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.') }}
+
+
+
- + + {{ _('Use this to specify commands that should never be sent to the printer. Just the G or M code, comma separated. Defaults to M0 and M1 since most firmware will block until a button on the controller has been pressed if it receives either of those two commands.') }} +
+
+
+ +
+ + {{ _('Use this to specify commands on which OctoPrint should pause the print job. Just the G or M code, comma separated. Defaults to M0, M1 and M25.') }}
@@ -374,11 +390,12 @@ {{ _('Disconnect from the printer') }}
diff --git a/src/octoprint/templates/dialogs/settings/webcam.jinja2 b/src/octoprint/templates/dialogs/settings/webcam.jinja2 index f53894271..ebec6fad6 100644 --- a/src/octoprint/templates/dialogs/settings/webcam.jinja2 +++ b/src/octoprint/templates/dialogs/settings/webcam.jinja2 @@ -1,6 +1,7 @@

{{ _('Webcam') }}

+ {% include "snippets/settings/webcam/webcamEnabled.jinja2" %} {% include "snippets/settings/webcam/webcamStreamUrl.jinja2" %} {% include "snippets/settings/webcam/webcamStreamRatio.jinja2" %} {% include "snippets/settings/webcam/webcamOrientation.jinja2" %} @@ -16,6 +17,7 @@

{{ _('Timelapse Recordings') }}

+ {% include "snippets/settings/webcam/timelapseEnabled.jinja2" %} {% include "snippets/settings/webcam/webcamSnapshotUrl.jinja2" %} {% include "snippets/settings/webcam/ffmpegPath.jinja2" %} {% include "snippets/settings/webcam/watermark.jinja2" %} diff --git a/src/octoprint/templates/index.jinja2 b/src/octoprint/templates/index.jinja2 index d18a41fca..35eb91090 100644 --- a/src/octoprint/templates/index.jinja2 +++ b/src/octoprint/templates/index.jinja2 @@ -117,7 +117,7 @@
+
  • -
  • {{ _('Only show machine code files') }}
  • -
  • {{ _('Only show model files') }}
  • + +
  • + + {% if enableSdSupport %}
  • {{ _('Only show files stored locally') }}
  • diff --git a/src/octoprint/templates/sidebar/state.jinja2 b/src/octoprint/templates/sidebar/state.jinja2 index 80e90da8b..30e4f9839 100644 --- a/src/octoprint/templates/sidebar/state.jinja2 +++ b/src/octoprint/templates/sidebar/state.jinja2 @@ -4,14 +4,16 @@ {{ _('User') }}:
    + {{ _('Timelapse') }}:
    +
    -{{ _('Approx. Total Print Time') }}:
    +{{ _('Approx. Total Print Time') }}:

    {{ _('Print Time') }}:
    -{{ _('Print Time Left') }}:
    +{{ _('Print Time Left') }}:
    {{ _('Printed') }}:
    diff --git a/src/octoprint/templates/snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2 b/src/octoprint/templates/snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2 index 763e3aeb2..eb5dcd65c 100644 --- a/src/octoprint/templates/snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2 +++ b/src/octoprint/templates/snippets/settings/printerprofiles/profileEditorBuildvolume.jinja2 @@ -23,6 +23,12 @@ +
    + +
    + +
    +
    diff --git a/src/octoprint/templates/snippets/settings/webcam/timelapseEnabled.jinja2 b/src/octoprint/templates/snippets/settings/webcam/timelapseEnabled.jinja2 new file mode 100644 index 000000000..e11a1a8ac --- /dev/null +++ b/src/octoprint/templates/snippets/settings/webcam/timelapseEnabled.jinja2 @@ -0,0 +1,7 @@ +
    +
    + +
    +
    diff --git a/src/octoprint/templates/snippets/settings/webcam/webcamEnabled.jinja2 b/src/octoprint/templates/snippets/settings/webcam/webcamEnabled.jinja2 new file mode 100644 index 000000000..e719d3d2f --- /dev/null +++ b/src/octoprint/templates/snippets/settings/webcam/webcamEnabled.jinja2 @@ -0,0 +1,7 @@ +
    +
    + +
    +
    diff --git a/src/octoprint/templates/tabs/control.jinja2 b/src/octoprint/templates/tabs/control.jinja2 index 14b672508..0e8f2b5ff 100644 --- a/src/octoprint/templates/tabs/control.jinja2 +++ b/src/octoprint/templates/tabs/control.jinja2 @@ -1,4 +1,4 @@ -{% if webcamStream %} +{% if enableWebcam %}
    @@ -7,7 +7,7 @@

    {{ _('Webcam stream not loaded') }}

    {{ _('It might not be configured correctly or require authentication. To have this fixed, get in touch with an administrator of this OctoPrint instance.') }}

    -

    {{ _('It might not be configured correctly or require authentication. You can change the URL of the stream under "Settings" > "Webcam & Timelapse" > "Stream URL". If you don\'t have a webcam just set the URL to an empty value.') }}

    +

    {{ _('It might not be configured correctly or require authentication. You can change the URL of the stream under "Settings" > "Webcam & Timelapse" > "Webcam" > "Stream URL". If you don\'t have a webcam you can also just disable webcam support there.') }}

    {{ _('Currently configured stream URL') }}:

    @@ -85,7 +85,7 @@
    -