Merge branch 'devel' into dev/permission

# Conflicts:
#	src/octoprint/plugins/printer_safety_check/__init__.py
#	src/octoprint/server/__init__.py
#	src/octoprint/server/util/sockjs.py
This commit is contained in:
Gina Häußge committed 2018-04-12 16:37:27 +02:00
commit 08bfae216c
58 files changed
+2556 -227

No files matched your search

+30 -37
View File
@@ -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/<server_id>/<session_id>/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 <current>/<total>`
* 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/<server_id>/<session_id>/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)
+2 -1
View File
@@ -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)!
and 1233 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+2 -2
View File
@@ -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.
+4 -4
View File
@@ -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::
+1 -1
View File
@@ -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``
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

+1 -1
View File
@@ -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:**
+1 -1
View File
@@ -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 <sec-api-fileops-uploadfile>` for more details on the file upload API and
+1 -1
View File
@@ -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
+3 -3
View File
@@ -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)
+2 -2
View File
@@ -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,
+2 -1
View File
@@ -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",
+2 -2
View File
@@ -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
@@ -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
}
+53 -21
View File
@@ -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
+13 -106
View File
@@ -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<session_id>[^/.]+)'
# 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__)
+2 -2
View File
@@ -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,
+1
View File
@@ -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();
@@ -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();
+2 -2
View File
@@ -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);
@@ -1,12 +0,0 @@
<div id="forgot_password_dialog" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="forgot_password_dialog_label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h3 id="forgot_password_dialog_label">{{ _('Forgot password?') }}</h3>
</div>
<div class="modal-body">
<p>{{ _('See detailed instructions at <a href="https://discourse.octoprint.org/t/i-forgot-my-octoprint-password-how-can-i-reset-it/215">I forgot my OctoPrint password, how can I reset it?</a>') }}</p>
</div>
<div class="modal-footer">
<button class="btn btn-block" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
</div>
</div>
@@ -26,8 +26,8 @@
<div class="controls">
<div class="input-append input-block-level">
<input type="text" readonly="readonly" id="settings-apikey" data-bind="value: api_key, attr: {placeholder: '{{ _('N/A') }}'}">
<a class="btn add-on" title="Copy API Key to clipboard" data-bind="click: copyApiKey, enable: api_key"><i class="fa fa-copy"></i></a>
<a class="btn add-on" title="Generate new API Key" data-bind="click: generateApiKey, enable: api_key"><i class="fa fa-refresh"></i></a>
<a class="btn add-on" title="Copy API Key to clipboard" data-bind="click: copyApiKey, css: {'disabled': !api_key()}"><i class="fa fa-copy"></i></a>
<a class="btn add-on" title="Generate new API Key" data-bind="click: generateApiKey"><i class="fa fa-refresh"></i></a>
</div>
<span class="help-block">{{ _('Please note that changes to the API key are applied immediately, without having to "Save" first.') }}</span>
</div>
@@ -25,9 +25,9 @@
<div class="controls">
<div class="input-append input-block-level">
<input type="text" readonly="readonly" id="userSettings-access_apikey" data-bind="value: access_apikey, attr: {placeholder: '{{ _('N/A') }}'}">
<a class="btn add-on" title="Copy API Key to clipboard" data-bind="click: copyApikey, enable: access_apikey"><i class="fa fa-copy"></i></a>
<a class="btn add-on" title="Copy API Key to clipboard" data-bind="click: copyApikey, css: {'disabled': !access_apikey()}"><i class="fa fa-copy"></i></a>
<a class="btn add-on" title="Generate new API Key" data-bind="click: generateApikey"><i class="fa fa-refresh"></i></a>
<a class="btn btn-danger add-on" title="Delete API Key" data-bind="click: deleteApikey, enable: access_apikey"><i class="fa fa-trash-o"></i></a>
<a class="btn btn-danger add-on" title="Delete API Key" data-bind="click: deleteApikey, css: {'disabled': !access_apikey()}"><i class="fa fa-trash-o"></i></a>
</div>
<span class="help-block">{{ _('Please note that changes to the API key are applied immediately, without having to "Confirm" first.') }}</span>
</div>
+1 -3
View File
@@ -6,7 +6,7 @@
<form id="loginForm" data-bind="event: {'submit': loginState.prepareLogin }" onsubmit="return false; // this gets overwritten on view model bind">
<label for="login_user">{{ _('Username') }}</label>
<input type="text" id="login_user" name="username" data-bind="valueWithInit: loginState.loginUser" placeholder="{{ _('Username') }}" autocapitalize="none" autocorrect="off">
<span class="pull-right"><small><a href="#forgot_password_dialog" data-toggle="modal">{{ _('Forgot password?') }}</a></small></span>
<span class="pull-right"><small><a href="https://faq.octoprint.org/forgotten-password" target="_blank" rel="noreferrer noopener" tabindex="-1">{{ _('Forgot password?') }}</a></small></span>
<label for="login_pass">{{ _('Password') }}</label>
<input type="password" id="login_pass" name="password" data-bind="valueWithInit: loginState.loginPass" placeholder="{{ _('Password') }}">
<label class="checkbox">
@@ -19,5 +19,3 @@
<li><a href="#" id="usersettings_button" data-bind="click: function() { usersettings.show(); }">{{ _('User Settings') }}</a></li>
<li><a href="#" id="logout_button" data-bind="click: loginState.logout">{{ _('Logout') }}</a></li>
</ul>
{% include 'dialogs/forgot_password.jinja2' %}
+21 -6
View File
@@ -192,7 +192,7 @@ Groups will be as follows:
* ``value``: reported position value
"""
regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):")
regex_firmware_splitter = re.compile("\s*([A-Z0-9_]+):\s*")
"""Regex to use for splitting M115 responses."""
regex_resend_linenumber = re.compile("(N|N:)?(?P<n>%s)" % regex_int_pattern)
@@ -1557,7 +1557,11 @@ class MachineCom(object):
handled = True
# process timeouts
elif ((line == "" and now > self._timeout) or (self.isPrinting() and not self.isSdPrinting() and not self.job_on_hold and now > self._ok_timeout)) \
elif ((line == "" and now > self._timeout) or (self.isPrinting()
and not self.isSdPrinting()
and not self.job_on_hold
and not self._long_running_command
and not self._heating and now > self._ok_timeout)) \
and (not self._blockWhileDwelling or not self._dwelling_until or now > self._dwelling_until):
# We have two timeout variants:
#
@@ -1659,7 +1663,7 @@ class MachineCom(object):
pass
##~~ firmware name & version
elif "NAME:" in line:
elif "NAME:" in line or line.startswith("NAME."):
# looks like a response to M115
data = parse_firmware_line(line)
firmware_name = data.get("FIRMWARE_NAME")
@@ -1669,7 +1673,11 @@ class MachineCom(object):
# report its firmware name properly in response to M115. Wonderful - why stick to established
# protocol when you can do your own thing, right?
#
# Example: NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02
# Examples:
#
# NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02
# NAME. Malyan VER: 3.8 MODEL: M100 HW: HB02
# NAME. Malyan VER: 3.7 MODEL: M300 HW: HG01
#
# We do a bit of manual fiddling around here to circumvent that issue and get ourselves a
# reliable firmware name (NAME + VER) out of the Malyan M115 response.
@@ -3562,7 +3570,8 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
"""
with self._handle_mutex:
if self._handle is None:
raise ValueError("File %s is not open for reading" % self._filename)
self._logger.warn(u"File {} is not open for reading".format(self._filename))
return None, None, None
try:
offsets = self._offsets_callback() if self._offsets_callback is not None else None
@@ -4009,10 +4018,16 @@ def parse_firmware_line(line):
dict: a dictionary with the parsed data
"""
if line.startswith("NAME."):
# Good job Malyan. Why use a : when you can also just use a ., right? Let's revert that.
line = list(line)
line[4] = ":"
line = "".join(line)
result = dict()
split_line = regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string
for key, value in chunks(split_line, 2):
result[key] = value
result[key] = value.strip()
return result
def parse_capability_line(line):
+23
View File
@@ -0,0 +1,23 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import socket
import sys
HAS_V6 = socket.has_ipv6
if hasattr(socket, "IPPROTO_IPV6") and hasattr(socket, "IPV6_V6ONLY"):
# Dual stack support, hooray!
IPPROTO_IPV6 = socket.IPPROTO_IPV6
IPV6_V6ONLY = socket.IPV6_V6ONLY
else:
if sys.platform == "win32":
# Python 2.7 on Windows lacks IPPROTO_IPV6, but supports the socket options just fine, let's redefine it
IPPROTO_IPV6 = 41
IPV6_V6ONLY = 27
else:
# Whatever we are running on here, it we don't want to use V6 on here due to lack of dual stack support
HAS_V6 = False
View File
Whitespace-only changes.
+5
View File
@@ -0,0 +1,5 @@
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
+4
View File
@@ -0,0 +1,4 @@
# -*- coding: utf-8 -*-
from .router import SockJSRouter
from .conn import SockJSConnection
+130
View File
@@ -0,0 +1,130 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.basehandler
~~~~~~~~~~~~~~~~~~~~~~~~~~
Various base http handlers
"""
import datetime
import socket
import logging
from tornado.web import asynchronous, RequestHandler
CACHE_TIME = 31536000
LOG = logging.getLogger("tornado.general")
class BaseHandler(RequestHandler):
"""Base request handler with set of helpers."""
def initialize(self, server):
"""Initialize request
`server`
SockJSRouter instance.
"""
self.server = server
self.logged = False
# Statistics
def prepare(self):
"""Increment connection count"""
self.logged = True
self.server.stats.on_conn_opened()
def _log_disconnect(self):
"""Decrement connection count"""
if self.logged:
self.server.stats.on_conn_closed()
self.logged = False
def finish(self, chunk=None):
"""Tornado `finish` handler"""
self._log_disconnect()
super(BaseHandler, self).finish(chunk)
def on_connection_close(self):
"""Tornado `on_connection_close` handler"""
self._log_disconnect()
# Various helpers
def enable_cache(self):
"""Enable client-side caching for the current request"""
self.set_header('Cache-Control', 'max-age=%d, public' % CACHE_TIME)
d = datetime.datetime.now() + datetime.timedelta(seconds=CACHE_TIME)
self.set_header('Expires', d.strftime('%a, %d %b %Y %H:%M:%S'))
self.set_header('access-control-max-age', CACHE_TIME)
def disable_cache(self):
"""Disable client-side cache for the current request"""
self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
def handle_session_cookie(self):
"""Handle JSESSIONID cookie logic"""
# If JSESSIONID support is disabled in the settings, ignore cookie logic
if not self.server.settings['jsessionid']:
return
cookie = self.cookies.get('JSESSIONID')
if not cookie:
cv = 'dummy'
else:
cv = cookie.value
self.set_cookie('JSESSIONID', cv)
def safe_finish(self):
"""Finish session. If it will blow up - connection was set to Keep-Alive and
client dropped connection, ignore any IOError or socket error."""
try:
self.finish()
except (socket.error, IOError):
# We don't want to raise IOError exception if finish() call fails.
# It can happen if connection is set to Keep-Alive, but client
# closes connection after receiving response.
LOG.debug('Ignoring IOError in safe_finish()')
pass
class PreflightHandler(BaseHandler):
"""CORS preflight handler"""
@asynchronous
def options(self, *args, **kwargs):
"""XHR cross-domain OPTIONS handler"""
self.enable_cache()
self.handle_session_cookie()
self.preflight()
if self.verify_origin():
allowed_methods = getattr(self, 'access_methods', 'OPTIONS, POST')
self.set_header('Access-Control-Allow-Methods', allowed_methods)
self.set_header('Allow', allowed_methods)
self.set_status(204)
else:
# Set forbidden
self.set_status(403)
self.finish()
def preflight(self):
"""Handles request authentication"""
origin = self.request.headers.get('Origin', '*')
self.set_header('Access-Control-Allow-Origin', origin)
headers = self.request.headers.get('Access-Control-Request-Headers')
if headers:
self.set_header('Access-Control-Allow-Headers', headers)
self.set_header('Access-Control-Allow-Credentials', 'true')
def verify_origin(self):
"""Verify if request can be served"""
# TODO: Verify origin
return True
+70
View File
@@ -0,0 +1,70 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.conn
~~~~~~~~~~~~~~~~~~~
SockJS connection interface
"""
class SockJSConnection(object):
def __init__(self, session):
"""Connection constructor.
`session`
Associated session
"""
self.session = session
# Public API
def on_open(self, request):
"""Default on_open() handler.
Override when you need to do some initialization or request validation.
If you return False, connection will be rejected.
You can also throw Tornado HTTPError to close connection.
`request`
``ConnectionInfo`` object which contains caller IP address, query string
parameters and cookies associated with this request (if any).
"""
pass
def on_message(self, message):
"""Default on_message handler. Must be overridden in your application"""
raise NotImplementedError()
def on_close(self):
"""Default on_close handler."""
pass
def send(self, message, binary=False):
"""Send message to the client.
`message`
Message to send.
"""
if not self.is_closed:
self.session.send_message(message, binary=binary)
def broadcast(self, clients, message):
"""Broadcast message to the one or more clients.
Use this method if you want to send same message to lots of clients, as
it contains several optimizations and will work fast than just having loop
in your code.
`clients`
Clients iterable
`message`
Message to send.
"""
self.session.broadcast(clients, message)
def close(self):
self.session.close()
@property
def is_closed(self):
"""Check if connection was closed"""
return self.session.is_closed
+34
View File
@@ -0,0 +1,34 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.migrate
~~~~~~~~~~~~~~~~~~~~~~
`tornado.websocket` to `sockjs.tornado` migration helper.
"""
from octoprint.vendor.sockjs.tornado import conn
class WebsocketHandler(conn.SockJSConnection):
"""If you already use Tornado websockets for your application and
want try sockjs-tornado, change your handlers to derive from this
WebsocketHandler class. There are some limitations, for example
only self.request only contains remote_ip, cookies and arguments
collection"""
def open(self):
"""open handler"""
pass
def on_open(self, info):
"""sockjs-tornado on_open handler"""
# Store some properties
self.ip = info.ip
# Create fake request object
self.request = info
# Call open
self.open()
def write_message(self, msg):
self.send(msg)
+76
View File
@@ -0,0 +1,76 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.periodic
~~~~~~~~~~~~~~~~~~~~~~~
This module implements customized PeriodicCallback from tornado with
support of the sliding window.
"""
import time
import logging
LOG = logging.getLogger("tornado.general")
class Callback(object):
"""Custom implementation of the Tornado.Callback with support
of callback timeout delays.
"""
def __init__(self, callback, callback_time, io_loop):
"""Constructor.
`callback`
Callback function
`callback_time`
Callback timeout value (in milliseconds)
`io_loop`
io_loop instance
"""
self.callback = callback
self.callback_time = callback_time
self.io_loop = io_loop
self._running = False
self.next_run = None
def calculate_next_run(self):
"""Caltulate next scheduled run"""
return time.time() + self.callback_time / 1000.0
def start(self, timeout=None):
"""Start callbacks"""
self._running = True
if timeout is None:
timeout = self.calculate_next_run()
self.io_loop.add_timeout(timeout, self._run)
def stop(self):
"""Stop callbacks"""
self._running = False
def delay(self):
"""Delay callback"""
self.next_run = self.calculate_next_run()
def _run(self):
if not self._running:
return
# Support for shifting callback window
if self.next_run is not None and time.time() < self.next_run:
self.start(self.next_run)
self.next_run = None
return
next_call = None
try:
next_call = self.callback()
except (KeyboardInterrupt, SystemExit):
raise
except:
LOG.error("Error in periodic callback", exc_info=True)
if self._running:
self.start(next_call)
+50
View File
@@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.proto
~~~~~~~~~~~~~~~~~~~~
SockJS protocol related functions
"""
import logging
LOG = logging.getLogger("tornado.general")
# TODO: Add support for ujson module once they can accept unicode strings
# Try to find best json encoder available
try:
# Check for simplejson
import simplejson
json_encode = lambda data: simplejson.dumps(data, separators=(',', ':'))
json_decode = lambda data: simplejson.loads(data)
JSONDecodeError = ValueError
LOG.debug('sockjs.tornado will use simplejson module')
except ImportError:
# Use slow json
import json
LOG.debug('sockjs.tornado will use json module')
json_encode = lambda data: json.dumps(data, separators=(',', ':'))
json_decode = lambda data: json.loads(data)
JSONDecodeError = ValueError
# Protocol handlers
CONNECT = 'o'
DISCONNECT = 'c'
MESSAGE = 'm'
HEARTBEAT = 'h'
# Various protocol helpers
def disconnect(code, reason):
"""Return SockJS packet with code and close reason
`code`
Closing code
`reason`
Closing reason
"""
return 'c[%d,"%s"]' % (code, reason)
+208
View File
@@ -0,0 +1,208 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.router
~~~~~~~~~~~~~~~~~~~~~
SockJS protocol router implementation.
"""
from tornado import ioloop, version_info
from octoprint.vendor.sockjs.tornado import transports, session, sessioncontainer, static, stats, proto
DEFAULT_SETTINGS = {
# Sessions check interval in seconds
'session_check_interval': 1,
# Session expiration in seconds
'disconnect_delay': 5,
# Heartbeat time in seconds. Do not change this value unless
# you absolutely sure that new value will work.
'heartbeat_delay': 25,
# Enabled protocols
'disabled_transports': [],
# SockJS location
'sockjs_url': 'https://cdn.jsdelivr.net/sockjs/0.3/sockjs.min.js',
# Max response body size
'response_limit': 128 * 1024,
# Enable or disable JSESSIONID cookie handling
'jsessionid': True,
# Should sockjs-tornado flush messages immediately or queue then and
# flush on next ioloop tick
'immediate_flush': True,
# Enable or disable Nagle for persistent transports
'disable_nagle': True,
# Enable IP checks for polling transports. If enabled, all subsequent
# polling calls should be from the same IP address.
'verify_ip': True,
# list of allowed origins for websocket connections
# or "*" - accept all websocket connections
'websocket_allow_origin': "*"
}
GLOBAL_HANDLERS = [
('xhr_send', transports.XhrSendHandler),
('jsonp_send', transports.JSONPSendHandler)
]
TRANSPORTS = {
'websocket': transports.WebSocketTransport,
'xhr': transports.XhrPollingTransport,
'xhr_streaming': transports.XhrStreamingTransport,
'jsonp': transports.JSONPTransport,
'eventsource': transports.EventSourceTransport,
'htmlfile': transports.HtmlFileTransport
}
STATIC_HANDLERS = {
'/chunking_test': static.ChunkingTestHandler,
'/info': static.InfoHandler,
'/iframe[0-9-.a-z_]*.html': static.IFrameHandler,
'/websocket': transports.RawWebSocketTransport,
'/?': static.GreetingsHandler
}
class SockJSRouter(object):
"""SockJS protocol router"""
def __init__(self,
connection,
prefix='',
user_settings=dict(),
io_loop=None,
session_kls=None):
"""Constructor.
`connection`
SockJSConnection class
`prefix`
Connection prefix
`user_settings`
Settings dictionary
`io_loop`
Optional IOLoop instance
"""
# 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.current()
# Settings
self.settings = 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 session.Session
self._sessions = 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 = stats.StatsCollector(self.io_loop)
# Initialize URLs
base = prefix + r'/[^/.]+/(?P<session_id>[^/.]+)'
# Generate global handler URLs
self._transport_urls = [('%s/%s$' % (base, p[0]), p[1], dict(server=self))
for p in GLOBAL_HANDLERS]
for k, v in 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 STATIC_HANDLERS.items()])
@property
def urls(self):
"""List of the URLs to be added to the Tornado application"""
return self._transport_urls
def apply_routes(self, routes):
"""Feed list of the URLs to the routes list. Returns list"""
routes.extend(self._transport_urls)
return routes
def create_session(self, session_id, register=True):
"""Creates new session object and returns it.
`request`
Request that created the session. Will be used to get query string
parameters and cookies
`register`
Should be session registered in a storage. Websockets don't
need it.
"""
# TODO: Possible optimization here for settings.get
s = self._session_kls(self._connection,
self,
session_id,
self.settings.get('disconnect_delay')
)
if register:
self._sessions.add(s)
return s
def get_session(self, session_id):
"""Get session by session id
`session_id`
Session id
"""
return self._sessions.get(session_id)
def get_connection_class(self):
"""Return associated connection class"""
return self._connection
# Broadcast helper
def broadcast(self, clients, msg):
"""Optimized `broadcast` implementation. Depending on type of the session, will json-encode
message once and will call either `send_message` or `send_jsonifed`.
`clients`
Clients iterable
`msg`
Message to send
"""
json_msg = None
count = 0
for c in clients:
sess = c.session
if not sess.is_closed:
if sess.send_expects_json:
if json_msg is None:
json_msg = proto.json_encode(msg)
sess.send_jsonified(json_msg, False)
else:
sess.send_message(msg, stats=False)
count += 1
self.stats.on_pack_sent(count)
+419
View File
@@ -0,0 +1,419 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.session
~~~~~~~~~~~~~~~~~~~~~~
SockJS session implementation.
"""
import logging
from octoprint.vendor.sockjs.tornado import sessioncontainer, periodic, proto
from octoprint.vendor.sockjs.tornado.util import bytes_to_str
LOG = logging.getLogger("tornado.general")
class ConnectionInfo(object):
"""Connection information object.
Will be passed to the ``on_open`` handler of your connection class.
Has few properties:
`ip`
Caller IP address
`cookies`
Collection of cookies
`arguments`
Collection of the query string arguments
`headers`
Collection of headers sent by the browser that established this
connection
`path`
Request uri path
"""
def __init__(self, ip, cookies, arguments, headers, path):
self.ip = ip
self.cookies = cookies
self.arguments = arguments
self.headers = headers
self.path = path
def get_argument(self, name):
"""Return single argument by name"""
val = self.arguments.get(name)
if val:
return val[0]
return None
def get_cookie(self, name):
"""Return single cookie by its name"""
return self.cookies.get(name)
def get_header(self, name):
"""Return single header by its name"""
return self.headers.get(name)
# Session states
CONNECTING = 0
OPEN = 1
CLOSING = 2
CLOSED = 3
class BaseSession(object):
"""Base session implementation class"""
def __init__(self, conn, server):
"""Base constructor.
`conn`
Connection class
`server`
SockJSRouter instance
"""
self.server = server
self.stats = server.stats
self.send_expects_json = False
self.handler = None
self.state = CONNECTING
self.conn_info = None
self.conn = conn(self)
self.close_reason = None
def set_handler(self, handler):
"""Set transport handler
``handler``
Handler, should derive from the `sockjs.tornado.transports.base.BaseTransportMixin`.
"""
if self.handler is not None:
raise Exception('Attempted to overwrite BaseSession handler')
self.handler = handler
self.transport_name = self.handler.name
if self.conn_info is None:
self.conn_info = handler.get_conn_info()
self.stats.on_sess_opened(self.transport_name)
return True
def verify_state(self):
"""Verify if session was not yet opened. If it is, open it and call connections `on_open`"""
if self.state == CONNECTING:
self.state = OPEN
self.conn.on_open(self.conn_info)
def remove_handler(self, handler):
"""Remove active handler from the session
`handler`
Handler to remove
"""
# Attempt to remove another handler
if self.handler != handler:
raise Exception('Attempted to remove invalid handler')
self.handler = None
def close(self, code=3000, message='Go away!'):
"""Close session or endpoint connection.
`code`
Closing code
`message`
Close message
"""
if self.state != CLOSED:
try:
self.conn.on_close()
except:
LOG.debug("Failed to call on_close().", exc_info=True)
finally:
self.state = CLOSED
self.close_reason = (code, message)
self.conn = None
# Bump stats
self.stats.on_sess_closed(self.transport_name)
# If we have active handler, notify that session was closed
if self.handler is not None:
self.handler.session_closed()
def delayed_close(self):
"""Delayed close - won't close immediately, but on next ioloop tick."""
self.state = CLOSING
self.server.io_loop.add_callback(self.close)
def get_close_reason(self):
"""Return last close reason tuple.
For example:
if self.session.is_closed:
code, reason = self.session.get_close_reason()
"""
if self.close_reason:
return self.close_reason
return (3000, 'Go away!')
@property
def is_closed(self):
"""Check if session was closed."""
return self.state == CLOSED or self.state == CLOSING
def send_message(self, msg, stats=True, binary=False):
"""Send or queue outgoing message
`msg`
Message to send
`stats`
If set to True, will update statistics after operation completes
"""
raise NotImplemented()
def send_jsonified(self, msg, stats=True):
"""Send or queue outgoing message which was json-encoded before. Used by the `broadcast`
method.
`msg`
JSON-encoded message to send
`stats`
If set to True, will update statistics after operation completes
"""
raise NotImplemented()
def broadcast(self, clients, msg):
"""Optimized `broadcast` implementation. Depending on type of the session, will json-encode
message once and will call either `send_message` or `send_jsonifed`.
`clients`
Clients iterable
`msg`
Message to send
"""
self.server.broadcast(clients, msg)
class Session(BaseSession, sessioncontainer.SessionMixin):
"""SockJS session implementation.
"""
def __init__(self, conn, server, session_id, expiry=None):
"""Session constructor.
`conn`
Default connection class
`server`
`SockJSRouter` instance
`session_id`
Session id
`expiry`
Session expiry time
"""
# Initialize session
sessioncontainer.SessionMixin.__init__(self, session_id, expiry)
BaseSession.__init__(self, conn, server)
self.send_queue = ''
self.send_expects_json = True
# Heartbeat related stuff
self._heartbeat_timer = None
self._heartbeat_interval = self.server.settings['heartbeat_delay'] * 1000
self._immediate_flush = self.server.settings['immediate_flush']
self._pending_flush = False
self._verify_ip = self.server.settings['verify_ip']
# Session callbacks
def on_delete(self, forced):
"""Session expiration callback
`forced`
If session item explicitly deleted, forced will be set to True. If
item expired, will be set to False.
"""
# Do not remove connection if it was not forced and there's running connection
if not forced and self.handler is not None and not self.is_closed:
self.promote()
else:
self.close()
# Add session
def set_handler(self, handler, start_heartbeat=True):
"""Set active handler for the session
`handler`
Associate active Tornado handler with the session
`start_heartbeat`
Should session start heartbeat immediately
"""
# Check if session already has associated handler
if self.handler is not None:
handler.send_pack(proto.disconnect(2010, "Another connection still open"))
return False
if self._verify_ip and self.conn_info is not None:
# If IP address doesn't match - refuse connection
if handler.request.remote_ip != self.conn_info.ip:
LOG.error('Attempted to attach to session %s (%s) from different IP (%s)' % (
self.session_id,
self.conn_info.ip,
handler.request.remote_ip
))
handler.send_pack(proto.disconnect(2010, "Attempted to connect to session from different IP"))
return False
if (self.state == CLOSING or self.state == CLOSED) and not self.send_queue:
handler.send_pack(proto.disconnect(*self.get_close_reason()))
return False
# Associate handler and promote session
super(Session, self).set_handler(handler)
self.promote()
if start_heartbeat:
self.start_heartbeat()
return True
def verify_state(self):
"""Verify if session was not yet opened. If it is, open it and call connections `on_open`"""
# If we're in CONNECTING state - send 'o' message to the client
if self.state == CONNECTING:
self.handler.send_pack(proto.CONNECT)
# Call parent implementation
super(Session, self).verify_state()
def remove_handler(self, handler):
"""Detach active handler from the session
`handler`
Handler to remove
"""
super(Session, self).remove_handler(handler)
self.promote()
self.stop_heartbeat()
def send_message(self, msg, stats=True, binary=False):
"""Send or queue outgoing message
`msg`
Message to send
`stats`
If set to True, will update statistics after operation completes
"""
self.send_jsonified(proto.json_encode(bytes_to_str(msg)), stats)
def send_jsonified(self, msg, stats=True):
"""Send JSON-encoded message
`msg`
JSON encoded string to send
`stats`
If set to True, will update statistics after operation completes
"""
msg = bytes_to_str(msg)
if self._immediate_flush:
if self.handler and self.handler.active and not self.send_queue:
# Send message right away
self.handler.send_pack('a[%s]' % msg)
else:
if self.send_queue:
self.send_queue += ','
self.send_queue += msg
self.flush()
else:
if self.send_queue:
self.send_queue += ','
self.send_queue += msg
if not self._pending_flush:
self.server.io_loop.add_callback(self.flush)
self._pending_flush = True
if stats:
self.stats.on_pack_sent(1)
def flush(self):
"""Flush message queue if there's an active connection running"""
self._pending_flush = False
if self.handler is None or not self.handler.active or not self.send_queue:
return
self.handler.send_pack('a[%s]' % self.send_queue)
self.send_queue = ''
def close(self, code=3000, message='Go away!'):
"""Close session.
`code`
Closing code
`message`
Closing message
"""
if self.state != CLOSED:
# Notify handler
if self.handler is not None:
self.handler.send_pack(proto.disconnect(code, message))
super(Session, self).close(code, message)
# Heartbeats
def start_heartbeat(self):
"""Reset hearbeat timer"""
self.stop_heartbeat()
self._heartbeat_timer = periodic.Callback(self._heartbeat,
self._heartbeat_interval,
self.server.io_loop)
self._heartbeat_timer.start()
def stop_heartbeat(self):
"""Stop active heartbeat"""
if self._heartbeat_timer is not None:
self._heartbeat_timer.stop()
self._heartbeat_timer = None
def delay_heartbeat(self):
"""Delay active heartbeat"""
if self._heartbeat_timer is not None:
self._heartbeat_timer.delay()
def _heartbeat(self):
"""Heartbeat callback"""
if self.handler is not None:
self.handler.send_pack(proto.HEARTBEAT)
else:
self.stop_heartbeat()
def on_messages(self, msg_list):
"""Handle incoming messages
`msg_list`
Message list to process
"""
self.stats.on_pack_recv(len(msg_list))
for msg in msg_list:
if self.state == OPEN:
self.conn.on_message(msg)
+159
View File
@@ -0,0 +1,159 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.sessioncontainer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simple heapq-based session implementation with sliding expiration window
support.
"""
from heapq import heappush, heappop
from time import time
from hashlib import md5
from random import random
def _random_key():
"""Return random session key"""
i = md5()
i.update('%s%s' % (random(), time()))
return i.hexdigest()
class SessionMixin(object):
"""Represents one session object stored in the session container.
Derive from this object to store additional data.
"""
def __init__(self, session_id=None, expiry=None):
"""Constructor.
``session_id``
Optional session id. If not provided, will generate
new session id.
``expiry``
Expiration time. If not provided, will never expire.
"""
self.session_id = session_id or _random_key()
self.promoted = None
self.expiry = expiry
if self.expiry is not None:
self.expiry_date = time() + self.expiry
def is_alive(self):
"""Check if session is still alive"""
return self.expiry_date > time()
def promote(self):
"""Mark object as alive, so it won't be collected during next
run of the garbage collector.
"""
if self.expiry is not None:
self.promoted = time() + self.expiry
def on_delete(self, forced):
"""Triggered when object was expired or deleted."""
pass
def __lt__(self, other):
return self.expiry_date < other.expiry_date
__cmp__ = __lt__
def __repr__(self):
return '%f %s %d' % (getattr(self, 'expiry_date', -1),
self.session_id,
self.promoted or 0)
class SessionContainer(object):
"""Session container object.
If we will implement sessions with Tornado timeouts, for polling transports
it will be nightmare - if load will be high, number of discarded timeouts
will be huge and will be huge performance hit, as Tornado will have to
clean them up all the time.
"""
def __init__(self):
self._items = dict()
self._queue = []
def add(self, session):
"""Add session to the container.
`session`
Session object
"""
self._items[session.session_id] = session
if session.expiry is not None:
heappush(self._queue, session)
def get(self, session_id):
"""Return session object or None if it is not available
`session_id`
Session identifier
"""
return self._items.get(session_id, None)
def remove(self, session_id):
"""Remove session object from the container
`session_id`
Session identifier
"""
session = self._items.get(session_id, None)
if session is not None:
session.promoted = -1
session.on_delete(True)
del self._items[session_id]
return True
return False
def expire(self, current_time=None):
"""Expire any old entries
`current_time`
Optional time to be used to clean up queue (can be used in unit tests)
"""
if not self._queue:
return
if current_time is None:
current_time = time()
while self._queue:
# Get top most item
top = self._queue[0]
# Early exit if item was not promoted and its expiration time
# is greater than now.
if top.promoted is None and top.expiry_date > current_time:
break
# Pop item from the stack
top = heappop(self._queue)
need_reschedule = (top.promoted is not None
and top.promoted > current_time)
# Give chance to reschedule
if not need_reschedule:
top.promoted = None
top.on_delete(False)
need_reschedule = (top.promoted is not None
and top.promoted > current_time)
# If item is promoted and expiration time somewhere in future
# just reschedule it
if need_reschedule:
top.expiry_date = top.promoted
top.promoted = None
heappush(self._queue, top)
else:
del self._items[top.session_id]
+133
View File
@@ -0,0 +1,133 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.static
~~~~~~~~~~~~~~~~~~~~~
Various static handlers required for SockJS to function properly.
"""
import time
import hashlib
import random
import sys
from tornado.web import asynchronous
from octoprint.vendor.sockjs.tornado.basehandler import BaseHandler, PreflightHandler
from octoprint.vendor.sockjs.tornado.proto import json_encode
from octoprint.vendor.sockjs.tornado.util import MAXSIZE, str_to_bytes
IFRAME_TEXT = '''<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
document.domain = document.domain;
_sockjs_onload = function(){SockJS.bootstrap_iframe();};
</script>
<script src="%s"></script>
</head>
<body>
<h2>Don't panic!</h2>
<p>This is a SockJS hidden iframe. It's used for cross domain magic.</p>
</body>
</html>'''.strip()
class IFrameHandler(BaseHandler):
"""SockJS IFrame page handler"""
def get(self):
data = str_to_bytes(IFRAME_TEXT % self.server.settings['sockjs_url'])
hsh = hashlib.md5(data).hexdigest()
value = self.request.headers.get('If-None-Match')
if value:
if value.find(hsh) != -1:
# TODO: Fix me? Right now it is a hack to remove content-type
# header
self.clear()
del self._headers['Content-Type']
self.set_status(304)
return
self.enable_cache()
self.set_header('Etag', hsh)
self.write(data)
class GreetingsHandler(BaseHandler):
"""SockJS greetings page handler"""
def initialize(self, server):
self.server = server
def get(self):
self.enable_cache()
self.set_header('Content-Type', 'text/plain; charset=UTF-8')
self.write('Welcome to SockJS!\n')
class ChunkingTestHandler(PreflightHandler):
"""SockJS chunking test handler"""
# Step timeouts according to sockjs documentation
steps = [0.005, 0.025, 0.125, 0.625, 3.125]
def initialize(self, server):
self.server = server
self.step = 0
self.io_loop = server.io_loop
@asynchronous
def post(self):
self.preflight()
self.set_header('Content-Type', 'application/javascript; charset=UTF-8')
# Send one 'h' immediately
self.write('h\n')
self.flush()
# Send 2048 spaces followed by 'h'
self.write(' ' * 2048 + 'h\n')
self.flush()
# Send 'h' with different timeouts
def run_step():
try:
self.write('h\n')
self.flush()
self.step += 1
if self.step < len(self.steps):
self.io_loop.add_timeout(time.time() + self.steps[self.step],
run_step)
else:
self.finish()
except IOError:
pass
self.io_loop.add_timeout(time.time() + self.steps[0], run_step)
class InfoHandler(PreflightHandler):
"""SockJS 0.2+ /info handler"""
def initialize(self, server):
self.server = server
self.access_methods = 'OPTIONS, GET'
def get(self):
self.preflight()
self.disable_cache()
self.set_header('Content-Type', 'application/json; charset=UTF-8')
options = dict(websocket=self.server.websockets_enabled,
cookie_needed=self.server.cookie_needed,
origins=['*:*'],
entropy=random.randint(0, MAXSIZE))
self.write(json_encode(options))
+123
View File
@@ -0,0 +1,123 @@
from collections import deque
from tornado import ioloop
class MovingAverage(object):
"""Moving average class implementation"""
def __init__(self, period=10):
"""Constructor.
`period`
Moving window size. Average will be calculated
from the data in the window.
"""
self.period = period
self.stream = deque()
self.sum = 0
self.accumulator = 0
self.last_average = 0
def add(self, n):
"""Add value to the current accumulator
`n`
Value to add
"""
self.accumulator += n
def flush(self):
"""Add accumulator to the moving average queue
and reset it. For example, called by the StatsCollector
once per second to calculate per-second average.
"""
n = self.accumulator
self.accumulator = 0
stream = self.stream
stream.append(n)
self.sum += n
streamlen = len(stream)
if streamlen > self.period:
self.sum -= stream.popleft()
streamlen -= 1
if streamlen == 0:
self.last_average = 0
else:
self.last_average = self.sum / float(streamlen)
class StatsCollector(object):
def __init__(self, io_loop):
# Sessions
self.sess_active = 0
# Avoid circular reference
self.sess_transports = dict()
# Connections
self.conn_active = 0
self.conn_ps = MovingAverage()
# Packets
self.pack_sent_ps = MovingAverage()
self.pack_recv_ps = MovingAverage()
self._callback = ioloop.PeriodicCallback(self._update,
1000)
self._callback.start()
def _update(self):
self.conn_ps.flush()
self.pack_sent_ps.flush()
self.pack_recv_ps.flush()
def dump(self):
"""Return dictionary with current statistical information"""
data = dict(
# Sessions
sessions_active=self.sess_active,
# Connections
connections_active=self.conn_active,
connections_ps=self.conn_ps.last_average,
# Packets
packets_sent_ps=self.pack_sent_ps.last_average,
packets_recv_ps=self.pack_recv_ps.last_average
)
for k, v in self.sess_transports.items():
data['transp_' + k] = v
return data
# Various event callbacks
def on_sess_opened(self, transport):
self.sess_active += 1
if transport not in self.sess_transports:
self.sess_transports[transport] = 0
self.sess_transports[transport] += 1
def on_sess_closed(self, transport):
self.sess_active -= 1
self.sess_transports[transport] -= 1
def on_conn_opened(self):
self.conn_active += 1
self.conn_ps.add(1)
def on_conn_closed(self):
self.conn_active -= 1
def on_pack_sent(self, num):
self.pack_sent_ps.add(num)
def on_pack_recv(self, num):
self.pack_recv_ps.add(num)
@@ -0,0 +1,11 @@
# -*- coding: utf-8 -*-
import octoprint.vendor.sockjs.tornado.transports.pollingbase
from .xhr import XhrPollingTransport, XhrSendHandler
from .jsonp import JSONPTransport, JSONPSendHandler
from .websocket import WebSocketTransport
from .xhrstreaming import XhrStreamingTransport
from .eventsource import EventSourceTransport
from .htmlfile import HtmlFileTransport
from .rawwebsocket import RawWebSocketTransport
+22
View File
@@ -0,0 +1,22 @@
from octoprint.vendor.sockjs.tornado import session
class BaseTransportMixin(object):
"""Base transport.
Implements few methods that session expects to see in each transport.
"""
name = 'override_me_please'
def get_conn_info(self):
"""Return `ConnectionInfo` object from current transport"""
return session.ConnectionInfo(self.request.remote_ip,
self.request.cookies,
self.request.arguments,
self.request.headers,
self.request.path)
def session_closed(self):
"""Called by the session, when it gets closed"""
pass
@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.transports.eventsource
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
EventSource transport implementation.
"""
from tornado.web import asynchronous
from octoprint.vendor.sockjs.tornado.transports import streamingbase
class EventSourceTransport(streamingbase.StreamingTransportBase):
name = 'eventsource'
@asynchronous
def get(self, session_id):
# Start response
self.preflight()
self.handle_session_cookie()
self.disable_cache()
self.set_header('Content-Type', 'text/event-stream; charset=UTF-8')
self.write('\r\n')
self.flush()
if not self._attach_session(session_id):
self.finish()
return
if self.session:
self.session.flush()
def send_pack(self, message, binary=False):
if binary:
raise Exception('binary not supported for EventSourceTransport')
msg = 'data: %s\r\n\r\n' % message
self.active = False
try:
self.notify_sent(len(msg))
self.write(msg)
self.flush(callback=self.send_complete)
except IOError:
# If connection dropped, make sure we close offending session instead
# of propagating error all way up.
self.session.delayed_close()
self._detach()
@@ -0,0 +1,86 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.transports.htmlfile
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HtmlFile transport implementation.
"""
from tornado.web import asynchronous
from octoprint.vendor.sockjs.tornado import proto
from octoprint.vendor.sockjs.tornado.transports import streamingbase
# HTMLFILE template
HTMLFILE_HEAD = r'''
<!doctype html>
<html><head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head><body><h2>Don't panic!</h2>
<script>
document.domain = document.domain;
var c = parent.%s;
c.start();
function p(d) {c.message(d);};
window.onload = function() {c.stop();};
</script>
'''.strip()
HTMLFILE_HEAD += ' ' * (1024 - len(HTMLFILE_HEAD) + 14)
HTMLFILE_HEAD += '\r\n\r\n'
class HtmlFileTransport(streamingbase.StreamingTransportBase):
name = 'htmlfile'
def initialize(self, server):
super(HtmlFileTransport, self).initialize(server)
@asynchronous
def get(self, session_id):
# Start response
self.preflight()
self.handle_session_cookie()
self.disable_cache()
self.set_header('Content-Type', 'text/html; charset=UTF-8')
# Grab callback parameter
callback = self.get_argument('c', None)
if not callback:
self.write('"callback" parameter required')
self.set_status(500)
self.finish()
return
# TODO: Fix me - use parameter
self.write(HTMLFILE_HEAD % callback)
self.flush()
# Now try to attach to session
if not self._attach_session(session_id):
self.finish()
return
# Flush any pending messages
if self.session:
self.session.flush()
def send_pack(self, message, binary=False):
if binary:
raise Exception('binary not supported for HtmlFileTransport')
# TODO: Just do escaping
msg = '<script>\np(%s);\n</script>\r\n' % proto.json_encode(message)
self.active = False
try:
self.notify_sent(len(message))
self.write(msg)
self.flush(callback=self.send_complete)
except IOError:
# If connection dropped, make sure we close offending session instead
# of propagating error all way up.
self.session.delayed_close()
self._detach()
+127
View File
@@ -0,0 +1,127 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.transports.jsonp
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
JSONP transport implementation.
"""
import logging
from tornado.web import asynchronous
from octoprint.vendor.sockjs.tornado import proto
from octoprint.vendor.sockjs.tornado.transports import pollingbase
from octoprint.vendor.sockjs.tornado.util import bytes_to_str, unquote_plus
LOG = logging.getLogger("tornado.general")
class JSONPTransport(pollingbase.PollingTransportBase):
name = 'jsonp'
@asynchronous
def get(self, session_id):
# Start response
self.handle_session_cookie()
self.disable_cache()
# Grab callback parameter
self.callback = self.get_argument('c', None)
if not self.callback:
self.write('"callback" parameter required')
self.set_status(500)
self.finish()
return
# Get or create session without starting heartbeat
if not self._attach_session(session_id, False):
return
# Might get already detached because connection was closed in on_open
if not self.session:
return
if not self.session.send_queue:
self.session.start_heartbeat()
else:
self.session.flush()
def send_pack(self, message, binary=False):
if binary:
raise Exception('binary not supported for JSONPTransport')
self.active = False
try:
# TODO: Just escape
msg = '%s(%s);\r\n' % (self.callback, proto.json_encode(message))
self.set_header('Content-Type', 'application/javascript; charset=UTF-8')
self.set_header('Content-Length', len(msg))
# TODO: Fix me
self.set_header('Etag', 'dummy')
self.write(msg)
self.flush(callback=self.send_complete)
except IOError:
# If connection dropped, make sure we close offending session instead
# of propagating error all way up.
self.session.delayed_close()
class JSONPSendHandler(pollingbase.PollingTransportBase):
def post(self, session_id):
self.preflight()
self.handle_session_cookie()
self.disable_cache()
session = self._get_session(session_id)
if session is None or session.is_closed:
self.set_status(404)
return
data = bytes_to_str(self.request.body)
ctype = self.request.headers.get('Content-Type', '').lower()
if ctype == 'application/x-www-form-urlencoded':
if not data.startswith('d='):
LOG.exception('jsonp_send: Invalid payload.')
self.write("Payload expected.")
self.set_status(500)
return
data = unquote_plus(data[2:])
if not data:
LOG.debug('jsonp_send: Payload expected.')
self.write("Payload expected.")
self.set_status(500)
return
try:
messages = proto.json_decode(data)
except:
# TODO: Proper error handling
LOG.debug('jsonp_send: Invalid json encoding')
self.write("Broken JSON encoding.")
self.set_status(500)
return
try:
session.on_messages(messages)
except Exception:
LOG.exception('jsonp_send: on_message() failed')
session.close()
self.write('Message handler failed.')
self.set_status(500)
return
self.write('ok')
self.set_header('Content-Type', 'text/plain; charset=UTF-8')
self.set_status(200)
@@ -0,0 +1,72 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.transports.pollingbase
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Polling transports base
"""
from octoprint.vendor.sockjs.tornado import basehandler
from octoprint.vendor.sockjs.tornado.transports import base
class PollingTransportBase(basehandler.PreflightHandler, base.BaseTransportMixin):
"""Polling transport handler base class"""
def initialize(self, server):
super(PollingTransportBase, self).initialize(server)
self.session = None
self.active = True
def _get_session(self, session_id):
return self.server.get_session(session_id)
def _attach_session(self, session_id, start_heartbeat=False):
session = self._get_session(session_id)
if session is None:
session = self.server.create_session(session_id)
# Try to attach to the session
if not session.set_handler(self, start_heartbeat):
return False
self.session = session
# Verify if session is properly opened
session.verify_state()
return True
def _detach(self):
"""Detach from the session"""
if self.session:
self.session.remove_handler(self)
self.session = None
def check_xsrf_cookie(self):
pass
def send_message(self, message, binary=False):
"""Called by the session when some data is available"""
raise NotImplementedError()
def session_closed(self):
"""Called by the session when it was closed"""
self._detach()
self.safe_finish()
def on_connection_close(self):
# If connection was dropped by the client, close session.
# In all other cases, connection will be closed by the server.
if self.session is not None:
self.session.close(1002, 'Connection interrupted')
super(PollingTransportBase, self).on_connection_close()
def send_complete(self):
self._detach()
# Avoid race condition when waiting for write callback and session getting closed in between
if not self._finished:
self.safe_finish()
@@ -0,0 +1,93 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.transports.rawwebsocket
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Raw websocket transport implementation
"""
import logging
import socket
from octoprint.vendor.sockjs.tornado import websocket, session
from octoprint.vendor.sockjs.tornado.transports import base
LOG = logging.getLogger("tornado.general")
class RawSession(session.BaseSession):
"""Raw session without any sockjs protocol encoding/decoding. Simply
works as a proxy between `SockJSConnection` class and `RawWebSocketTransport`."""
def send_message(self, msg, stats=True, binary=False):
self.handler.send_pack(msg, binary)
def on_message(self, msg):
self.conn.on_message(msg)
class RawWebSocketTransport(websocket.SockJSWebSocketHandler, base.BaseTransportMixin):
"""Raw Websocket transport"""
name = 'rawwebsocket'
def initialize(self, server):
self.server = server
self.session = None
self.active = True
def open(self):
# Stats
self.server.stats.on_conn_opened()
# Disable nagle if needed
if self.server.settings['disable_nagle']:
self.stream.socket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
# Create and attach to session
self.session = RawSession(self.server.get_connection_class(), self.server)
self.session.set_handler(self)
self.session.verify_state()
def _detach(self):
if self.session is not None:
self.session.remove_handler(self)
self.session = None
def on_message(self, message):
# SockJS requires that empty messages should be ignored
if not message or not self.session:
return
try:
self.session.on_message(message)
except Exception:
LOG.exception('RawWebSocket')
# Close running connection
self.abort_connection()
def on_close(self):
# Close session if websocket connection was closed
if self.session is not None:
# Stats
self.server.stats.on_conn_closed()
session = self.session
self._detach()
session.close()
def send_pack(self, message, binary=False):
# Send message
try:
self.write_message(message, binary)
except IOError:
self.server.io_loop.add_callback(self.on_close)
def session_closed(self):
try:
self.close(*self.session.get_close_reason())
except IOError:
pass
finally:
self._detach()
# Websocket overrides
def allow_draft76(self):
return True
@@ -0,0 +1,47 @@
from octoprint.vendor.sockjs.tornado.transports import pollingbase
class StreamingTransportBase(pollingbase.PollingTransportBase):
def initialize(self, server):
super(StreamingTransportBase, self).initialize(server)
self.amount_limit = self.server.settings['response_limit']
# HTTP 1.0 client might send keep-alive
if hasattr(self.request, 'connection') and not self.request.supports_http_1_1():
self.request.connection.no_keep_alive = True
def notify_sent(self, data_len):
"""
Update amount of data sent
"""
self.amount_limit -= data_len
def should_finish(self):
"""
Check if transport should close long running connection after
sending X bytes to the client.
`data_len`
Amount of data that was sent
"""
if self.amount_limit <= 0:
return True
return False
def send_complete(self):
"""
Verify if connection should be closed based on amount of data that was sent.
"""
self.active = True
if self.should_finish():
self._detach()
# Avoid race condition when waiting for write callback and session getting closed in between
if not self._finished:
self.safe_finish()
else:
if self.session:
self.session.flush()
@@ -0,0 +1,105 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.transports.websocket
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Websocket transport implementation
"""
import logging
import socket
from octoprint.vendor.sockjs.tornado import proto, websocket
from octoprint.vendor.sockjs.tornado.transports import base
from octoprint.vendor.sockjs.tornado.util import bytes_to_str
LOG = logging.getLogger("tornado.general")
class WebSocketTransport(websocket.SockJSWebSocketHandler, base.BaseTransportMixin):
"""Websocket transport"""
name = 'websocket'
def initialize(self, server):
self.server = server
self.session = None
self.active = True
def open(self, session_id):
# Stats
self.server.stats.on_conn_opened()
# Disable nagle
if self.server.settings['disable_nagle']:
self.stream.set_nodelay(True)
# Handle session
self.session = self.server.create_session(session_id, register=False)
if not self.session.set_handler(self):
self.close()
return
self.session.verify_state()
if self.session:
self.session.flush()
def _detach(self):
if self.session is not None:
self.session.remove_handler(self)
self.session = None
def on_message(self, message):
# SockJS requires that empty messages should be ignored
if not message or not self.session:
return
try:
msg = proto.json_decode(bytes_to_str(message))
if isinstance(msg, list):
self.session.on_messages(msg)
else:
self.session.on_messages((msg,))
except Exception:
LOG.exception('WebSocket')
# Close session on exception
#self.session.close()
# Close running connection
self.abort_connection()
def on_close(self):
# Close session if websocket connection was closed
if self.session is not None:
# Stats
self.server.stats.on_conn_closed()
# Detach before closing session
session = self.session
self._detach()
session.close()
def send_pack(self, message, binary=False):
# Send message
try:
self.write_message(message, binary)
except IOError:
self.server.io_loop.add_callback(self.on_close)
def session_closed(self):
# If session was closed by the application, terminate websocket
# connection as well.
try:
self.close()
except IOError:
pass
finally:
self._detach()
# Websocket overrides
def allow_draft76(self):
return True
def auto_decode(self):
return False
+95
View File
@@ -0,0 +1,95 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.transports.xhr
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Xhr-Polling transport implementation
"""
import logging
from tornado.web import asynchronous
from octoprint.vendor.sockjs.tornado import proto
from octoprint.vendor.sockjs.tornado.transports import pollingbase
from octoprint.vendor.sockjs.tornado.util import bytes_to_str
LOG = logging.getLogger("tornado.general")
class XhrPollingTransport(pollingbase.PollingTransportBase):
"""xhr-polling transport implementation"""
name = 'xhr'
@asynchronous
def post(self, session_id):
# Start response
self.preflight()
self.handle_session_cookie()
self.disable_cache()
# Get or create session without starting heartbeat
if not self._attach_session(session_id, False):
return
# Might get already detached because connection was closed in on_open
if not self.session:
return
if not self.session.send_queue:
self.session.start_heartbeat()
else:
self.session.flush()
def send_pack(self, message, binary=False):
if binary:
raise Exception('binary not supported for XhrPollingTransport')
self.active = False
try:
self.set_header('Content-Type', 'application/javascript; charset=UTF-8')
self.set_header('Content-Length', len(message) + 1)
self.write(message + '\n')
self.flush(callback=self.send_complete)
except IOError:
# If connection dropped, make sure we close offending session instead
# of propagating error all way up.
self.session.delayed_close()
class XhrSendHandler(pollingbase.PollingTransportBase):
def post(self, session_id):
self.preflight()
self.handle_session_cookie()
self.disable_cache()
session = self._get_session(session_id)
if session is None or session.is_closed:
self.set_status(404)
return
data = self.request.body
if not data:
self.write("Payload expected.")
self.set_status(500)
return
try:
messages = proto.json_decode(bytes_to_str(data))
except:
# TODO: Proper error handling
self.write("Broken JSON encoding.")
self.set_status(500)
return
try:
session.on_messages(messages)
except Exception:
LOG.exception('XHR incoming')
session.close()
self.set_status(500)
return
self.set_status(204)
self.set_header('Content-Type', 'text/plain; charset=UTF-8')
@@ -0,0 +1,51 @@
# -*- coding: utf-8 -*-
"""
sockjs.tornado.transports.xhrstreaming
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Xhr-Streaming transport implementation
"""
from tornado.web import asynchronous
from octoprint.vendor.sockjs.tornado.transports import streamingbase
class XhrStreamingTransport(streamingbase.StreamingTransportBase):
name = 'xhr_streaming'
@asynchronous
def post(self, session_id):
# Handle cookie
self.preflight()
self.handle_session_cookie()
self.disable_cache()
self.set_header('Content-Type', 'application/javascript; charset=UTF-8')
# Send prelude and flush any pending messages
self.write('h' * 2048 + '\n')
self.flush()
if not self._attach_session(session_id, False):
self.finish()
return
if self.session:
self.session.flush()
def send_pack(self, message, binary=False):
if binary:
raise Exception('binary not supported for XhrStreamingTransport')
self.active = False
try:
self.notify_sent(len(message))
self.write(message + '\n')
self.flush(callback=self.send_complete)
except IOError:
# If connection dropped, make sure we close offending session instead
# of propagating error all way up.
self.session.delayed_close()
self._detach()
+50
View File
@@ -0,0 +1,50 @@
import sys
PY3 = sys.version_info[0] == 3
if PY3:
MAXSIZE = sys.maxsize
def bytes_to_str(b):
if isinstance(b, bytes):
return str(b, 'utf8')
return b
def str_to_bytes(s):
if isinstance(s, bytes):
return s
return s.encode('utf8')
import urllib.parse
unquote_plus = urllib.parse.unquote_plus
else:
if sys.platform == "java":
# Jython always uses 32 bits.
MAXSIZE = int((1 << 31) - 1)
else:
# It's possible to have sizeof(long) != sizeof(Py_ssize_t).
class X(object):
def __len__(self):
return 1 << 31
try:
len(X())
except OverflowError:
# 32-bit
MAXSIZE = int((1 << 31) - 1)
else:
# 64-bit
MAXSIZE = int((1 << 63) - 1)
del X
def bytes_to_str(s):
if isinstance(s, unicode):
return s.encode('utf-8')
return s
def str_to_bytes(s):
if isinstance(s, unicode):
return s.encode('utf8')
return s
import urllib
unquote_plus = urllib.unquote_plus
+36
View File
@@ -0,0 +1,36 @@
import tornado
from tornado import escape, gen, websocket
try:
from urllib.parse import urlparse # py3
except ImportError:
from urlparse import urlparse # py2
class SockJSWebSocketHandler(websocket.WebSocketHandler):
if tornado.version_info[0] == 4 and tornado.version_info[1] > 1:
def get_compression_options(self):
# let tornado use compression when Sec-WebSocket-Extensions:permessage-deflate is provided
return {}
SUPPORTED_METHODS = ('GET',)
def check_origin(self, origin):
# let tornado first check if connection from the same domain
same_domain = super(SockJSWebSocketHandler, self).check_origin(origin)
if same_domain:
return True
# this is cross-origin connection - check using SockJS server settings
allow_origin = self.server.settings.get("websocket_allow_origin", "*")
if allow_origin == "*":
return True
else:
parsed_origin = urlparse(origin)
origin = parsed_origin.netloc
origin = origin.lower()
return origin in allow_origin
def abort_connection(self):
if self.ws_connection:
self.ws_connection._abort()
+17 -1
View File
@@ -50,6 +50,22 @@ def recursively_handle_files(directory, file_matcher, folder_matcher=None, folde
return applied_handler
def has_requirement(requirement, requirements):
if requirement is None or requirements is None:
return False
assert isinstance(requirement, basestring)
assert isinstance(requirements, (list, tuple))
assert all(map(lambda x: x is not None and isinstance(x, basestring), requirements))
requirement = requirement.lower()
requirements = [r.lower() for r in requirements]
compat = [requirement.lower() + c for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")]
return requirement in requirements or \
any(any(r.startswith(c) for c in compat) for r in requirements)
class CleanCommand(_clean):
user_options = _clean.user_options + [("orig", None, "behave like original clean command"),
("noeggs", None, "don't clean up eggs"),
@@ -479,7 +495,7 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1"
requires = ["OctoPrint"]
if not isinstance(requires, list):
raise ValueError("requires must be a list")
if "OctoPrint" not in requires:
if not has_requirement("OctoPrint", requires):
requires = ["OctoPrint"] + list(requires)
if extra_requires is None:
+30
View File
@@ -0,0 +1,30 @@
# coding=utf-8
import unittest
import ddt
import octoprint_setuptools
@ddt.ddt
class OctoPrintSetuptoolsTest(unittest.TestCase):
@ddt.data(
("OctoPrint", ["OctoPrint", "flask"], True),
("OctoPrint", ["OctoPrint<1.3.7", "flask"], True),
("OctoPrint", ["OctoPrint<=1.3.7", "flask"], True),
("OctoPrint", ["OctoPrint==1.3.7", "flask"], True),
("OctoPrint", ["OctoPrint!=1.3.7", "flask"], True),
("OctoPrint", ["OctoPrint>=1.3.7", "flask"], True),
("OctoPrint", ["OctoPrint>1.3.7", "flask"], True),
("OctoPrint", ["OctoPrint~=1.3.7", "flask"], True),
("OctoPrint", ["OctoPrint===1.3.7", "flask"], True),
("OctoPrint", ["oCTOpRINT>=1.3.7", "flask"], True),
("OctoPrint", ["flask"], False),
("OctoPrint", [], False),
("OctoPrint", None, False),
(None, [], False),
)
@ddt.unpack
def test_has_requirement(self, requirement, requirements, expected):
actual = octoprint_setuptools.has_requirement(requirement, requirements)
self.assertEqual(actual, expected)
+14 -1
View File
@@ -259,7 +259,20 @@ class TestCommHelpers(unittest.TestCase):
@data(
("KEY1:Value 1 FIRMWARE_NAME:Some Firmware With Spaces KEY2:Value 2",
dict(KEY1="Value 1", KEY2="Value 2", FIRMWARE_NAME="Some Firmware With Spaces"))
dict(KEY1="Value 1", KEY2="Value 2", FIRMWARE_NAME="Some Firmware With Spaces")),
("NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02",
dict(NAME="Malyan", VER="2.9", MODEL="M200", HW="HA02")),
("NAME. Malyan VER: 3.8 MODEL: M100 HW: HB02",
dict(NAME="Malyan", VER="3.8", MODEL="M100", HW="HB02")),
("NAME. Malyan VER: 3.7 MODEL: M300 HW: HG01",
dict(NAME="Malyan", VER="3.7", MODEL="M300", HW="HG01")),
("FIRMWARE_NAME:Marlin 1.1.0 From Archive SOURCE_CODE_URL:http:// ... PROTOCOL_VERSION:1.0 MACHINE_TYPE:www.cxsw3d.com EXTRUDER_COUNT:1 UUID:00000000-0000-0000-0000-000000000000",
dict(FIRMWARE_NAME="Marlin 1.1.0 From Archive",
SOURCE_CODE_URL="http:// ...",
PROTOCOL_VERSION="1.0",
MACHINE_TYPE="www.cxsw3d.com",
EXTRUDER_COUNT="1",
UUID="00000000-0000-0000-0000-000000000000"))
)
@unpack
def test_parse_firmware_line(self, line, expected):