diff --git a/CHANGELOG.md b/CHANGELOG.md index 963eb5425..560a28bbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,45 +1,11 @@ # OctoPrint Changelog -## 1.3.7rc4 (2018-04-04) - -### Bugfixes - - * [#2536](https://github.com/foosel/OctoPrint/issues/2536) - Fix a wrong state tracking when starting an SD print through the controller, causing a disconnect due to a timeout. - * [#2544](https://github.com/foosel/OctoPrint/issues/2544) - Fix an exception when connecting to the raw websocket at `/sockjs/websocket` (instead of `/sockjs///websocket`). - * [#2546](https://github.com/foosel/OctoPrint/issues/2546) - Fix the `PRINT_FAILED` event getting triggered twice on print failure due to disconnect - -([Commits](https://github.com/foosel/OctoPrint/compare/1.3.7rc3...1.3.7rc4)) - -## 1.3.7rc3 (2018-03-29) - -### Bugfixes - - * [#2524](https://github.com/foosel/OctoPrint/issues/2524) Ignore `wait` while job is on hold. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.3.7rc2...1.3.7rc3)) - -## 1.3.7rc2 (2018-03-23) - -### Bugfixes - - * [#1951](http://github.com/foosel/OctoPrint/issues/1951) - Fixed plugins being able to modify internal state data (e.g. progress, job), causing concurrent modification and resulting run time errors in the printer state processing. - * [#2494](https://github.com/foosel/OctoPrint/issues/2494) - Fixed `undefined` values not saving in the settings. - * [#2499](https://github.com/foosel/OctoPrint/issues/2499) - Fixed communication error notification lacking the actual error message. - * [#2501](https://github.com/foosel/OctoPrint/issues/2501) - Fixed a bug causing log downloads to fail with an HTTP 500 error. - * [#2506](https://github.com/foosel/OctoPrint/issues/2506) - Fixed `printer.get_current_data` and `printer.get_current_job` returning `frozendict` instead of `dict` instances, causing issues with plugins relying on being able to modify the returned data (e.g. [dattas/OctoPrint-DetailedProgress#26](https://github.com/dattas/OctoPrint-DetailedProgress/issues/26)). - * [#2508](https://github.com/foosel/OctoPrint/issues/2508) - Fixed HTTP 500 error on `/api/slicing` in case of an unconfigured slicer. - * Have `OctoPrintJsonEncoder` fall back to regular flask JSON encoder, otherwise we might not be able to serialize some data types we need to be able to serialize. - * Use `pkg_resources` to determine pip version during environment check instead of `import pip; pip.__version__` since the latter causes issues with pip version 9.0.2. In the same spirit make `pip.main` approach of calling `pip` in the PipCaller the last resort during auto detection, only after trying `pip` or `pip.exe` inside the same folder as the Python executable. - * Use `octoprint.util.monotonic_time` instead of `monotonic.monotonic` in comm layer. - * Fixed timelapse not stopping on print failure due to firmware error due to missing `PrintFailed` event. - -([Commits](https://github.com/foosel/OctoPrint/compare/1.3.7rc1...1.3.7rc2)) - -## 1.3.7rc1 (2018-03-19) +## 1.3.7 (2018-04-09) ### Improvements * [#324](https://github.com/foosel/OctoPrint/issues/324) & [#2414](https://github.com/foosel/OctoPrint/issues/2414) - Native support for the following [@ commands](http://docs.octoprint.org/en/maintenance/features/atcommands.html): `@pause` (pauses the print), `@resume` (resumes the print), `@cancel` or `@abort` (cancels the print). More commands can be added through the plugin hooks [`octoprint.comm.protocol.atcommand.*`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-atcommand-phase). + * [#1951](http://github.com/foosel/OctoPrint/issues/1951) - Fixed plugins being able to modify internal state data (e.g. progress, job), causing concurrent modification and resulting run time errors in the printer state processing. * [#2208](https://github.com/foosel/OctoPrint/issues/2208) - New plugin hook [`octoprint.comm.protocol.gcode.error`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-protocol-gcode-error) to allow plugins to override OctoPrint's handling of `Error:`/`!!` messages reported by the firmware. Can be used to "downgrade" errors that aren't actually fatal errors that make the printer halt. * [#2213](https://github.com/foosel/OctoPrint/issues/2213) - Made sure to prevent accidental configuration of a temperature cutoff value less than 1min for the temperature graph. * [#2250](https://github.com/foosel/OctoPrint/pull/2250) - Added [`octoprint.util.ResettableTimer`](http://docs.octoprint.org/en/maintenance/modules/util.html#octoprint.util.ResettableTimer) helper class. @@ -50,6 +16,7 @@ * Firmware must send a "File opened: ..." message on start of the print * Firmware must respond to an immediately sent `M27` with `SD printing byte /` * Firmware must stay responsive during ongoing print to allow for regular M27 polls (or push those automatically) or M25 to pause/cancel the print through OctoPrint. + * Firmware must send `Done printing file` or respond to `M27` with `Not SD printing` when SD printing finishes (either due to being done or to having been cancelled by the user). * [#2362](https://github.com/foosel/OctoPrint/issues/2362) - Added option to configure timelapse snapshot timeout. * [#2367](https://github.com/foosel/OctoPrint/issues/2367) - Added support for `//action:cancel` action command. * [#2378](https://github.com/foosel/OctoPrint/issues/2378) - Made GCODE viewer gracefully handle GCODE subcodes. @@ -104,11 +71,37 @@ * [#2426](https://github.com/foosel/OctoPrint/issues/2426) - Made resend logging to `octoprint.log` unicode safe * [#2442](https://github.com/foosel/OctoPrint/issues/2442) - Don't even import disabled plugins, use a dummy entry for them just like for backlisted plugins. More resilience against misbehaving plugins. * [#2461](https://github.com/foosel/OctoPrint/issues/2461) - Fixed OctoPrint not properly disconnecting in case of a firmware error. + * [#2494](https://github.com/foosel/OctoPrint/issues/2494) - Fixed `undefined` values not saving in the settings. + * [#2499](https://github.com/foosel/OctoPrint/issues/2499) (regression) - Fixed communication error notification lacking the actual error message. + * [#2501](https://github.com/foosel/OctoPrint/issues/2501) (regression) - Fixed a bug causing log downloads to fail with an HTTP 500 error. + * [#2506](https://github.com/foosel/OctoPrint/issues/2506) (regression) - Fixed `printer.get_current_data` and `printer.get_current_job` returning `frozendict` instead of `dict` instances, causing issues with plugins relying on being able to modify the returned data (e.g. [dattas/OctoPrint-DetailedProgress#26](https://github.com/dattas/OctoPrint-DetailedProgress/issues/26)). + * [#2508](https://github.com/foosel/OctoPrint/issues/2508) (regression) - Fixed HTTP 500 error on `/api/slicing` in case of an unconfigured slicer. + * [#2524](https://github.com/foosel/OctoPrint/issues/2524) - Ignore `wait` while job is on hold. + * [#2536](https://github.com/foosel/OctoPrint/issues/2536) - Fix a wrong state tracking when starting an SD print through the controller, causing a disconnect due to a timeout. + * [#2544](https://github.com/foosel/OctoPrint/issues/2544) (regression) - Fix an exception when connecting to the raw websocket at `/sockjs/websocket` (instead of `/sockjs///websocket`). + * [#2546](https://github.com/foosel/OctoPrint/issues/2546) (regression) - Fix the `PRINT_FAILED` event getting triggered twice on print failure due to disconnect + * Use `pkg_resources` to determine pip version during environment check instead of `import pip; pip.__version__` since the latter causes issues with pip version 9.0.2. In the same spirit make `pip.main` approach of calling `pip` in the PipCaller the last resort during auto detection, only after trying `pip` or `pip.exe` inside the same folder as the Python executable. + * Use `octoprint.util.monotonic_time` instead of `monotonic.monotonic` in comm layer. + * Fixed timelapse not stopping on print failure due to firmware error due to missing `PrintFailed` event. * Announcement Plugin: Fixed a missing line break in case of more than three announcements in a notification. * Docs: Documentation for printer profile related bits and pieces * Docs: Various fixes of typos and grammar. + * Have `OctoPrintJsonEncoder` fall back to regular flask JSON encoder, otherwise we might not be able to serialize some data types we need to be able to serialize. (regression) -([Commits](https://github.com/foosel/OctoPrint/compare/1.3.6...1.3.7rc1)) +### Known bugs + + * [#2547](https://github.com/foosel/OctoPrint/issues/2547) - Error during processing of afterPrintJobDone script will trigger PRINT_FAILED event even though PRINT_DONE event was already triggered + +### More Information + + * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.6...1.3.7) + * Release Candidates: + * [1.3.7rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc1) + * [1.3.7rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc2) + * [1.3.7rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc3) + * [1.3.7rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.7rc4) + * A special **Thank you!** to everyone who reported back on these release candidates this time: + [aaronkeck](https://github.com/aaronkeck), [akurz42](https://github.com/akurz42), [andrivet](https://github.com/andrivet), [anthonyst91](https://github.com/anthonyst91), [arhi](https://github.com/arhi), [b-morgan](https://github.com/b-morgan), [BryanSmithDev](https://github.com/BryanSmithDev), [chippypilot](https://github.com/chippypilot), [ChrisHeerschap](https://github.com/ChrisHeerschap), [Crowlord](https://github.com/Crowlord), [dforsi](https://github.com/dforsi), [drdelaney](https://github.com/drdelaney), [FormerLurker](https://github.com/FormerLurker), [goeland86](https://github.com/goeland86), [inspiredbylife](https://github.com/inspiredbylife), [jbjones27](https://github.com/jbjones27), [jesasi](https://github.com/jesasi), [jneilliii](https://github.com/jneilliii), [JohnOCFII](https://github.com/JohnOCFII), [kantlivelong](https://github.com/kantlivelong), [lnx13](https://github.com/lnx13), [makaper](https://github.com/makaper), [markwal](https://github.com/markwal), [MiquelAdell](https://discourse.octoprint.org/u/MiquelAdell), [ml0w](https://github.com/ml0w), [mmotley999](https://github.com/mmotley999), [mrhanman](https://github.com/mrhanman), [SCiunczyk](https://github.com/SCiunczyk), [tdub415](https://github.com/tdub415), [tedder42](https://discourse.octoprint.org/u/tedder42), [thatjoshguy](https://github.com/thatjoshguy), [wescrockett](https://github.com/wescrockett) ## 1.3.6 (2017-12-12) diff --git a/SUPPORTERS.md b/SUPPORTERS.md index 1de21d611..6159d8f79 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -23,6 +23,7 @@ thanks to everyone who contributed! * günter weber * James Seigel * Jeff Moe + * Jeff Renfer * Jefferson Hunt * Jeremiah Avery * Josh Daniels @@ -54,4 +55,4 @@ thanks to everyone who contributed! * Thomas Hatley * Trent Shumay -and 1217 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! \ No newline at end of file +and 1233 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! \ No newline at end of file diff --git a/docs/api/files.rst b/docs/api/files.rst index b13123036..23583d59c 100644 --- a/docs/api/files.rst +++ b/docs/api/files.rst @@ -472,7 +472,7 @@ Upload file or create folder :form select: Whether to select the file directly after upload (``true``) or not (``false``). Optional, defaults to ``false``. Ignored when creating a folder. :form print: Whether to start printing the file directly after upload (``true``) or not (``false``). If set, ``select`` - is implicitely ``true`` as well. Optional, defaults to ``false``. Ignored when creating a folder. + is implicitly ``true`` as well. Optional, defaults to ``false``. Ignored when creating a folder. :form userdata: [Optional] An optional string that if specified will be interpreted as JSON and then saved along with the file as metadata (metadata key ``userdata``). Ignored when creating a folder. :form foldername: The name of the folder to create. Ignored when uploading a file. diff --git a/docs/api/printer.rst b/docs/api/printer.rst index 1409bf300..5d7c8ebde 100644 --- a/docs/api/printer.rst +++ b/docs/api/printer.rst @@ -37,7 +37,7 @@ Besides that, OctoPrint also provides a :ref:`full state report of the printer < OctoPrint's internal webserver is single threaded and can only handle one request at a time. This is not a problem generally since asynchronous programming allows to just have one request which is waiting for data from a long running backend operation to sleep while handling other requests. The internal framework - used for providing the REST API though, Flask, is based on WSGI, which is synchrounous in nature. This means + used for providing the REST API though, Flask, is based on WSGI, which is synchronous in nature. This means that it is impossible to wait in a non blocking wait while handling a request on the REST API. So in order to return the response of a command sent to the printer, the single thread of the webserver would have to be blocked by the API while the response wasn't available yet. Which in turn would mean that the whole web server would diff --git a/docs/api/printerprofiles.rst b/docs/api/printerprofiles.rst index 835399d5c..8db1b51ae 100644 --- a/docs/api/printerprofiles.rst +++ b/docs/api/printerprofiles.rst @@ -581,7 +581,7 @@ Profile * - ``axes`` - 0..1 - Object - - Description of the printer's axes properties, one entry each for ``x``, ``y``, ``z`` and ``e`` holding maxium speed + - Description of the printer's axes properties, one entry each for ``x``, ``y``, ``z`` and ``e`` holding maximum speed and whether this axis is inverted or not. * - ``axes.{axis}.speed`` - 0..1 diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 41e0fae69..79795f021 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -151,7 +151,7 @@ appearance or to modify the order and presence of the various UI components: # order of settings, if settings plugins are registered gets extended internally by # section_plugins and all settings plugins - settings + settings: - section_printer - serial - printerprofiles @@ -454,7 +454,7 @@ the estimation of the left print time during an active job utilizes this section .. code-block:: yaml estimation: - # Parameters for the print time estmation during an ongoing print job + # Parameters for the print time estimation during an ongoing print job printTime: # Until which percentage to do a weighted mixture of statistical duration (analysis or # past prints) with the result from the calculated estimate if that's already available. diff --git a/docs/events/index.rst b/docs/events/index.rst index 193574247..a97e7e385 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -207,8 +207,8 @@ FolderAdded Payload: * ``storage``: the storage's identifier - * ``path``: the folders's path within its storage location - * ``name``: the folders's name + * ``path``: the folder's path within its storage location + * ``name``: the folder's name .. note:: @@ -220,8 +220,8 @@ FolderRemoved Payload: * ``storage``: the storage's identifier - * ``path``: the folders's path within its storage location - * ``name``: the folders's name + * ``path``: the folder's path within its storage location + * ``name``: the folder's name .. note:: diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index 65732e2fd..4fb891eb4 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -75,7 +75,7 @@ All GCODE scripts have access to the following template variables through the te * ``last_temperature``: Last actual and target temperature reported for all available tools and if available the heated bed. This is a dictionary of key-value pairs. The keys are the indices of the available tools (``0``, ``1``, ...) and ``b`` for the heated bed. The values are a dictionary consisting of ``actual`` and ``target`` keys mapped - to the corresponding temperature in degrees celsius. Note that not all tools your printer has must necessarily be + to the corresponding temperature in degrees Celsius. Note that not all tools your printer has must necessarily be present here, neither must the heated bed - it depends on whether OctoPrint has values for a tool or the bed. Also note that ``actual`` and ``target`` might be ``None``. * ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type`` diff --git a/docs/images/bundledplugins-printer_safety_check-example.png b/docs/images/bundledplugins-printer_safety_check-example.png new file mode 100644 index 000000000..c6bac3a8e Binary files /dev/null and b/docs/images/bundledplugins-printer_safety_check-example.png differ diff --git a/docs/jsclientlib/base.rst b/docs/jsclientlib/base.rst index 618299fd1..63833f0dc 100644 --- a/docs/jsclientlib/base.rst +++ b/docs/jsclientlib/base.rst @@ -417,7 +417,7 @@ Creates a custom exception class. ``name`` may be either a function in which case it will be used as constructor for the new exception class, or a string, in which case a constructor with proper - ``name``, ``message`` and ``stack`` attributes will be created. The class hierarchy will be propery + ``name``, ``message`` and ``stack`` attributes will be created. The class hierarchy will be properly setup to subclass ``Error``. **Example:** diff --git a/docs/jsclientlib/files.rst b/docs/jsclientlib/files.rst index 9c4d8233a..5ecf5ea38 100644 --- a/docs/jsclientlib/files.rst +++ b/docs/jsclientlib/files.rst @@ -189,7 +189,7 @@ A boolean value, specifies whether to immediately start printing the file after the upload completes (true) or not (false, default) userdata - An optional object or a serialized JSON string of additional user supplised data to associate with + An optional object or a serialized JSON string of additional user supplied data to associate with the uploaded file. See :ref:`Upload file or create folder ` for more details on the file upload API and diff --git a/docs/jsclientlib/socket.rst b/docs/jsclientlib/socket.rst index 844b845a5..6da88a1ee 100644 --- a/docs/jsclientlib/socket.rst +++ b/docs/jsclientlib/socket.rst @@ -85,7 +85,7 @@ .. js:function:: OctoPrintClient.socket.onRateTooHigh(measured, maximum) Called by the socket client when the last measured round trip time was higher than the - current upper procesisng limit, indicating that the messages are now processed slower than + current upper processing limit, indicating that the messages are now processed slower than the current rate requires and a slower rate might be necessary. Can be overwritten with custom handler methods. The default implementation will call diff --git a/docs/plugins/gettingstarted.rst b/docs/plugins/gettingstarted.rst index c26686a41..ac43e92ad 100644 --- a/docs/plugins/gettingstarted.rst +++ b/docs/plugins/gettingstarted.rst @@ -410,8 +410,8 @@ Now look at that! Settings Galore: How to make parts of your plugin user adjustable ----------------------------------------------------------------- -Remember that Wikipedia link we added to our little link in the navigation bar? It links to the english Wikipedia. But -what if we want to allow our users to adjust that according to their wishes, e.g. to link to the german language node +Remember that Wikipedia link we added to our little link in the navigation bar? It links to the English Wikipedia. But +what if we want to allow our users to adjust that according to their wishes, e.g. to link to the German language node about "Hello World" programs instead? To allow your users to customized the behaviour of your plugin you'll need to implement the :class:`~octoprint.plugin.SettingsPlugin` @@ -509,7 +509,7 @@ section doesn't yet exist in the file, create it): # [...] Restart OctoPrint. Not only should the URL displayed in the log file have changed, but also the link should now (after -a proper shift-reload) point to the german Wikipedia node about "Hello World" programs:: +a proper shift-reload) point to the German Wikipedia node about "Hello World" programs:: 2015-01-30 11:47:18,634 - octoprint.plugins.helloworld - INFO - Hello World! (more: https://de.wikipedia.org/wiki/Hallo-Welt-Programm) diff --git a/docs/plugins/viewmodels.rst b/docs/plugins/viewmodels.rst index 2b97a4df1..09aa3a846 100644 --- a/docs/plugins/viewmodels.rst +++ b/docs/plugins/viewmodels.rst @@ -56,9 +56,9 @@ Example: // more of your view model's implementation } - // we don't explicitely declare a name property here + // we don't explicitly declare a name property here // our view model will be registered under "myCustomViewModel" (implicit - // name derived from contructor name) and "yourCustomViewModel" (explicitely + // name derived from constructor name) and "yourCustomViewModel" (explicitly // provided as additional name) OCTOPRINT_VIEWMODELS.push({ construct: MyCustomViewModel, diff --git a/setup.py b/setup.py index d05daf619..b78d24097 100644 --- a/setup.py +++ b/setup.py @@ -20,7 +20,8 @@ INSTALL_REQUIRES = [ "Jinja2>=2.8,<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 - "sockjs-tornado>=1.0.3,<1.1", + #"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a + # vendored one "PyYAML>=3.12,<3.13", "Flask-Login>=0.4,<0.5", "Flask-Principal>=0.4,<0.5", diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index de1b43072..51d56a575 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -184,7 +184,7 @@ class StorageInterface(object): def copy_folder(self, source, destination): """ - Copys the folder ``source`` to ``destination`` + Copies the folder ``source`` to ``destination`` :param string source: path to the source folder :param string destination: path to destination @@ -233,7 +233,7 @@ class StorageInterface(object): def copy_file(self, source, destination): """ - Copys the file ``source`` to ``destination`` + Copies the file ``source`` to ``destination`` :param string source: path to the source file :param string destination: path to destination diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index 597a56557..0f07e84d3 100644 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ b/src/octoprint/plugins/printer_safety_check/__init__.py @@ -23,8 +23,26 @@ Learn more at https://faq.octoprint.org/warning-{warning_type} """ +# Anet A8 +ANETA8_M115_TEST = lambda name, data: name and name.lower().startswith("anet_a8_") + +# Anycubic MEGA +ANYCUBIC_AUTHOR1 = "| Author: (Jolly, xxxxxxxx.CO.)".lower() +ANYCUBIC_AUTHOR2 = "| Author: (**Jolly, xxxxxxxx.CO.**)".lower() +ANYCUBIC_RECEIVED_TEST = lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower() or ANYCUBIC_AUTHOR2 in line.lower()) + +# Creality CR-10s +CR10S_AUTHOR = " | Author: (CR-10Slanguage)".lower() +CR10S_RECEIVED_TEST = lambda line: line and CR10S_AUTHOR in line.lower() + +# Malyan M200 aka Monoprice Select Mini +MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200" + SAFETY_CHECKS = { - "firmware-unsafe": (lambda name, data: name and name.lower().startswith("anet_a8_"),) + "firmware-unsafe": dict(m115=(ANETA8_M115_TEST, MALYANM200_M115_TEST), + received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST), + message=u"Your printer's firmware is known to lack mandatory safety features (e.g. " \ + u"thermal runaway protection). This is a fire risk.") } class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, @@ -35,6 +53,7 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, # noinspection PyMissingConstructor def __init__(self): self._warnings = dict() + self._scan_received = True ##~~ TemplatePlugin API @@ -58,7 +77,8 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, def on_event(self, event, payload): if event == Events.FIRMWARE_DATA: - self._analyze_firmware_data(payload.get("name"), payload.get("data")) + self._run_checks("m115", payload.get("name"), payload.get("data")) + self._scan_received = False elif event == Events.DISCONNECTED: self._reset_warnings() @@ -69,6 +89,13 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, return flask.make_response("Insufficient rights", 403) return flask.jsonify(self._warnings) + ##~~ GCODE received hook handler + + def on_gcode_received(self, comm_instance, line, *args, **kwargs): + if self._scan_received: + self._run_checks("received", line) + return line + # Additional permissions hook def get_additional_permissions(self): @@ -81,21 +108,27 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, ##~~ Helpers - def _analyze_firmware_data(self, name, data): + def _run_checks(self, check_type, *args, **kwargs): changes = False - for warning_type, checks in SAFETY_CHECKS.items(): - if any(x(name, data) for x in checks): - message = u"Your printer's firmware is known to lack mandatory safety features (e.g. " \ - u"thermal runaway protection). This is a fire risk." - self._log_to_terminal(TERMINAL_SAFETY_WARNING.format(message="\n".join(textwrap.wrap(message, 75)), - warning_type=warning_type)) - self._warnings[warning_type] = message + for warning_type, check_data in SAFETY_CHECKS.items(): + checks = check_data.get(check_type) + message = check_data.get("message") + if not checks or not message: + continue + + if any(x(*args, **kwargs) for x in checks): + self._register_warning(warning_type, message) changes = True if changes: self._ping_clients() + def _register_warning(self, warning_type, message): + self._log_to_terminal(TERMINAL_SAFETY_WARNING.format(message="\n".join(textwrap.wrap(message, 75)), + warning_type=warning_type)) + self._warnings[warning_type] = message + def _reset_warnings(self): self._warnings.clear() self._ping_clients() @@ -118,6 +151,7 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will n __plugin_license__ = "AGPLv3" __plugin_implementation__ = PrinterSafetyCheckPlugin() __plugin_hooks__ = { + "octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received, "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions } diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 76d92fbb9..9a9c60f5e 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -6,7 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import uuid -from sockjs.tornado import SockJSRouter +from octoprint.vendor.sockjs.tornado import SockJSRouter from flask import Flask, g, request, session, Blueprint, Request, Response, current_app from flask_login import LoginManager, current_user, session_protected, user_logged_out from flask_principal import Principal, Permission, RoleNeed, identity_loaded, identity_changed, UserNeed, Identity, AnonymousIdentity @@ -90,6 +90,8 @@ import octoprint.events as events import octoprint.plugin import octoprint.timelapse import octoprint._version +import octoprint.util +import octoprint.util.net import octoprint.filemanager.storage import octoprint.filemanager.analysis import octoprint.slicing @@ -178,7 +180,7 @@ def unauthorized_user(): class Server(object): def __init__(self, settings=None, plugin_manager=None, connectivity_checker=None, environment_detector=None, - event_manager=None, host="0.0.0.0", port=5000, debug=False, safe_mode=False, allow_root=False, + event_manager=None, host=None, port=None, debug=False, safe_mode=False, allow_root=False, octoprint_daemon=None): self._settings = settings self._plugin_manager = plugin_manager @@ -239,12 +241,29 @@ class Server(object): debug = self._debug safe_mode = self._safe_mode + if self._host is None: + host = self._settings.get(["server", "host"]) + if host is None: + if octoprint.util.net.HAS_V6: + host = "::" + else: + host = "0.0.0.0" + + self._host = host + + if ":" in self._host and not octoprint.util.net.HAS_V6: + raise RuntimeError("IPv6 host address {!r} configured but system doesn't support IPv6".format(self._host)) + + if self._port is None: + self._port = self._settings.getInt(["server", "port"]) + if self._port is None: + self._port = 5000 + self._logger = logging.getLogger(__name__) self._setup_heartbeat_logging() pluginManager = self._plugin_manager # monkey patch some stuff - util.sockjs.fix_tornado5_compatibility() util.tornado.fix_json_encode() util.flask.enable_additional_translations(additional_folders=[self._settings.getBaseFolder("translations")]) @@ -524,13 +543,8 @@ class Server(object): ## Tornado initialization starts here - if self._host is None: - self._host = self._settings.get(["server", "host"]) - if self._port is None: - self._port = self._settings.getInt(["server", "port"]) - ioloop = IOLoop() - ioloop.install() + ioloop.make_current() self._router = SockJSRouter(self._create_socket_connection, "/sockjs", session_kls=util.sockjs.ThreadSafeSession) @@ -686,7 +700,9 @@ class Server(object): default_max_body_size=self._settings.getInt(["server", "maxSize"]), xheaders=True, trusted_downstream=trusted_downstream) - self._server.listen(self._port, address=self._host) + self._server.listen(self._port, address=self._host if self._host != "::" else None) # special case - tornado + # only listens on v4 & v6 + # if we use None as address ### From now on it's ok to launch subprocesses again @@ -731,7 +747,8 @@ class Server(object): # prepare our after startup function def on_after_startup(): - self._logger.info("Listening on http://%s:%d" % (self._host, self._port)) + self._logger.info("Listening on http://{}:{}".format(self._host if not ":" in self._host else "[" + self._host + "]", + self._port)) if safe_mode and self._settings.getBoolean(["server", "startOnceInSafeMode"]): self._logger.info("Server started successfully in safe mode as requested from config, removing flag") @@ -803,7 +820,9 @@ class Server(object): except (KeyboardInterrupt, SystemExit): pass except: - self._logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!") + self._logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report " + "this including reproduction steps, octoprint.log and the stacktrace below in " + "OctoPrint's bugtracker. Thanks!") self._logger.exception("Stacktrace follows:") def _create_socket_connection(self, session): @@ -1541,15 +1560,10 @@ class Server(object): import BaseHTTPServer import SimpleHTTPServer import threading + import socket host = self._host port = self._port - if host is None: - host = self._settings.get(["server", "host"]) - if port is None: - port = self._settings.getInt(["server", "port"]) - - self._logger.debug("Starting intermediary server on {}:{}".format(host, port)) class IntermediaryServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def __init__(self, rules=None, *args, **kwargs): @@ -1606,9 +1620,27 @@ class Server(object): rules = map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules)) - self._intermediary_server = BaseHTTPServer.HTTPServer((host, port), - lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs), - bind_and_activate=False) + class HTTPServerV6(BaseHTTPServer.HTTPServer): + address_family = socket.AF_INET6 + + def __init__(self, *args, **kwargs): + BaseHTTPServer.HTTPServer.__init__(self, *args, **kwargs) + + # make sure to enable dual stack mode, otherwise the socket might only listen on IPv6 + self.socket.setsockopt(octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 0) + + if ":" in host: + # v6 + ServerClass = HTTPServerV6 + else: + # v4 + ServerClass = BaseHTTPServer.HTTPServer + + self._logger.debug("Starting intermediary server on http://{}:{}".format(host if not ":" in host else "[" + host + "]", port)) + + self._intermediary_server = ServerClass((host, port), + lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs), + bind_and_activate=False) # if possible, make sure our socket's port descriptor isn't handed over to subprocesses from octoprint.util.platform import set_close_exec diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index f05269e4d..d74b158bf 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -7,10 +7,10 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging import threading -import sockjs.tornado -import sockjs.tornado.session -import sockjs.tornado.proto -import sockjs.tornado.util +import octoprint.vendor.sockjs.tornado +import octoprint.vendor.sockjs.tornado.session +import octoprint.vendor.sockjs.tornado.proto +import octoprint.vendor.sockjs.tornado.util import time import octoprint.timelapse @@ -30,103 +30,9 @@ import wrapt import json -def fix_tornado5_compatibility(): - """ - Monkey patches sockjs tornado dependency to fix tornado 5.x compatibility - - See https://github.com/mrjoes/sockjs-tornado/issues/113 for reason. - - We need to first patch StatsCollector since that also gets used by SockJSRouter. - """ - - import sockjs.tornado.router - import sockjs.tornado.stats - from tornado import ioloop, version_info - - def fixed_stats_init(self, io_loop): - ### Copied from sockjs.tornado.stats.StatsCollector.__init__ - - # Sessions - self.sess_active = 0 - - # Avoid circular reference - self.sess_transports = dict() - - # Connections - self.conn_active = 0 - self.conn_ps = sockjs.tornado.stats.MovingAverage() - - # Packets - self.pack_sent_ps = sockjs.tornado.stats.MovingAverage() - self.pack_recv_ps = sockjs.tornado.stats.MovingAverage() - - self._callback = ioloop.PeriodicCallback(self._update, - 1000) - self._callback.start() - - sockjs.tornado.stats.StatsCollector.__init__ = fixed_stats_init - - def fixed_router_init(self, connection, prefix="", user_settings=dict(), io_loop=None, session_kls=None): - ### Copied from sockjs.tornado.router.SockJSRouter.__init__ - - # TODO: Version check - if version_info[0] < 2: - raise Exception('sockjs-tornado requires Tornado 2.0 or higher.') - - # Store connection class - self._connection = connection - - # Initialize io_loop - self.io_loop = io_loop or ioloop.IOLoop.instance() - - # Settings - self.settings = sockjs.tornado.router.DEFAULT_SETTINGS.copy() - if user_settings: - self.settings.update(user_settings) - - self.websockets_enabled = 'websocket' not in self.settings['disabled_transports'] - self.cookie_needed = self.settings['jsessionid'] - - # Sessions - self._session_kls = session_kls if session_kls else sockjs.tornado.router.session.Session - self._sessions = sockjs.tornado.router.sessioncontainer.SessionContainer() - - check_interval = self.settings['session_check_interval'] * 1000 - self._sessions_cleanup = ioloop.PeriodicCallback(self._sessions.expire, - check_interval) - self._sessions_cleanup.start() - - # Stats - self.stats = sockjs.tornado.stats.StatsCollector(self.io_loop) - - # Initialize URLs - base = prefix + r'/[^/.]+/(?P[^/.]+)' - - # Generate global handler URLs - self._transport_urls = [('%s/%s$' % (base, p[0]), p[1], dict(server=self)) - for p in sockjs.tornado.router.GLOBAL_HANDLERS] - - for k, v in sockjs.tornado.router.TRANSPORTS.items(): - if k in self.settings['disabled_transports']: - continue - - # Only version 1 is supported - self._transport_urls.append( - (r'%s/%s$' % (base, k), - v, - dict(server=self)) - ) - - # Generate static URLs - self._transport_urls.extend([('%s%s' % (prefix, k), v, dict(server=self)) - for k, v in sockjs.tornado.router.STATIC_HANDLERS.items()]) - - sockjs.tornado.router.SockJSRouter.__init__ = fixed_router_init - - -class ThreadSafeSession(sockjs.tornado.session.Session): +class ThreadSafeSession(octoprint.vendor.sockjs.tornado.session.Session): def __init__(self, conn, server, session_id, expiry=None): - sockjs.tornado.session.Session.__init__(self, conn, server, session_id, expiry=expiry) + octoprint.vendor.sockjs.tornado.session.Session.__init__(self, conn, server, session_id, expiry=expiry) def set_handler(self, handler, start_heartbeat=True): if getattr(handler, "__orig_send_pack", None) is None: @@ -140,10 +46,10 @@ class ThreadSafeSession(sockjs.tornado.session.Session): handler.send_pack = send_pack setattr(handler, "__orig_send_pack", orig_send_pack) - return sockjs.tornado.session.Session.set_handler(self, handler, start_heartbeat=start_heartbeat) + return octoprint.vendor.sockjs.tornado.session.Session.set_handler(self, handler, start_heartbeat=start_heartbeat) def remove_handler(self, handler): - result = sockjs.tornado.session.Session.remove_handler(self, handler) + result = octoprint.vendor.sockjs.tornado.session.Session.remove_handler(self, handler) if getattr(handler, "__orig_send_pack", None) is not None: handler.send_pack = getattr(handler, "__orig_send_pack") @@ -154,13 +60,13 @@ class ThreadSafeSession(sockjs.tornado.session.Session): class JsonEncodingSessionWrapper(wrapt.ObjectProxy): def send_message(self, msg, stats=True, binary=False): - self.send_jsonified(json.dumps(sockjs.tornado.util.bytes_to_str(msg), + self.send_jsonified(json.dumps(octoprint.vendor.sockjs.tornado.util.bytes_to_str(msg), separators=(',', ':'), default=JsonEncoding.encode), stats) -class PrinterStateConnection(sockjs.tornado.SockJSConnection, +class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback, LoginStatusListener): @@ -169,9 +75,10 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, "*": [Permissions.STATUS]} def __init__(self, printer, fileManager, analysisQueue, userManager, groupManager, eventManager, pluginManager, session): - if isinstance(session, sockjs.tornado.session.Session): + if isinstance(session, octoprint.vendor.sockjs.tornado.session.Session): session = JsonEncodingSessionWrapper(session) - sockjs.tornado.SockJSConnection.__init__(self, session) + + octoprint.vendor.sockjs.tornado.SockJSConnection.__init__(self, session) self._logger = logging.getLogger(__name__) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index a8f6fb3c6..94edb1ef7 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -147,7 +147,7 @@ default_settings = { "triggerOkForM29": True }, "server": { - "host": "0.0.0.0", + "host": None, "port": 5000, "firstRun": True, "startOnceInSafeMode": False, @@ -407,7 +407,7 @@ default_settings = { "resetLines": ['start', 'Marlin: Virtual Marlin!', '\x80', 'SD card ok'], "preparedOks": [], "okFormatString": "ok", - "m115FormatString": "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0", + "m115FormatString": "FIRMWARE_NAME:{firmware_name} PROTOCOL_VERSION:1.0", "m115ReportCapabilities": False, "capabilities": { "AUTOREPORT_TEMP": True, diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 98a1e5741..7517ad1e2 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -27,6 +27,7 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor }; self.updateItems = function(items) { + if (items === undefined) items = []; self.allItems = items; self.allSize(items.length); self._updateItems(); diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index 2104e9c04..b6dabafae 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -284,6 +284,20 @@ $(function() { self.allItems(files); + // Sanity check file list - see #2572 + var nonrecursive = false; + _.each(files, function(file) { + if (file.type === "folder" && file.children === undefined) { + nonrecursive = true; + } + }); + if (nonrecursive) { + log.error("At least one folder doesn't have a 'children' element defined. That means the file list request " + + "wasn't actually made with 'recursive=true' in the query.\n\n" + + "This can happen on wrong reverse proxy configs that " + + "swallow up query parameters, see https://github.com/foosel/OctoPrint/issues/2572"); + } + if (!switchToPath) { var currentPath = self.currentPath(); if (currentPath === undefined) { @@ -326,6 +340,11 @@ $(function() { }; self.changeFolder = function(data) { + if (data.children === undefined) { + log.error("Can't switch to folder '" + data.path + "', no children available"); + return; + } + self.currentPath(data.path); self.listHelper.updateItems(data.children); self.highlightCurrentFilename(); diff --git a/src/octoprint/static/js/lib/sockjs.js b/src/octoprint/static/js/lib/sockjs.js index f168d5f7b..dff4b42c7 100644 --- a/src/octoprint/static/js/lib/sockjs.js +++ b/src/octoprint/static/js/lib/sockjs.js @@ -817,8 +817,8 @@ SockJS.prototype._connect = function() { } } - // calculate timeout based on RTO and round trips. Default to 5s - var timeoutMs = (this._rto * Transport.roundTrips) || 5000; + // calculate timeout based on RTO and round trips, compensate for potential nagle. Default to 5s. + var timeoutMs = (this._rto * Transport.roundTrips + 300) || 5000; this._transportTimeoutId = setTimeout(this._transportTimeout.bind(this), timeoutMs); debug('using timeout', timeoutMs); diff --git a/src/octoprint/templates/dialogs/forgot_password.jinja2 b/src/octoprint/templates/dialogs/forgot_password.jinja2 deleted file mode 100644 index 6f5735449..000000000 --- a/src/octoprint/templates/dialogs/forgot_password.jinja2 +++ /dev/null @@ -1,12 +0,0 @@ - diff --git a/src/octoprint/templates/dialogs/settings/api.jinja2 b/src/octoprint/templates/dialogs/settings/api.jinja2 index 5bd1e9f77..ed6228c78 100644 --- a/src/octoprint/templates/dialogs/settings/api.jinja2 +++ b/src/octoprint/templates/dialogs/settings/api.jinja2 @@ -26,8 +26,8 @@
- - + +
{{ _('Please note that changes to the API key are applied immediately, without having to "Save" first.') }}
diff --git a/src/octoprint/templates/dialogs/usersettings/access.jinja2 b/src/octoprint/templates/dialogs/usersettings/access.jinja2 index 3a1b07a3a..f134b4e01 100644 --- a/src/octoprint/templates/dialogs/usersettings/access.jinja2 +++ b/src/octoprint/templates/dialogs/usersettings/access.jinja2 @@ -25,9 +25,9 @@
- + - +
{{ _('Please note that changes to the API key are applied immediately, without having to "Confirm" first.') }}
diff --git a/src/octoprint/templates/navbar/login.jinja2 b/src/octoprint/templates/navbar/login.jinja2 index c3bcdade0..eacc9d108 100644 --- a/src/octoprint/templates/navbar/login.jinja2 +++ b/src/octoprint/templates/navbar/login.jinja2 @@ -6,7 +6,7 @@
- {{ _('Forgot password?') }} + {{ _('Forgot password?') }}