Merge branch 'devel' into dev/timelapseProgress
This commit is contained in:
94 files changed
+3264
-448
No files matched your search
+7
-7
@@ -18,16 +18,16 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.7
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.9
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev
|
||||
fix/.* 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev
|
||||
improve/.* 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev
|
||||
maintenance 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
|
||||
fix/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
|
||||
improve/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.7rc4
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.7rc5
|
||||
# so is regressionfix/...
|
||||
staging/maintenance 1.3.7rc4 9c5d996ea2b66a085392981a5e6e0ee341013674 pep440-dev
|
||||
regressionfix/.* 1.3.7rc4 9c5d996ea2b66a085392981a5e6e0ee341013674 pep440-dev
|
||||
staging/maintenance 1.3.7rc5 e5caa3d0bf77ed23f04c1d96ab0fa997d19d2006 pep440-dev
|
||||
regressionfix/.* 1.3.7rc5 e5caa3d0bf77ed23f04c1d96ab0fa997d19d2006 pep440-dev
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
|
||||
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||
@@ -75,6 +75,7 @@ date of first contribution):
|
||||
* [Mathias Rangel Wulff](https://github.com/mathiasrw)
|
||||
* [Clemens Niemeyer](https://github.com/clemniem)
|
||||
* ["I-am-me"](https://github.com/I-am-me)
|
||||
* [J-J Heinonen](https://github.com/jammi)
|
||||
* [Noah Martin](https://github.com/noahsmartin)
|
||||
* [Eyal Soha](https://github.com/eyal0)
|
||||
* [Greg Hulands](https://github.com/ghulands)
|
||||
@@ -87,6 +88,8 @@ date of first contribution):
|
||||
* [Josh Major](https://github.com/astateofblank)
|
||||
* ["alex-gh"](https://github.com/alex-gh)
|
||||
* [Bernd Zeimetz](https://github.com/bzed)
|
||||
* [Daniele Forsi](https://github.com/dforsi)
|
||||
* [Ganey](https://github.com/ganey)
|
||||
* [Zachary Nofzinger](https://github.com/ZachNo)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
|
||||
+56
-9
@@ -263,8 +263,11 @@ File information
|
||||
- Path to type of file in extension tree. E.g. ``["model", "stl"]`` for ``.stl`` files, or ``["machinecode", "gcode"]``
|
||||
for ``.gcode`` files. ``["folder"]`` for folders.
|
||||
|
||||
Additional properties depend on ``type``. For a ``type`` value of ``folder``, see "Folders". For any other value
|
||||
see "Files".
|
||||
Additional properties depend on ``type``.
|
||||
For a ``type`` value of ``folder``, see :ref:`Folders <sec-api-datamodel-files-folders>`.
|
||||
For any other value see :ref:`Files <sec-api-datamodel-files-files>`.
|
||||
|
||||
.. _sec-api-datamodel-files-folders:
|
||||
|
||||
Folders
|
||||
'''''''
|
||||
@@ -280,13 +283,14 @@ Folders
|
||||
* - ``children``
|
||||
- 0..*
|
||||
- Array of :ref:`File information items <sec-api-datamodel-files-file>`
|
||||
- Contained children for entries of type ``folder``. Will only include children in subfolders in recursive
|
||||
listings. Not present in non recursive listings, this might be revisited in the future.
|
||||
- Contained children for entries of type ``folder``. On non recursive listings only present on first level
|
||||
sub folders!
|
||||
* - ``size``
|
||||
- 0..1
|
||||
- Number
|
||||
- The size of all files contained in the folder and its subfolders. Not present in non recursive listings, this might
|
||||
be revisited in the future.
|
||||
- The size of all files contained in the folder and its subfolders. Not present in non recursive listings!
|
||||
|
||||
.. _sec-api-datamodel-files-files:
|
||||
|
||||
Files
|
||||
'''''
|
||||
@@ -385,14 +389,58 @@ GCODE analysis information
|
||||
- 0..1
|
||||
- Object
|
||||
- The estimated usage of filament
|
||||
* - ``filament.length``
|
||||
* - ``filament.tool{n}.length``
|
||||
- 0..1
|
||||
- Integer
|
||||
- The length of filament used, in mm
|
||||
* - ``filament.volume``
|
||||
* - ``filament.tool{n}.volume``
|
||||
- 0..1
|
||||
- Float
|
||||
- The volume of filament used, in cm³
|
||||
* - ``dimensions``
|
||||
- 0..1
|
||||
- Object
|
||||
- Information regarding the size of the printed model
|
||||
* - ``dimensions.depth``
|
||||
- 0..1
|
||||
- Float
|
||||
- The depth of the printed model, in mm
|
||||
* - ``dimensions.height``
|
||||
- 0..1
|
||||
- Float
|
||||
- The height of the printed model, in mm
|
||||
* - ``dimensions.width``
|
||||
- 0..1
|
||||
- Float
|
||||
- The width of the printed model, in mm
|
||||
* - ``printingArea``
|
||||
- 0..1
|
||||
- Object
|
||||
- Information regarding the size of the printing area
|
||||
* - ``printingArea.maxX``
|
||||
- 0..1
|
||||
- Float
|
||||
- The maximum X coordinate of the printed model, in mm
|
||||
* - ``printingArea.maxY``
|
||||
- 0..1
|
||||
- Float
|
||||
- The maximum Y coordinate of the printed model, in mm
|
||||
* - ``printingArea.maxZ``
|
||||
- 0..1
|
||||
- Float
|
||||
- The maximum Z coordinate of the printed model, in mm
|
||||
* - ``printingArea.minX``
|
||||
- 0..1
|
||||
- Float
|
||||
- The minimum X coordinate of the printed model, in mm
|
||||
* - ``printingArea.minY``
|
||||
- 0..1
|
||||
- Float
|
||||
- The minimum Y coordinate of the printed model, in mm
|
||||
* - ``printingArea.minZ``
|
||||
- 0..1
|
||||
- Float
|
||||
- The minimum Z coordinate of the printed model, in mm
|
||||
|
||||
|
||||
.. _sec-api-datamodel-files-ref:
|
||||
@@ -421,4 +469,3 @@ References
|
||||
- URL
|
||||
- The model from which this file was generated (e.g. an STL, currently not used). Never present for
|
||||
folders.
|
||||
|
||||
+32
-3
@@ -82,8 +82,37 @@ Retrieve all files
|
||||
"path": "folderA",
|
||||
"type": "folder",
|
||||
"typePath": ["folder"],
|
||||
"children": [],
|
||||
"size": 1334
|
||||
"children": [
|
||||
{
|
||||
"name": "whistle_v2_copy.gcode",
|
||||
"path": "whistle_v2_copy.gcode",
|
||||
"type": "machinecode",
|
||||
"typePath": ["machinecode", "gcode"],
|
||||
"hash": "...",
|
||||
"size": 1468987,
|
||||
"date": 1378847754,
|
||||
"origin": "local",
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/local/folderA/whistle_v2_copy.gcode",
|
||||
"download": "http://example.com/downloads/files/local/folderA/whistle_v2_copy.gcode"
|
||||
},
|
||||
"gcodeAnalysis": {
|
||||
"estimatedPrintTime": 1188,
|
||||
"filament": {
|
||||
"length": 810,
|
||||
"volume": 5.36
|
||||
}
|
||||
},
|
||||
"print": {
|
||||
"failure": 4,
|
||||
"success": 23,
|
||||
"last": {
|
||||
"date": 1387144346,
|
||||
"success": true
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"free": "3.2GB"
|
||||
@@ -443,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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -106,7 +106,7 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
|
||||
* - ``api.key``
|
||||
- Only maps to ``api.key`` in ``config.yaml`` if request is sent with admin rights, set to ``n/a`` otherwise.
|
||||
Starting with OctoPrint 1.3.3 setting this field via :ref:`the API <sec-api-settings-save>` is not possible,
|
||||
only :ref:`regenerting it <sec-api-settings-generateapikey>` is supported. Setting a custom value is only
|
||||
only :ref:`regenerating it <sec-api-settings-generateapikey>` is supported. Setting a custom value is only
|
||||
possible through `config.yaml`.
|
||||
* - ``api.allowCrossOrigin``
|
||||
-
|
||||
|
||||
@@ -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.
|
||||
@@ -893,7 +893,7 @@ Use the following settings to configure the serial connection to the printer:
|
||||
supportResendsWithoutOk: false
|
||||
|
||||
# Whether to "manually" trigger an ok for M29 (a lot of versions of this command are buggy and
|
||||
# the responds skips on the ok)
|
||||
# the response skips on the ok)
|
||||
triggerOkForM29: true
|
||||
|
||||
capabilities:
|
||||
@@ -934,7 +934,7 @@ Use the following settings to configure the server:
|
||||
|
||||
# Settings if OctoPrint is running behind a reverse proxy (haproxy, nginx, apache, ...).
|
||||
# These are necessary in order to make OctoPrint generate correct external URLs so
|
||||
# that AJAX requests and download URLs work.
|
||||
# that AJAX requests and download URLs work, and so that client IPs are read correctly.
|
||||
reverseProxy:
|
||||
|
||||
# The request header from which to determine the URL prefix under which OctoPrint
|
||||
@@ -968,6 +968,14 @@ Use the following settings to configure the server:
|
||||
# (X-Forwarded-Host by default, see above) with forwarded requests.
|
||||
hostFallback:
|
||||
|
||||
# List of trusted downstream servers for which to ignore the IP address when trying to determine
|
||||
# the connecting client's IP address. If you have OctoPrint behind more than one reverse proxy
|
||||
# you should add their IPs here so that they won't be interpreted as the client's IP. One reverse
|
||||
# proxy will be handled correctly by default.
|
||||
trustedDownstream:
|
||||
- 192.168.1.254
|
||||
- 192.168.23.42
|
||||
|
||||
# Settings for file uploads to OctoPrint, such as maximum allowed file size and
|
||||
# header suffixes to use for streaming uploads. OctoPrint does some nifty things internally in
|
||||
# order to allow streaming of large file uploads to the application rather than just storing
|
||||
@@ -1092,7 +1100,12 @@ System
|
||||
|
||||
Use the following settings to add custom system commands to the "System" dropdown within OctoPrint's top bar.
|
||||
|
||||
Commands consist of a name, an action identifier, the commandline to execute and an optional confirmation message to
|
||||
Commands consist of a ``name`` shown to the user, an ``action`` identifier used by the code and the actual
|
||||
``command`` including any argument needed for its execution.
|
||||
By default OctoPrint blocks until the command has returned so that the exit code can be used to show a success
|
||||
or failure message; use the flag ``async: true`` for commands that don't return.
|
||||
|
||||
Optionally you can add a confirmation message to
|
||||
display before actually executing the command (should be set to False if a confirmation dialog is not desired).
|
||||
|
||||
The following example defines a command for shutting down the system under Linux. It assumes that the user under which
|
||||
|
||||
@@ -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::
|
||||
|
||||
|
||||
@@ -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``
|
||||
|
||||
@@ -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:**
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
+33
-1
@@ -66,7 +66,7 @@ the general type of script for which to look for additions ("gcode") and the scr
|
||||
return a 2-tuple of prefix and postfix if has something for either of those, otherwise ``None``. OctoPrint will then take
|
||||
care to add prefix and suffix as necessary after a small round of preprocessing.
|
||||
|
||||
Plugins can easily add their own hooks too. For example, the `Software Update Plugin <https://github.com/OctoPrint/OctoPrint-SoftwareUpdate>`_
|
||||
Plugins can easily add their own hooks too. For example, the `Software Update Plugin <https://github.com/foosel/OctoPrint/tree/master/src/octoprint/plugins/softwareupdate>`_
|
||||
declares a custom hook "octoprint.plugin.softwareupdate.check_config" which other plugins can add handlers for in order
|
||||
to register themselves with the Software Update Plugin by returning their own update check configuration.
|
||||
|
||||
@@ -1151,3 +1151,35 @@ octoprint.users.factory
|
||||
:return: The ``userManager`` instance to use globally.
|
||||
:rtype: UserManager subclass or None
|
||||
|
||||
|
||||
.. _sec-plugins-hook-timelapse-capture-pre:
|
||||
|
||||
octoprint.timelapse.capture.pre
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: capture_pre_hook(filename)
|
||||
|
||||
Perform specific actions prior to capturing a timelapse frame.
|
||||
|
||||
``filename`` will be the future path of the frame to be saved.
|
||||
|
||||
:param str filename: The future path of the frame to be saved.
|
||||
:return: None
|
||||
:rtype: None
|
||||
|
||||
.. _sec-plugins-hook-timelapse-capture-post:
|
||||
|
||||
octoprint.timelapse.capture.post
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. py:function:: capture_post_hook(filename, success)
|
||||
|
||||
Perform specific actions after capturing a timelapse frame.
|
||||
|
||||
``filename`` will be the path of the frame that should have been saved.
|
||||
``sucesss`` indicates whether the capture was successful or not.
|
||||
|
||||
:param str filename: The path of the frame that should have been saved.
|
||||
:param boolean success: Indicates whether the capture was successful or not.
|
||||
:return: None
|
||||
:rtype: None
|
||||
@@ -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,
|
||||
|
||||
@@ -14,35 +14,33 @@ import octoprint_setuptools
|
||||
|
||||
# Requirements for our application
|
||||
INSTALL_REQUIRES = [
|
||||
"flask>=0.9,<0.11",
|
||||
"flask>=0.12,<0.13",
|
||||
"werkzeug>=0.11.1,<0.12",
|
||||
"tornado>=5.0.1,<6",
|
||||
"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
|
||||
"werkzeug>=0.8.3,<0.9",
|
||||
"tornado==4.0.2", # pinned for now, we need to migrate to a newer tornado, but due
|
||||
# to some voodoo needed to get large streamed uploads and downloads
|
||||
# to work that is probably not completely straightforward and therefore
|
||||
# something for post-1.3.0-stable release
|
||||
"sockjs-tornado>=1.0.3,<1.1",
|
||||
"PyYAML>=3.10,<3.11",
|
||||
"Flask-Login>=0.2.2,<0.3",
|
||||
"Flask-Principal>=0.3.5,<0.4",
|
||||
"Flask-Babel>=0.9,<0.10",
|
||||
"Flask-Assets>=0.10,<0.11",
|
||||
#"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",
|
||||
"Flask-Babel>=0.11,<0.12",
|
||||
"Flask-Assets>=0.12,<0.13",
|
||||
"markdown>=2.6.4,<2.7",
|
||||
"pyserial>=2.7,<3.5",
|
||||
"pyserial>=3.4,<3.5",
|
||||
"netaddr>=0.7.17,<0.8",
|
||||
"watchdog>=0.8.3,<0.9",
|
||||
"sarge>=0.1.4,<0.2",
|
||||
"netifaces>=0.10,<0.11",
|
||||
"pylru>=1.0.9,<1.1",
|
||||
"rsa>=3.2,<3.3",
|
||||
"pkginfo>=1.2.1,<1.3",
|
||||
"rsa>=3.4,<3.5",
|
||||
"pkginfo>=1.4.1,<1.5",
|
||||
"requests>=2.18.4,<3",
|
||||
"semantic_version>=2.4.2,<2.5",
|
||||
"semantic_version>=2.6.0,<2.7",
|
||||
"psutil==5.4.3", # 5.4.4 introduced a breaking change concerning installing under non current
|
||||
# setuptools versions. Pinning to 5.4.3 for now to work around this.
|
||||
"Click>=6.2,<6.3",
|
||||
"Click>=6.7,<6.8",
|
||||
"awesome-slugify>=1.6.5,<1.7",
|
||||
"feedparser>=5.2.1,<5.3",
|
||||
"chainmap>=1.0.2,<1.1",
|
||||
@@ -81,7 +79,7 @@ EXTRA_REQUIRES = dict(
|
||||
|
||||
# Dependencies for developing OctoPrint plugins
|
||||
plugins=[
|
||||
"cookiecutter>=1.4,<1.7"
|
||||
"cookiecutter>=1.5,<1.7"
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@@ -198,7 +198,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
|
||||
},
|
||||
"handlers": {
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
"class": "octoprint.logging.handlers.OctoPrintStreamHandler",
|
||||
"level": "DEBUG",
|
||||
"formatter": "simple",
|
||||
"stream": "ext://sys.stdout"
|
||||
|
||||
@@ -153,7 +153,8 @@ class StorageInterface(object):
|
||||
from root of base folder
|
||||
:param function filter: a filter that matches the files that are to be returned, may be left out in which case no
|
||||
filtering will take place
|
||||
:param bool recursive: will also step into sub folders for building the complete list if set to True
|
||||
:param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only
|
||||
do one step down into sub folders to be able to populate the ``children``.
|
||||
:return: a dictionary mapping entry names to entry data that represents the whole file list
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
@@ -183,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
|
||||
@@ -232,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
|
||||
@@ -1277,7 +1278,7 @@ class LocalFileStorage(StorageInterface):
|
||||
if metadata_dirty:
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def _list_folder(self, path, base="", entry_filter=None, recursive=True, **kwargs):
|
||||
def _list_folder(self, path, base="", entry_filter=None, recursive=True, include_children=True, **kwargs):
|
||||
if entry_filter is None:
|
||||
entry_filter = kwargs.get("filter", None)
|
||||
|
||||
@@ -1385,8 +1386,14 @@ class LocalFileStorage(StorageInterface):
|
||||
sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter,
|
||||
recursive=recursive)
|
||||
entry_data["children"] = sub_result
|
||||
elif include_children:
|
||||
sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter,
|
||||
recursive=False, include_children=False)
|
||||
entry_data["children"] = sub_result
|
||||
|
||||
if not entry_filter or entry_filter(entry_name, entry_data):
|
||||
# only add folders passing the optional filter
|
||||
|
||||
def get_size():
|
||||
total_size = 0
|
||||
for element in entry_data["children"].values():
|
||||
@@ -1395,7 +1402,6 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
return total_size
|
||||
|
||||
# only add folders passing the optional filter
|
||||
extended_entry_data = dict()
|
||||
extended_entry_data.update(entry_data)
|
||||
if recursive:
|
||||
|
||||
@@ -6,10 +6,30 @@ import os
|
||||
import re
|
||||
import time
|
||||
|
||||
# noinspection PyCompatibility
|
||||
import concurrent.futures
|
||||
|
||||
|
||||
class AsyncLogHandlerMixin(logging.Handler):
|
||||
def __init__(self, *args, **kwargs):
|
||||
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
||||
super(AsyncLogHandlerMixin, self).__init__(*args, **kwargs)
|
||||
|
||||
def emit(self, record):
|
||||
try:
|
||||
self._executor.submit(self._emit, record)
|
||||
except:
|
||||
self.handleError(record)
|
||||
|
||||
def _emit(self, record):
|
||||
# noinspection PyUnresolvedReferences
|
||||
super(AsyncLogHandlerMixin, self).emit(record)
|
||||
|
||||
|
||||
class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
logging.handlers.TimedRotatingFileHandler.__init__(self, *args, **kwargs)
|
||||
super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs)
|
||||
|
||||
# clean up old files on handler start
|
||||
if self.backupCount > 0:
|
||||
@@ -17,7 +37,7 @@ class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler
|
||||
os.remove(s)
|
||||
|
||||
|
||||
class OctoPrintLogHandler(CleaningTimedRotatingFileHandler):
|
||||
class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler):
|
||||
rollover_callbacks = []
|
||||
|
||||
@classmethod
|
||||
@@ -25,32 +45,33 @@ class OctoPrintLogHandler(CleaningTimedRotatingFileHandler):
|
||||
cls.rollover_callbacks.append((callback, args, kwargs))
|
||||
|
||||
def doRollover(self):
|
||||
CleaningTimedRotatingFileHandler.doRollover(self)
|
||||
super(OctoPrintLogHandler, self).doRollover()
|
||||
|
||||
for rcb in self.rollover_callbacks:
|
||||
callback, args, kwargs = rcb
|
||||
callback(*args, **kwargs)
|
||||
|
||||
|
||||
class SerialLogHandler(logging.handlers.RotatingFileHandler):
|
||||
class OctoPrintStreamHandler(AsyncLogHandlerMixin, logging.StreamHandler):
|
||||
pass
|
||||
|
||||
_do_rollover = False
|
||||
_suffix_template = "%Y-%m-%d_%H-%M-%S"
|
||||
_file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
|
||||
|
||||
class SerialLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler):
|
||||
|
||||
do_rollover = False
|
||||
suffix_template = "%Y-%m-%d_%H-%M-%S"
|
||||
file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
|
||||
|
||||
@classmethod
|
||||
def on_open_connection(cls):
|
||||
cls._do_rollover = True
|
||||
cls.do_rollover = True
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
logging.handlers.RotatingFileHandler.__init__(self, *args, **kwargs)
|
||||
super(SerialLogHandler, self).__init__(*args, **kwargs)
|
||||
self.cleanupFiles()
|
||||
|
||||
def emit(self, record):
|
||||
logging.handlers.RotatingFileHandler.emit(self, record)
|
||||
|
||||
def shouldRollover(self, record):
|
||||
return self.__class__._do_rollover
|
||||
return type(self).do_rollover
|
||||
|
||||
def getFilesToDelete(self):
|
||||
"""
|
||||
@@ -64,7 +85,7 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
|
||||
for fileName in fileNames:
|
||||
if fileName[:plen] == prefix:
|
||||
suffix = fileName[plen:]
|
||||
if self.__class__._file_pattern.match(suffix):
|
||||
if type(self).file_pattern.match(suffix):
|
||||
result.append(os.path.join(dirName, fileName))
|
||||
result.sort()
|
||||
if len(result) < self.backupCount:
|
||||
@@ -88,7 +109,7 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
|
||||
if os.path.exists(self.baseFilename):
|
||||
# figure out creation date/time to use for file suffix
|
||||
t = time.localtime(os.stat(self.baseFilename).st_mtime)
|
||||
dfn = self.baseFilename + "." + time.strftime(self.__class__._suffix_template, t)
|
||||
dfn = self.baseFilename + "." + time.strftime(type(self).suffix_template, t)
|
||||
if os.path.exists(dfn):
|
||||
os.remove(dfn)
|
||||
os.rename(self.baseFilename, dfn)
|
||||
@@ -98,8 +119,8 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
|
||||
self.stream = self._open()
|
||||
|
||||
class RecordingLogHandler(logging.Handler):
|
||||
def __init__(self, target=None, level=logging.NOTSET):
|
||||
logging.Handler.__init__(self, level=level)
|
||||
def __init__(self, target=None, *args, **kwargs):
|
||||
super(RecordingLogHandler, self).__init__(*args, **kwargs)
|
||||
self._buffer = []
|
||||
self._target = target
|
||||
|
||||
@@ -133,6 +154,7 @@ class RecordingLogHandler(logging.Handler):
|
||||
return len(self._buffer)
|
||||
|
||||
|
||||
# noinspection PyAbstractClass
|
||||
class CombinedLogHandler(logging.Handler):
|
||||
def __init__(self, *handlers):
|
||||
logging.Handler.__init__(self)
|
||||
|
||||
@@ -1443,7 +1443,7 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
Make sure to protect sensitive information stored by your plugin that only logged in administrators (or users)
|
||||
should have access to via :meth:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths`. OctoPrint will
|
||||
return its settings on the REST API even to anonymous clients, but will filter out fields it know are restricted,
|
||||
return its settings on the REST API even to anonymous clients, but will filter out fields it knows are restricted,
|
||||
therefore you **must** make sure that you specify sensitive information accordingly to limit access as required!
|
||||
"""
|
||||
|
||||
@@ -1527,8 +1527,8 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
else:
|
||||
node[key] = None
|
||||
|
||||
conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous(),
|
||||
admin=lambda: current_user is not None and not current_user.is_anonymous() and current_user.is_admin(),
|
||||
conditions = dict(user=lambda: current_user is not None and not current_user.is_anonymous,
|
||||
admin=lambda: current_user is not None and not current_user.is_anonymous and current_user.is_admin,
|
||||
never=lambda: False)
|
||||
|
||||
for level, condition in conditions.items():
|
||||
|
||||
@@ -74,9 +74,9 @@ class AclSubwizard(object):
|
||||
if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.hasBeenCustomized():
|
||||
abort(404)
|
||||
|
||||
data = request.values
|
||||
if hasattr(request, "json") and request.json:
|
||||
data = request.json
|
||||
data = request.get_json()
|
||||
if data is None:
|
||||
data = request.values
|
||||
|
||||
if "ac" in data and data["ac"] in valid_boolean_trues and \
|
||||
"user" in data.keys() and "pass1" in data.keys() and \
|
||||
|
||||
@@ -52,7 +52,7 @@
|
||||
</form>
|
||||
<small>{% trans %}
|
||||
You can import your existing profile <code>.ini</code> files from <strong>Cura 15.04.x or older</strong>
|
||||
here. Anything but those are <strong>not supported</strong>. That especiallymeans that <code>.json</code>
|
||||
here. Anything but those are <strong>not supported</strong>. That especially means that <code>.json</code>
|
||||
profiles from Cura 15.06.x and <code>.curaprofile</code> profiles from Cura 2.x will not work, and neither
|
||||
will custom Cura profile formats that third party tools like e.g. Repetier create.
|
||||
{% endtrans %}</small>
|
||||
|
||||
@@ -333,7 +333,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
raise ValueError("Either URL or path must be provided")
|
||||
|
||||
self._logger.info("Installing plugin from {}".format(source))
|
||||
pip_args = ["install", sarge.shell_quote(source)]
|
||||
pip_args = ["install", sarge.shell_quote(source), '--no-cache-dir']
|
||||
|
||||
if dependency_links or self._settings.get_boolean(["dependency_links"]):
|
||||
pip_args.append("--process-dependency-links")
|
||||
|
||||
@@ -1 +1 @@
|
||||
table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px;padding-right:12px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px 10px 5px 5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
|
||||
@@ -23,13 +23,6 @@ table {
|
||||
}
|
||||
|
||||
#settings_plugin_pluginmanager_repositorydialog {
|
||||
.slimScrollDiv {
|
||||
@scrollBar: 10px;
|
||||
|
||||
margin-bottom: 20px;
|
||||
padding-right: @scrollBar + 2px;
|
||||
}
|
||||
|
||||
h4 {
|
||||
position: relative;
|
||||
|
||||
@@ -75,14 +68,15 @@ table {
|
||||
}
|
||||
|
||||
#settings_plugin_pluginmanager_repositorydialog_list {
|
||||
overflow: hidden;
|
||||
width: auto;
|
||||
height: 300px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: scroll;
|
||||
padding-right: 2px;
|
||||
|
||||
.entry {
|
||||
border-bottom: 1px solid #ddd;
|
||||
padding: 5px;
|
||||
padding-right: 10px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,7 +155,7 @@
|
||||
</form>
|
||||
|
||||
<div data-bind="visible: repositoryAvailable()">
|
||||
<div id="settings_plugin_pluginmanager_repositorydialog_list" data-bind="slimScrolledForeach: {data: repositoryplugins.paginatedItems, slimscroll: {height: '306px', size: '10px', distance: 0, railVisible: true, alwaysVisible: true, scrollBy: '102px'} }">
|
||||
<div id="settings_plugin_pluginmanager_repositorydialog_list" data-bind="foreach: repositoryplugins.paginatedItems">
|
||||
<div class="entry">
|
||||
<div class="row-fluid">
|
||||
<div class="span9">
|
||||
@@ -245,57 +245,64 @@
|
||||
<form class="form-horizontal">
|
||||
<p>{% trans %}You should normally <strong>not</strong> have to change <strong>any</strong> of the following settings, they are purely provided for convenience here.{% endtrans %}</p>
|
||||
|
||||
<legend>{{ _('Plugin repository configuration') }}</legend>
|
||||
<fieldset>
|
||||
<legend>{{ _('Plugin repository configuration') }}</legend>
|
||||
|
||||
<div class="control-group" title="{{ _('URL of the Plugin Repository to use. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Repository URL') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_repositoryUrl">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('How long to cache repository data, in minutes. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Repository cache TTL') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" class="input-mini" data-bind="value: config_repositoryTtl">
|
||||
<span class="add-on">min</span>
|
||||
<div class="control-group" title="{{ _('URL of the Plugin Repository to use. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Repository URL') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_repositoryUrl">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<legend>{{ _('Notices configuration') }}</legend>
|
||||
|
||||
<div class="control-group" title="{{ _('URL of the Notices source to use. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Notices URL') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_noticesUrl">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('How long to cache notices, in minutes. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Notices cache TTL') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" class="input-mini" data-bind="value: config_noticesTtl">
|
||||
<span class="add-on">min</span>
|
||||
<div class="control-group" title="{{ _('How long to cache repository data, in minutes. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Repository cache TTL') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" class="input-mini" data-bind="value: config_repositoryTtl">
|
||||
<span class="add-on">min</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<legend>{{ _('pip configuration') }}</legend>
|
||||
<fieldset>
|
||||
<legend>{{ _('Notices configuration') }}</legend>
|
||||
|
||||
<div class="control-group" title="{{ _('Additional arguments for the pip command. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Additional arguments') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_pipAdditionalArgs">
|
||||
<div class="control-group" title="{{ _('URL of the Notices source to use. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Notices URL') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_noticesUrl">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: config_pipForceUser"> {{ _('Force the use of the <code>--user</code> flag with <code>pip install</code>') }}
|
||||
</label>
|
||||
<div class="control-group" title="{{ _('How long to cache notices, in minutes. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Notices cache TTL') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" class="input-mini" data-bind="value: config_noticesTtl">
|
||||
<span class="add-on">min</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset>
|
||||
<legend>{{ _('pip configuration') }}</legend>
|
||||
|
||||
<div class="control-group" title="{{ _('Additional arguments for the pip command. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Additional arguments') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_pipAdditionalArgs">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: config_pipForceUser"> {{ _('Force the use of the <code>--user</code> flag with <code>pip install</code>') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
|
||||
@@ -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,23 +89,36 @@ 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
|
||||
|
||||
##~~ 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()
|
||||
@@ -107,4 +140,7 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will n
|
||||
"issue and inform you about that fact.")
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = PrinterSafetyCheckPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received
|
||||
}
|
||||
|
||||
@@ -538,7 +538,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if not "application/json" in flask.request.headers["Content-Type"]:
|
||||
return flask.make_response("Expected content-type JSON", 400)
|
||||
|
||||
json_data = flask.request.json
|
||||
json_data = flask.request.get_json(silent=True)
|
||||
if json_data is None:
|
||||
return flask.make_response("Invalid JSON", 400)
|
||||
|
||||
if "check" in json_data:
|
||||
check_targets = map(lambda x: x.strip(), json_data["check"])
|
||||
|
||||
@@ -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, AnonymousIdentity
|
||||
@@ -71,6 +71,7 @@ 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
|
||||
@@ -97,9 +98,9 @@ def on_identity_loaded(sender, identity):
|
||||
return
|
||||
|
||||
identity.provides.add(UserNeed(user.get_id()))
|
||||
if user.is_user():
|
||||
if user.is_user:
|
||||
identity.provides.add(RoleNeed("user"))
|
||||
if user.is_admin():
|
||||
if user.is_admin:
|
||||
identity.provides.add(RoleNeed("admin"))
|
||||
|
||||
|
||||
@@ -142,7 +143,7 @@ def load_user(id):
|
||||
else:
|
||||
user = userManager.findUser(userid=id)
|
||||
|
||||
if user and user.is_active():
|
||||
if user and user.is_active:
|
||||
return user
|
||||
|
||||
return None
|
||||
@@ -160,7 +161,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
|
||||
@@ -217,12 +218,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 a bunch of stuff
|
||||
util.tornado.fix_ioloop_scheduling()
|
||||
# monkey patch some stuff
|
||||
util.tornado.fix_json_encode()
|
||||
util.flask.enable_additional_translations(additional_folders=[self._settings.getBaseFolder("translations")])
|
||||
|
||||
@@ -471,13 +489,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)
|
||||
@@ -618,8 +631,18 @@ class Server(object):
|
||||
self._stop_intermediary_server()
|
||||
|
||||
# initialize and bind the server
|
||||
self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=self._settings.getInt(["server", "maxSize"]))
|
||||
self._server.listen(self._port, address=self._host)
|
||||
trusted_downstream = self._settings.get(["server", "reverseProxy", "trustedDownstream"])
|
||||
if not isinstance(trusted_downstream, list):
|
||||
self._logger.warn("server.reverseProxy.trustedDownstream is not a list, skipping")
|
||||
trusted_downstreams = []
|
||||
self._server = util.tornado.CustomHTTPServer(self._tornado_app,
|
||||
max_body_sizes=max_body_sizes,
|
||||
default_max_body_size=self._settings.getInt(["server", "maxSize"]),
|
||||
xheaders=True,
|
||||
trusted_downstream=trusted_downstream)
|
||||
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
|
||||
|
||||
@@ -664,7 +687,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")
|
||||
@@ -736,7 +760,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):
|
||||
@@ -785,11 +811,13 @@ class Server(object):
|
||||
timer.start()
|
||||
|
||||
def _setup_app(self, app):
|
||||
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse, OctoPrintJsonEncoder
|
||||
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, \
|
||||
OctoPrintFlaskResponse, OctoPrintJsonEncoder, OctoPrintSessionInterface
|
||||
|
||||
s = settings()
|
||||
|
||||
app.debug = self._debug
|
||||
app.config["TEMPLATES_AUTO_RELOAD"] = True
|
||||
|
||||
app.json_encoder = OctoPrintJsonEncoder
|
||||
|
||||
@@ -820,6 +848,7 @@ class Server(object):
|
||||
OctoPrintFlaskRequest.environment_wrapper = reverse_proxied
|
||||
app.request_class = OctoPrintFlaskRequest
|
||||
app.response_class = OctoPrintFlaskResponse
|
||||
app.session_interface = OctoPrintSessionInterface()
|
||||
|
||||
@app.before_request
|
||||
def before_request():
|
||||
@@ -1315,25 +1344,13 @@ class Server(object):
|
||||
js_filters = ["sourcemap_remove", "js_delimiter_bundler"]
|
||||
js_plugin_filters = ["sourcemap_remove", "js_delimiter_bundler"]
|
||||
|
||||
if self._settings.getBoolean(["feature", "legacyPluginAssets"]):
|
||||
# TODO remove again in 1.3.8
|
||||
def js_bundles_for_plugins(collection, filters=None):
|
||||
"""Produces Bundle instances"""
|
||||
result = OrderedDict()
|
||||
for plugin, assets in collection.items():
|
||||
if len(assets):
|
||||
result[plugin] = Bundle(*assets, filters=filters)
|
||||
return result
|
||||
|
||||
else:
|
||||
def js_bundles_for_plugins(collection, filters=None):
|
||||
"""Produces JsPluginBundle instances that output IIFE wrapped assets"""
|
||||
result = OrderedDict()
|
||||
for plugin, assets in collection.items():
|
||||
if len(assets):
|
||||
result[plugin] = JsPluginBundle(plugin, *assets, filters=filters)
|
||||
return result
|
||||
|
||||
def js_bundles_for_plugins(collection, filters=None):
|
||||
"""Produces JsPluginBundle instances that output IIFE wrapped assets"""
|
||||
result = OrderedDict()
|
||||
for plugin, assets in collection.items():
|
||||
if len(assets):
|
||||
result[plugin] = JsPluginBundle(plugin, *assets, filters=filters)
|
||||
return result
|
||||
|
||||
js_core = dynamic_core_assets["js"] + \
|
||||
all_assets_for_plugins(dynamic_plugin_assets["bundled"]["js"]) + \
|
||||
@@ -1447,6 +1464,7 @@ class Server(object):
|
||||
loginManager = LoginManager()
|
||||
loginManager.session_protection = "strong"
|
||||
loginManager.user_callback = load_user
|
||||
loginManager.anonymous_user = users.AnonymousUser # TODO: remove in 1.5.0
|
||||
loginManager.unauthorized_callback = unauthorized_user
|
||||
|
||||
# login users authenticated by basic auth
|
||||
@@ -1462,15 +1480,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):
|
||||
@@ -1527,9 +1540,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
|
||||
|
||||
@@ -62,7 +62,7 @@ def pluginData(name):
|
||||
return make_response("More than one api provider registered for {name}, can't proceed".format(name=name), 500)
|
||||
|
||||
api_plugin = api_plugins[0]
|
||||
if api_plugin.is_api_adminonly() and not current_user.is_admin():
|
||||
if api_plugin.is_api_adminonly() and not current_user.is_admin:
|
||||
return make_response("Forbidden", 403)
|
||||
|
||||
response = api_plugin.on_api_get(request)
|
||||
@@ -89,7 +89,7 @@ def pluginCommand(name):
|
||||
if valid_commands is None:
|
||||
return make_response("Method not allowed", 405)
|
||||
|
||||
if api_plugin.is_api_adminonly() and not current_user.is_admin():
|
||||
if api_plugin.is_api_adminonly() and not current_user.is_admin:
|
||||
return make_response("Forbidden", 403)
|
||||
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
@@ -134,10 +134,13 @@ def wizardFinish():
|
||||
|
||||
data = dict()
|
||||
try:
|
||||
data = request.json
|
||||
data = request.get_json()
|
||||
except:
|
||||
abort(400)
|
||||
|
||||
if data is None:
|
||||
abort(400)
|
||||
|
||||
if not "handled" in data:
|
||||
abort(400)
|
||||
handled = data["handled"]
|
||||
@@ -186,9 +189,9 @@ def apiVersion():
|
||||
|
||||
@api.route("/login", methods=["POST"])
|
||||
def login():
|
||||
data = request.values
|
||||
if hasattr(request, "json") and request.json:
|
||||
data = request.json
|
||||
data = request.get_json()
|
||||
if data is None:
|
||||
data = request.values
|
||||
|
||||
if octoprint.server.userManager.enabled and "user" in data and "pass" in data:
|
||||
username = data["user"]
|
||||
@@ -205,7 +208,7 @@ def login():
|
||||
user = octoprint.server.userManager.findUser(username)
|
||||
if user is not None:
|
||||
if octoprint.server.userManager.checkPassword(username, password):
|
||||
if not user.is_active():
|
||||
if not user.is_active:
|
||||
return make_response(("Your account is deactivated", 403, []))
|
||||
|
||||
if octoprint.server.userManager.enabled:
|
||||
|
||||
@@ -334,10 +334,13 @@ def printerCommand():
|
||||
return make_response("Expected content type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if "command" in data and "commands" in data:
|
||||
return make_response("'command' and 'commands' are mutually exclusive", 400)
|
||||
elif ("command" in data or "commands" in data) and "script" in data:
|
||||
|
||||
@@ -51,10 +51,13 @@ def printerProfilesAdd():
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
json_data = request.json
|
||||
json_data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if json_data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "profile" in json_data:
|
||||
return make_response("No profile included in request", 400)
|
||||
|
||||
@@ -124,10 +127,13 @@ def printerProfilesUpdate(identifier):
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
json_data = request.json
|
||||
json_data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if json_data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "profile" in json_data:
|
||||
return make_response("No profile included in request", 400)
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ def _etag(lm=None):
|
||||
for key in sorted(plugin_settings.keys()):
|
||||
sorted_plugin_settings[key] = plugin_settings.get(key, dict())
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous():
|
||||
if current_user is not None and not current_user.is_anonymous:
|
||||
roles = sorted(current_user.roles)
|
||||
else:
|
||||
roles = []
|
||||
@@ -122,8 +122,7 @@ def getSettings():
|
||||
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]),
|
||||
"printCancelConfirmation": s.getBoolean(["feature", "printCancelConfirmation"]),
|
||||
"g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"]),
|
||||
"autoUppercaseBlacklist": s.get(["feature", "autoUppercaseBlacklist"]),
|
||||
"legacyPluginAssets": s.getBoolean(["feature", "legacyPluginAssets"])
|
||||
"autoUppercaseBlacklist": s.get(["feature", "autoUppercaseBlacklist"])
|
||||
},
|
||||
"serial": {
|
||||
"port": connectionOptions["portPreference"],
|
||||
@@ -140,6 +139,7 @@ def getSettings():
|
||||
"timeoutTemperatureAutoreport": s.getFloat(["serial", "timeout", "temperatureAutoreport"]),
|
||||
"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
|
||||
"timeoutSdStatusAutoreport": s.getFloat(["serial", "timeout", "sdStatusAutoreport"]),
|
||||
"timeoutBaudrateDetectionPause": s.getFloat(["serial", "timeout", "baudrateDetectionPause"]),
|
||||
"log": s.getBoolean(["serial", "log"]),
|
||||
"additionalPorts": s.get(["serial", "additionalPorts"]),
|
||||
"additionalBaudrates": s.get(["serial", "additionalBaudrates"]),
|
||||
@@ -281,10 +281,13 @@ def setSettings():
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not isinstance(data, dict):
|
||||
return make_response("Malformed request, need settings dictionary, "
|
||||
"got a {} instead: {!r}".format(type(data).__name__, data), 400)
|
||||
@@ -357,7 +360,6 @@ def _saveSettings(data):
|
||||
if "modelSizeDetection" in data["feature"]: s.setBoolean(["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"])
|
||||
if "printCancelConfirmation" in data["feature"]: s.setBoolean(["feature", "printCancelConfirmation"], data["feature"]["printCancelConfirmation"])
|
||||
if "g90InfluencesExtruder" in data["feature"]: s.setBoolean(["feature", "g90InfluencesExtruder"], data["feature"]["g90InfluencesExtruder"])
|
||||
if "legacyPluginAssets" in data["feature"]: s.setBoolean(["feature", "legacyPluginAssets"], data["feature"]["legacyPluginAssets"])
|
||||
if "autoUppercaseBlacklist" in data["feature"] and isinstance(data["feature"]["autoUppercaseBlacklist"], (list, tuple)): s.set(["feature", "autoUppercaseBlacklist"], data["feature"]["autoUppercaseBlacklist"])
|
||||
|
||||
if "serial" in data.keys():
|
||||
@@ -373,6 +375,7 @@ def _saveSettings(data):
|
||||
if "timeoutTemperatureAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureAutoreport"], data["serial"]["timeoutTemperatureAutoreport"])
|
||||
if "timeoutSdStatus" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
|
||||
if "timeoutSdStatusAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatusAutoreport"], data["serial"]["timeoutSdStatusAutoreport"])
|
||||
if "timeoutBaudrateDetectionPause" in data["serial"]: s.setFloat(["serial", "timeout", "baudrateDetectionPause"], data["serial"]["timeoutBaudrateDetectionPause"])
|
||||
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
|
||||
if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"])
|
||||
if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"])
|
||||
@@ -424,7 +427,16 @@ def _saveSettings(data):
|
||||
if "watched" in data["folder"]: s.setBaseFolder("watched", data["folder"]["watched"])
|
||||
|
||||
if "temperature" in data.keys():
|
||||
if "profiles" in data["temperature"]: s.set(["temperature", "profiles"], data["temperature"]["profiles"])
|
||||
if "profiles" in data["temperature"]:
|
||||
result = []
|
||||
for profile in data["temperature"]["profiles"]:
|
||||
try:
|
||||
profile["bed"] = int(profile["bed"])
|
||||
profile["extruder"] = int(profile["extruder"])
|
||||
except ValueError:
|
||||
pass
|
||||
result.append(profile)
|
||||
s.set(["temperature", "profiles"], result)
|
||||
if "cutoff" in data["temperature"]:
|
||||
try:
|
||||
cutoff = int(data["temperature"]["cutoff"])
|
||||
|
||||
@@ -131,10 +131,13 @@ def slicingAddSlicerProfile(slicer, name):
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
json_data = request.json
|
||||
json_data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if json_data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
data = dict()
|
||||
display_name = None
|
||||
description = None
|
||||
@@ -170,10 +173,13 @@ def slicingPatchSlicerProfile(slicer, name):
|
||||
return make_response("Profile {name} for slicer {slicer} not found".format(**locals()), 404)
|
||||
|
||||
try:
|
||||
json_data = request.json
|
||||
json_data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if json_data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
data = dict()
|
||||
display_name = None
|
||||
description = None
|
||||
|
||||
@@ -26,9 +26,9 @@ from octoprint.logging import prefix_multilines
|
||||
def performSystemAction():
|
||||
logging.getLogger(__name__).warn("Deprecated API call to /api/system made by {}, should be migrated to use /system/commands/custom/<action>".format(get_remote_address(request)))
|
||||
|
||||
data = request.values
|
||||
if hasattr(request, "json") and request.json:
|
||||
data = request.json
|
||||
data = request.get_json(silent=True)
|
||||
if data is None:
|
||||
data = request.values
|
||||
|
||||
if not "action" in data:
|
||||
return make_response("action to perform is not defined", 400)
|
||||
|
||||
@@ -170,9 +170,9 @@ def processUnrenderedTimelapseCommand(name):
|
||||
@api.route("/timelapse", methods=["POST"])
|
||||
@restricted_access
|
||||
def setTimelapseConfig():
|
||||
data = request.values
|
||||
if hasattr(request, "json") and request.json:
|
||||
data = request.json
|
||||
data = request.get_json(silent=True)
|
||||
if data is None:
|
||||
data = request.values
|
||||
|
||||
if "type" in data:
|
||||
config = {
|
||||
|
||||
@@ -40,10 +40,13 @@ def addUser():
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "name" in data:
|
||||
return make_response("Missing mandatory name field", 400)
|
||||
if not "password" in data:
|
||||
@@ -72,7 +75,7 @@ def getUser(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
|
||||
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin):
|
||||
user = userManager.findUser(username)
|
||||
if user is not None:
|
||||
return jsonify(user.asDict())
|
||||
@@ -95,10 +98,13 @@ def updateUser(username):
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
# change roles
|
||||
roles = ["user"]
|
||||
if "admin" in data and data["admin"] in valid_boolean_trues:
|
||||
@@ -133,15 +139,18 @@ def changePasswordForUser(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
|
||||
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "password" in data or not data["password"]:
|
||||
return make_response("password is missing from request", 400)
|
||||
|
||||
@@ -161,7 +170,7 @@ def getSettingsForUser(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is None or current_user.is_anonymous() or (current_user.get_name() != username and not current_user.is_admin()):
|
||||
if current_user is None or current_user.is_anonymous or (current_user.get_name() != username and not current_user.is_admin):
|
||||
return make_response("Forbidden", 403)
|
||||
|
||||
try:
|
||||
@@ -175,14 +184,17 @@ def changeSettingsForUser(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is None or current_user.is_anonymous() or (current_user.get_name() != username and not current_user.is_admin()):
|
||||
if current_user is None or current_user.is_anonymous or (current_user.get_name() != username and not current_user.is_admin):
|
||||
return make_response("Forbidden", 403)
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
try:
|
||||
userManager.changeUserSettings(username, data)
|
||||
return jsonify(SUCCESS)
|
||||
@@ -195,7 +207,7 @@ def deleteApikeyForUser(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
|
||||
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin):
|
||||
try:
|
||||
userManager.deleteApikey(username)
|
||||
except users.UnknownUser:
|
||||
@@ -211,7 +223,7 @@ def generateApikeyForUser(username):
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
|
||||
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin):
|
||||
try:
|
||||
apikey = userManager.generateApiKey(username)
|
||||
except users.UnknownUser:
|
||||
|
||||
@@ -29,7 +29,10 @@ def verifySessionKey():
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
data = request.json
|
||||
data = request.get_json()
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
for key in ("appid", "key", "_sig"):
|
||||
if not key in data:
|
||||
return make_response("Missing argument: {key}".format(key=key), 400)
|
||||
|
||||
@@ -75,6 +75,8 @@ def loginFromApiKeyRequestHandler():
|
||||
if not loginUser(user):
|
||||
return _flask.make_response("Invalid API key", 403)
|
||||
|
||||
_flask.g.login_via_apikey = True
|
||||
|
||||
|
||||
def loginFromAuthorizationHeaderRequestHandler():
|
||||
"""
|
||||
|
||||
@@ -498,6 +498,14 @@ class OctoPrintFlaskResponse(flask.Response):
|
||||
flask.Response.set_cookie(self, key, expires=0, max_age=0, path=path, domain=domain)
|
||||
|
||||
|
||||
class OctoPrintSessionInterface(flask.sessions.SecureCookieSessionInterface):
|
||||
|
||||
def save_session(self, app, session, response):
|
||||
if flask.g.get("login_via_apikey", False):
|
||||
return
|
||||
return super(OctoPrintSessionInterface, self).save_session(app, session, response)
|
||||
|
||||
|
||||
#~~ passive login helper
|
||||
|
||||
def passive_login():
|
||||
@@ -506,7 +514,7 @@ def passive_login():
|
||||
else:
|
||||
user = flask_login.current_user
|
||||
|
||||
if user is not None and not user.is_anonymous() and user.is_active():
|
||||
if user is not None and not user.is_anonymous and user.is_active:
|
||||
flask_principal.identity_changed.send(flask.current_app._get_current_object(),
|
||||
identity=flask_principal.Identity(user.get_id()))
|
||||
if hasattr(user, "session"):
|
||||
@@ -526,7 +534,7 @@ def passive_login():
|
||||
remoteAddr = get_remote_address(flask.request)
|
||||
if netaddr.IPAddress(remoteAddr) in localNetworks:
|
||||
user = octoprint.server.userManager.findUser(autologinAs)
|
||||
if user is not None and user.is_active():
|
||||
if user is not None and user.is_active:
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
flask.session["usersession.id"] = user.session
|
||||
flask.g.user = user
|
||||
@@ -1049,7 +1057,7 @@ def admin_validator(request):
|
||||
"""
|
||||
|
||||
user = _get_flask_user_from_request(request)
|
||||
if user is None or not user.is_authenticated() or not user.is_admin():
|
||||
if user is None or not user.is_authenticated or not user.is_admin:
|
||||
raise tornado.web.HTTPError(403)
|
||||
|
||||
|
||||
@@ -1064,7 +1072,7 @@ def user_validator(request):
|
||||
"""
|
||||
|
||||
user = _get_flask_user_from_request(request)
|
||||
if user is None or not user.is_authenticated():
|
||||
if user is None or not user.is_authenticated:
|
||||
raise tornado.web.HTTPError(403)
|
||||
|
||||
|
||||
@@ -1231,10 +1239,9 @@ def get_json_command_from_request(request, valid_commands):
|
||||
if content_type is None or not "application/json" in content_type:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
data = request.json
|
||||
data = request.get_json()
|
||||
if data is None:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
return None, None, make_response("Malformed JSON body or wrong content-type in request", 400)
|
||||
if not "command" in data.keys() or not data["command"] in valid_commands.keys():
|
||||
return None, None, make_response("Expected valid command", 400)
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -28,9 +28,9 @@ import wrapt
|
||||
import json
|
||||
|
||||
|
||||
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:
|
||||
@@ -44,10 +44,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")
|
||||
@@ -58,18 +58,18 @@ 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, octoprint.printer.PrinterCallback):
|
||||
class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback):
|
||||
def __init__(self, printer, fileManager, analysisQueue, userManager, 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__)
|
||||
|
||||
|
||||
@@ -7,11 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import logging
|
||||
import os
|
||||
import datetime
|
||||
import stat
|
||||
import mimetypes
|
||||
import email
|
||||
import time
|
||||
import re
|
||||
|
||||
import tornado
|
||||
@@ -29,35 +25,6 @@ import tornado.util
|
||||
import octoprint.util
|
||||
|
||||
|
||||
#~~ Monkey patching
|
||||
|
||||
|
||||
def fix_ioloop_scheduling():
|
||||
"""
|
||||
This monkey patches tornado's :meth:``tornado.ioloop.PeriodicCallback._schedule_next`` method so it no longer
|
||||
blocks for long times on slow machines (RPi) when the system time happens to change by a large amount (e.g. due to
|
||||
the first ever contact to an NTP server).
|
||||
|
||||
Patch by @nosyjoe on Github. See this PR against tornado: https://github.com/tornadoweb/tornado/pull/1290
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
# patched implementation taken from PR
|
||||
def _schedule_next(self):
|
||||
if self._running:
|
||||
current_time = self.io_loop.time()
|
||||
|
||||
if self._next_timeout <= current_time:
|
||||
callback_time_sec = self.callback_time / 1000.0
|
||||
self._next_timeout += (math.floor((current_time - self._next_timeout) / callback_time_sec) + 1) * callback_time_sec
|
||||
|
||||
self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)
|
||||
|
||||
# replace original implementation with patched version
|
||||
import tornado.ioloop
|
||||
tornado.ioloop.PeriodicCallback._schedule_next = _schedule_next
|
||||
|
||||
|
||||
def fix_json_encode():
|
||||
"""
|
||||
@@ -610,7 +577,8 @@ class WsgiInputContainer(object):
|
||||
if not data:
|
||||
raise Exception("WSGI app did not call start_response")
|
||||
|
||||
status_code = int(data["status"].split()[0])
|
||||
status_code, reason = data["status"].split(" ", 1)
|
||||
status_code = int(status_code)
|
||||
headers = data["headers"]
|
||||
header_set = set(k.lower() for (k, v) in headers)
|
||||
body = tornado.escape.utf8(body)
|
||||
@@ -628,13 +596,12 @@ class WsgiInputContainer(object):
|
||||
headers.append((header, value))
|
||||
headers = [(header, value) for header, value in headers if not header.lower() in self.removed_headers]
|
||||
|
||||
parts = [tornado.escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")]
|
||||
start_line = tornado.httputil.ResponseStartLine("HTTP/1.1", status_code, reason)
|
||||
header_obj = tornado.httputil.HTTPHeaders()
|
||||
for key, value in headers:
|
||||
parts.append(tornado.escape.utf8(key) + b": " + tornado.escape.utf8(value) + b"\r\n")
|
||||
parts.append(b"\r\n")
|
||||
parts.append(body)
|
||||
request.write(b"".join(parts))
|
||||
request.finish()
|
||||
header_obj.add(key, value)
|
||||
request.connection.write_headers(start_line, header_obj, chunk=body)
|
||||
request.connection.finish()
|
||||
self._log(status_code, request)
|
||||
|
||||
@staticmethod
|
||||
@@ -669,22 +636,22 @@ class WsgiInputContainer(object):
|
||||
host = request.host
|
||||
port = 443 if request.protocol == "https" else 80
|
||||
environ = {
|
||||
"REQUEST_METHOD": request.method,
|
||||
"SCRIPT_NAME": "",
|
||||
"PATH_INFO": to_wsgi_str(tornado.escape.url_unescape(
|
||||
request.path, encoding=None, plus=False)),
|
||||
"QUERY_STRING": request.query,
|
||||
"REMOTE_ADDR": request.remote_ip,
|
||||
"SERVER_NAME": host,
|
||||
"SERVER_PORT": str(port),
|
||||
"SERVER_PROTOCOL": request.version,
|
||||
"wsgi.version": (1, 0),
|
||||
"wsgi.url_scheme": request.protocol,
|
||||
"wsgi.input": request_body,
|
||||
"wsgi.errors": sys.stderr,
|
||||
"wsgi.multithread": False,
|
||||
"wsgi.multiprocess": True,
|
||||
"wsgi.run_once": False,
|
||||
"REQUEST_METHOD": request.method,
|
||||
"SCRIPT_NAME": "",
|
||||
"PATH_INFO": to_wsgi_str(tornado.escape.url_unescape(
|
||||
request.path, encoding=None, plus=False)),
|
||||
"QUERY_STRING": request.query,
|
||||
"REMOTE_ADDR": request.remote_ip,
|
||||
"SERVER_NAME": host,
|
||||
"SERVER_PORT": str(port),
|
||||
"SERVER_PROTOCOL": request.version,
|
||||
"wsgi.version": (1, 0),
|
||||
"wsgi.url_scheme": request.protocol,
|
||||
"wsgi.input": request_body,
|
||||
"wsgi.errors": sys.stderr,
|
||||
"wsgi.multithread": False,
|
||||
"wsgi.multiprocess": True,
|
||||
"wsgi.run_once": False,
|
||||
}
|
||||
if "Content-Type" in request.headers:
|
||||
environ["CONTENT_TYPE"] = request.headers.pop("Content-Type")
|
||||
@@ -705,7 +672,7 @@ class WsgiInputContainer(object):
|
||||
log_method = access_log.error
|
||||
request_time = 1000.0 * request.request_time()
|
||||
summary = request.method + " " + request.uri + " (" + \
|
||||
request.remote_ip + ")"
|
||||
request.remote_ip + ")"
|
||||
log_method("%d %s %.2fms", status_code, summary, request_time)
|
||||
|
||||
|
||||
@@ -728,36 +695,25 @@ class CustomHTTPServer(tornado.httpserver.HTTPServer):
|
||||
|
||||
``default_max_body_size`` is the default maximum body size to apply if no specific one from ``max_body_sizes`` matches.
|
||||
"""
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def __init__(self, request_callback, no_keep_alive=False, io_loop=None,
|
||||
xheaders=False, ssl_options=None, protocol=None,
|
||||
decompress_request=False,
|
||||
chunk_size=None, max_header_size=None,
|
||||
idle_connection_timeout=None, body_timeout=None,
|
||||
max_body_sizes=None, default_max_body_size=None, max_buffer_size=None):
|
||||
self.request_callback = request_callback
|
||||
self.no_keep_alive = no_keep_alive
|
||||
self.xheaders = xheaders
|
||||
self.protocol = protocol
|
||||
self.conn_params = CustomHTTP1ConnectionParameters(
|
||||
decompress=decompress_request,
|
||||
chunk_size=chunk_size,
|
||||
max_header_size=max_header_size,
|
||||
header_timeout=idle_connection_timeout or 3600,
|
||||
max_body_sizes=max_body_sizes,
|
||||
default_max_body_size=default_max_body_size,
|
||||
body_timeout=body_timeout)
|
||||
tornado.tcpserver.TCPServer.__init__(self, io_loop=io_loop, ssl_options=ssl_options,
|
||||
max_buffer_size=max_buffer_size,
|
||||
read_chunk_size=chunk_size)
|
||||
self._connections = set()
|
||||
def initialize(self, *args, **kwargs):
|
||||
default_max_body_size = kwargs.pop("default_max_body_size", None)
|
||||
max_body_sizes = kwargs.pop("max_body_sizes", None)
|
||||
|
||||
tornado.httpserver.HTTPServer.initialize(self, *args, **kwargs)
|
||||
|
||||
additional = dict(default_max_body_size=default_max_body_size,
|
||||
max_body_sizes=max_body_sizes)
|
||||
self.conn_params = CustomHTTP1ConnectionParameters.from_stock_params(self.conn_params, **additional)
|
||||
|
||||
|
||||
def handle_stream(self, stream, address):
|
||||
context = tornado.httpserver._HTTPRequestContext(stream, address,
|
||||
self.protocol)
|
||||
conn = CustomHTTP1ServerConnection(
|
||||
stream, self.conn_params, context)
|
||||
self.protocol,
|
||||
self.trusted_downstream)
|
||||
conn = CustomHTTP1ServerConnection(stream, self.conn_params, context)
|
||||
self._connections.add(conn)
|
||||
conn.start_serving(self)
|
||||
|
||||
@@ -774,7 +730,7 @@ class CustomHTTP1ServerConnection(tornado.http1connection.HTTP1ServerConnection)
|
||||
try:
|
||||
while True:
|
||||
conn = CustomHTTP1Connection(self.stream, False,
|
||||
self.params, self.context)
|
||||
self.params, self.context)
|
||||
request_delegate = delegate.start_request(self, conn)
|
||||
try:
|
||||
ret = yield conn.read_response(request_delegate)
|
||||
@@ -803,6 +759,9 @@ class CustomHTTP1Connection(tornado.http1connection.HTTP1Connection):
|
||||
"""
|
||||
|
||||
def __init__(self, stream, is_client, params=None, context=None):
|
||||
if params is None:
|
||||
params = CustomHTTP1ConnectionParameters()
|
||||
|
||||
tornado.http1connection.HTTP1Connection.__init__(self, stream, is_client, params=params, context=context)
|
||||
|
||||
import re
|
||||
@@ -818,8 +777,13 @@ class CustomHTTP1Connection(tornado.http1connection.HTTP1Connection):
|
||||
current request exceeds the individual max content length, the request processing is aborted and an
|
||||
``HTTPInputError`` is raised.
|
||||
"""
|
||||
content_length = headers.get("Content-Length")
|
||||
if "Content-Length" in headers:
|
||||
if "Transfer-Encoding" in headers:
|
||||
# Response cannot contain both Content-Length and
|
||||
# Transfer-Encoding headers.
|
||||
# http://tools.ietf.org/html/rfc7230#section-3.3.3
|
||||
raise tornado.httputil.HTTPInputError(
|
||||
"Response with both Transfer-Encoding and Content-Length")
|
||||
if "," in headers["Content-Length"]:
|
||||
# Proxies sometimes cause Content-Length headers to get
|
||||
# duplicated. If all the values are identical then we can
|
||||
@@ -830,9 +794,14 @@ class CustomHTTP1Connection(tornado.http1connection.HTTP1Connection):
|
||||
"Multiple unequal Content-Lengths: %r" %
|
||||
headers["Content-Length"])
|
||||
headers["Content-Length"] = pieces[0]
|
||||
content_length = int(headers["Content-Length"])
|
||||
|
||||
content_length = int(content_length)
|
||||
try:
|
||||
content_length = int(headers["Content-Length"])
|
||||
except ValueError:
|
||||
# Handles non-integer Content-Length value.
|
||||
raise tornado.httputil.HTTPInputError(
|
||||
"Only integer Content-Length is allowed: %s" % headers["Content-Length"])
|
||||
|
||||
max_content_length = self._get_max_content_length(self._request_start_line.method, self._request_start_line.path)
|
||||
if max_content_length is not None and 0 <= max_content_length < content_length:
|
||||
raise tornado.httputil.HTTPInputError("Content-Length too long")
|
||||
@@ -884,9 +853,20 @@ class CustomHTTP1ConnectionParameters(tornado.http1connection.HTTP1ConnectionPar
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
tornado.http1connection.HTTP1ConnectionParameters.__init__(self, args, kwargs)
|
||||
self.max_body_sizes = kwargs["max_body_sizes"] if "max_body_sizes" in kwargs else list()
|
||||
self.default_max_body_size = kwargs["default_max_body_size"] if "default_max_body_size" in kwargs else None
|
||||
max_body_sizes = kwargs.pop("max_body_sizes", list())
|
||||
default_max_body_size = kwargs.pop("default_max_body_size", None)
|
||||
|
||||
tornado.http1connection.HTTP1ConnectionParameters.__init__(self, *args, **kwargs)
|
||||
|
||||
self.max_body_sizes = max_body_sizes
|
||||
self.default_max_body_size = default_max_body_size
|
||||
|
||||
@classmethod
|
||||
def from_stock_params(cls, other, **additional):
|
||||
kwargs = dict(other.__dict__)
|
||||
for key, value in additional.items():
|
||||
kwargs[key] = value
|
||||
return cls(**kwargs)
|
||||
|
||||
#~~ customized large response handler
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ default_settings = {
|
||||
"autoconnect": False,
|
||||
"log": False,
|
||||
"timeout": {
|
||||
"detection": 0.5,
|
||||
"detection": 1,
|
||||
"connection": 10,
|
||||
"communication": 30,
|
||||
"communicationBusy": 3,
|
||||
@@ -100,7 +100,8 @@ default_settings = {
|
||||
"temperatureAutoreport": 2,
|
||||
"sdStatus": 1,
|
||||
"sdStatusAutoreport": 1,
|
||||
"resendOk": .5
|
||||
"resendOk": .5,
|
||||
"baudrateDetectionPause": 1.0
|
||||
},
|
||||
"maxCommunicationTimeouts": {
|
||||
"idle": 2,
|
||||
@@ -146,7 +147,7 @@ default_settings = {
|
||||
"triggerOkForM29": True
|
||||
},
|
||||
"server": {
|
||||
"host": "0.0.0.0",
|
||||
"host": None,
|
||||
"port": 5000,
|
||||
"firstRun": True,
|
||||
"startOnceInSafeMode": False,
|
||||
@@ -163,7 +164,8 @@ default_settings = {
|
||||
"schemeFallback": None,
|
||||
"hostFallback": None,
|
||||
"serverFallback": None,
|
||||
"portFallback": None
|
||||
"portFallback": None,
|
||||
"trustedDownstream": []
|
||||
},
|
||||
"uploads": {
|
||||
"maxSize": 1 * 1024 * 1024 * 1024, # 1GB
|
||||
@@ -237,8 +239,7 @@ default_settings = {
|
||||
"modelSizeDetection": True,
|
||||
"printCancelConfirmation": True,
|
||||
"autoUppercaseBlacklist": ["M117"],
|
||||
"g90InfluencesExtruder": False,
|
||||
"legacyPluginAssets": False # TODO remove again in 1.3.8
|
||||
"g90InfluencesExtruder": False
|
||||
},
|
||||
"folder": {
|
||||
"uploads": None,
|
||||
@@ -402,7 +403,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,
|
||||
@@ -919,7 +920,8 @@ class Settings(object):
|
||||
self._migrate_gcode_scripts,
|
||||
self._migrate_core_system_commands,
|
||||
self._migrate_serial_features,
|
||||
self._migrate_resend_without_ok
|
||||
self._migrate_resend_without_ok,
|
||||
self._migrate_string_temperature_profile_values
|
||||
)
|
||||
|
||||
for migrate in migrators:
|
||||
@@ -931,6 +933,8 @@ class Settings(object):
|
||||
def _migrate_gcode_scripts(self, config):
|
||||
"""
|
||||
Migrates an old development version of gcode scripts to the new template based format.
|
||||
|
||||
Added in 1.2.0
|
||||
"""
|
||||
|
||||
dirty = False
|
||||
@@ -955,6 +959,8 @@ class Settings(object):
|
||||
def _migrate_printer_parameters(self, config):
|
||||
"""
|
||||
Migrates the old "printer > parameters" data structure to the new printer profile mechanism.
|
||||
|
||||
Added in 1.2.0
|
||||
"""
|
||||
default_profile = config["printerProfiles"]["defaultProfile"] if "printerProfiles" in config and "defaultProfile" in config["printerProfiles"] else dict()
|
||||
dirty = False
|
||||
@@ -1020,6 +1026,8 @@ class Settings(object):
|
||||
"""
|
||||
Migrates the old "server > baseUrl" and "server > scheme" configuration entries to
|
||||
"server > reverseProxy > prefixFallback" and "server > reverseProxy > schemeFallback".
|
||||
|
||||
Added in 1.2.0
|
||||
"""
|
||||
if "server" in config.keys() and ("baseUrl" in config["server"] or "scheme" in config["server"]):
|
||||
prefix = ""
|
||||
@@ -1047,6 +1055,8 @@ class Settings(object):
|
||||
"""
|
||||
Migrates the old event configuration format of type "events > gcodeCommandTrigger" and
|
||||
"event > systemCommandTrigger" to the new events format.
|
||||
|
||||
Added in 1.2.0
|
||||
"""
|
||||
if "events" in config.keys() and ("gcodeCommandTrigger" in config["events"] or "systemCommandTrigger" in config["events"]):
|
||||
self._logger.info("Migrating config (event subscriptions)...")
|
||||
@@ -1142,6 +1152,8 @@ class Settings(object):
|
||||
|
||||
If server commands for action is not yet set, migrates command. Otherwise only
|
||||
deletes definition from custom system commands.
|
||||
|
||||
Added in 1.3.0
|
||||
"""
|
||||
changed = False
|
||||
|
||||
@@ -1188,6 +1200,8 @@ class Settings(object):
|
||||
Migrates feature flags identified as serial specific from the feature to the serial config tree and vice versa.
|
||||
|
||||
If a flag already exists in the target tree, only deletes the copy in the source tree.
|
||||
|
||||
Added in 1.3.7
|
||||
"""
|
||||
changed = False
|
||||
|
||||
@@ -1231,6 +1245,8 @@ class Settings(object):
|
||||
Migrates supportResendsWithoutOk flag from boolean to ("always", "detect", "never") value range.
|
||||
|
||||
True gets migrated to "always", False to "detect" (which is the new default).
|
||||
|
||||
Added in 1.3.7
|
||||
"""
|
||||
if "serial" in config and "supportResendsWithoutOk" in config["serial"] \
|
||||
and config["serial"]["supportResendsWithoutOk"] not in ("always", "detect", "never"):
|
||||
@@ -1242,6 +1258,28 @@ class Settings(object):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _migrate_string_temperature_profile_values(self, config):
|
||||
"""
|
||||
Migrates/fixes temperature profile wrongly saved with strings instead of ints as temperature values.
|
||||
|
||||
Added in 1.3.8
|
||||
"""
|
||||
if "temperature" in config and "profiles" in config["temperature"]:
|
||||
profiles = config["temperature"]["profiles"]
|
||||
if any(map(lambda x: not isinstance(x.get("extruder", 0), int) or not isinstance(x.get("bed", 0), int),
|
||||
profiles)):
|
||||
result = []
|
||||
for profile in profiles:
|
||||
try:
|
||||
profile["extruder"] = int(profile["extruder"])
|
||||
profile["bed"] = int(profile["bed"])
|
||||
except ValueError:
|
||||
pass
|
||||
result.append(profile)
|
||||
config["temperature"]["profiles"] = result
|
||||
return True
|
||||
return False
|
||||
|
||||
def backup(self, suffix, path=None):
|
||||
import shutil
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
|
||||
@@ -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();
|
||||
|
||||
@@ -276,6 +276,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) {
|
||||
@@ -294,10 +308,7 @@ $(function() {
|
||||
var entryElement = self.getEntryElement({path: focus.path, origin: focus.location});
|
||||
if (entryElement) {
|
||||
// scroll to uploaded element
|
||||
var entryOffset = entryElement.offsetTop;
|
||||
self.listElement.slimScroll({
|
||||
scrollTo: entryOffset + "px"
|
||||
});
|
||||
self.listElement.scrollTop(entryElement.offsetTop);
|
||||
|
||||
// highlight uploaded element
|
||||
var element = $(entryElement);
|
||||
@@ -321,6 +332,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();
|
||||
@@ -793,7 +809,7 @@ $(function() {
|
||||
}
|
||||
});
|
||||
|
||||
self.listElement = $(".gcode_files");
|
||||
self.listElement = $("#files").find(".scroll-wrapper");
|
||||
|
||||
self.addFolderDialog = $("#add_folder_dialog");
|
||||
self.addFolderDialog.on("shown", function() {
|
||||
|
||||
@@ -143,7 +143,6 @@ $(function() {
|
||||
self.feature_printCancelConfirmation = ko.observable(undefined);
|
||||
self.feature_g90InfluencesExtruder = ko.observable(undefined);
|
||||
self.feature_autoUppercaseBlacklist = ko.observable(undefined);
|
||||
self.feature_legacyPluginAssets = ko.observable(undefined);
|
||||
|
||||
self.serial_port = ko.observable();
|
||||
self.serial_baudrate = ko.observable();
|
||||
@@ -159,6 +158,7 @@ $(function() {
|
||||
self.serial_timeoutTemperatureAutoreport = ko.observable(undefined);
|
||||
self.serial_timeoutSdStatus = ko.observable(undefined);
|
||||
self.serial_timeoutSdStatusAutoreport = ko.observable(undefined);
|
||||
self.serial_timeoutBaudrateDetectionPause = ko.observable(undefined);
|
||||
self.serial_log = ko.observable(undefined);
|
||||
self.serial_additionalPorts = ko.observable(undefined);
|
||||
self.serial_additionalBaudrates = ko.observable(undefined);
|
||||
@@ -729,6 +729,23 @@ $(function() {
|
||||
});
|
||||
return result;
|
||||
}
|
||||
},
|
||||
temperature: {
|
||||
profiles: function() {
|
||||
var result = [];
|
||||
_.each(self.temperature_profiles(), function(profile) {
|
||||
try {
|
||||
result.push({
|
||||
name: profile.name,
|
||||
extruder: Math.floor(_.isNumber(profile.extruder) ? profile.extruder : parseInt(profile.extruder)),
|
||||
bed: Math.floor(_.isNumber(profile.bed) ? profile.bed : parseInt(profile.bed))
|
||||
});
|
||||
} catch (ex) {
|
||||
// ignore
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+2
-2
@@ -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);
|
||||
|
||||
|
||||
@@ -645,10 +645,14 @@ ul.dropdown-menu li a {
|
||||
#files {
|
||||
.gcode_files {
|
||||
@padding: 5px;
|
||||
@scrollBar: 10px;
|
||||
@line-height: 20px;
|
||||
|
||||
padding-right: @scrollBar + 2px;
|
||||
.scroll-wrapper {
|
||||
overflow-x: hidden;
|
||||
overflow-y: scroll;
|
||||
height: 306px;
|
||||
padding-right: 2px;
|
||||
}
|
||||
|
||||
.entry {
|
||||
padding: @padding;
|
||||
@@ -888,6 +892,13 @@ ul.dropdown-menu li a {
|
||||
}
|
||||
}
|
||||
|
||||
#settings_appearance_managelanguagesdialog_list {
|
||||
width: auto;
|
||||
height: 300px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: scroll;
|
||||
padding-right: 2px;
|
||||
}
|
||||
|
||||
#settings_appearance_managelanguagesdialog_emptylist {
|
||||
overflow: hidden;
|
||||
|
||||
@@ -18,8 +18,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>
|
||||
|
||||
@@ -61,7 +61,7 @@
|
||||
<h4>{{ _('Available Language Packs') }}</h4>
|
||||
|
||||
<div data-bind="visible: languagePacksAvailable()">
|
||||
<div id="settings_appearance_managelanguagesdialog_list" data-bind="slimScrolledForeach: translations.paginatedItems" style="height: 300px">
|
||||
<div id="settings_appearance_managelanguagesdialog_list" data-bind="foreach: translations.paginatedItems">
|
||||
<div class="entry">
|
||||
<strong><a href="#" class="fa" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.entry', container: '.packs' }"><i class="fa fa-caret-down"></i> <span data-bind="text: $root.languagePackDisplay($data)"></span></a></strong>
|
||||
<div class="packs">
|
||||
|
||||
@@ -1,18 +1,4 @@
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_legacyPluginAssets" id="settings-legacyPluginAssets"> {{ _('Enable legacy plugin asset bundling') }} <span class="label label-info">Compatibility</span>
|
||||
<span class="help-block">{% trans url="https://octoprint.org/blog/2017/12/01/heads-up-plugin-authors/" %}
|
||||
Enable this, save and restart your server if you are running into issues with plugins with OctoPrint
|
||||
1.3.6 or later that used to work with OctoPrint up to version 1.3.5. See <a href="{{ url }}">here</a>
|
||||
for details on why this is happening. Note that this legacy flag will be removed in a future
|
||||
OctoPrint version (currently planned for 1.3.8), so urge the authors of affected plugins to push
|
||||
an update with a fix.
|
||||
{% endtrans %}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
<label class="control-label" for="settings-serialAdditionalBaudrates">{{ _('Additional baud rates') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialAdditionalBaudrates" data-bind="value: serial_additionalBaudrates">
|
||||
<span class="help-inline">{{ _('Use this to define additional serial port baud rates to list for connecting with, e.g. <code>123456</code>. Comma separated.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}</span>
|
||||
<span class="help-inline">{{ _('Use this to define additional serial port baud rates to list for connecting with, e.g. <code>123456</code>. Comma separated.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
@@ -146,6 +146,16 @@
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', container: '#settings_serial_timeouts_timeouts .hide' }"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<div class="control-group" title="{{ _('Time to wait after opening the serial connection before starting baudrate detection') }}">
|
||||
<label class="control-label" for="settings-serialTimeoutBaudrateDetectionPause">{{ _('Initial baudrate detection pause') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutBaudrateDetectionPause" id="settings-serialTimeoutBaudrateDetectionPause">
|
||||
<span class="add-on">s</span>
|
||||
</div>
|
||||
<span class="help-block">{{ _('Some controllers need a bit of a breather before baudrate detection after initial connect. If baudrate detection fails due to a hanging controller, try increasing this value.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Maximum consecutive communication timeouts while idle. More than this and the printer will be considered to be gone. Set to 0 to disable.') }}">
|
||||
<label class="control-label" for="settings-serialMaxTimeoutsIdle">{{ _('Max. consecutive timeouts while idle') }}</label>
|
||||
<div class="controls">
|
||||
@@ -271,7 +281,7 @@
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: serial_triggerOkForM29" id="settings-serialTriggerOkForM29"> {{ _('Simulate <code>ok</code> for <code>M29</code>') }}
|
||||
<span class="help-block">{{ _('Most Marlin forks that were derived from Marlin versions < v1.1.0 do not send an acknowledging <code>ok</code> for a <code>M29</code>. Check this if you run into communication stalls following streaming of a file to your printer\'s SD.') }}</span>
|
||||
<span class="help-block">{{ _('Most Marlin forks that were derived from Marlin versions < v1.1.0 do not send an acknowledging <code>ok</code> for a <code>M29</code>. Check this if you run into communication stalls following streaming of a file to your printer\'s SD.') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
@@ -299,7 +309,7 @@
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: serial_waitForStart" id="settings-serialWaitForStart"> {{ _('Wait for <code>start</code> on connect') }}
|
||||
<span class="help-block">{{ _('Try checking this if you run into connection timeouts due to your printer taking too long to respond to OctoPrint\' handshake attempts on connect.') }}</span>
|
||||
<span class="help-block">{{ _('Try checking this if you run into connection timeouts due to your printer taking too long to respond to OctoPrint\'s handshake attempts on connect.') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -40,11 +40,11 @@
|
||||
<input type="text" class="span12 text-right" data-bind="value: name">
|
||||
</div>
|
||||
<div class="input-append span3">
|
||||
<input type="number" class="input-mini text-right" data-bind="value: extruder">
|
||||
<input type="number" min="0" step="1" class="input-mini text-right" data-bind="value: extruder">
|
||||
<span class="add-on">°C</span>
|
||||
</div>
|
||||
<div class="input-append span3">
|
||||
<input type="number" class="input-mini text-right" data-bind="value: bed">
|
||||
<input type="number" min="0" step="1" class="input-mini text-right" data-bind="value: bed">
|
||||
<span class="add-on">°C</span>
|
||||
</div>
|
||||
<div class="span2">
|
||||
|
||||
@@ -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,4 +1,4 @@
|
||||
<script lang="javascript">
|
||||
<script type="text/javascript">
|
||||
var BASEURL = "{{ url_for('index') }}";
|
||||
var API_BASEURL = BASEURL + "api/";
|
||||
var PLUGIN_BASEURL = BASEURL + "plugin/";
|
||||
|
||||
@@ -6,6 +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="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">
|
||||
|
||||
@@ -7,9 +7,9 @@
|
||||
<div class="back-path"><small class="muted">{{ _('Currently in') }} <span data-bind="text: currentPath"></span></small></div>
|
||||
</div>
|
||||
|
||||
<!-- ko slimScrolledForeach: {data: filesAndFolders, slimscroll: {height: "306px", size: "10px", distance: 0, railVisible: true, alwaysVisible: true, scrollBy: "102px"} } -->
|
||||
<div class="entry" data-bind="attr: { id: $root.getEntryId($data) }, template: { name: $root.templateFor($data), data: $data }, css: $data.type"></div>
|
||||
<!-- /ko -->
|
||||
<div class="scroll-wrapper" data-bind="foreach: filesAndFolders">
|
||||
<div class="entry" data-bind="attr: { id: $root.getEntryId($data) }, template: { name: $root.templateFor($data), data: $data }, css: $data.type"></div>
|
||||
</div>
|
||||
|
||||
<script type="text/html" id="files_template_machinecode">
|
||||
<div class="title clickable" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: $root.getSuccessClass($data), style: { 'font-weight': $root.listHelper.isSelected($data) ? 'bold' : 'normal' }, text: display"></div>
|
||||
|
||||
@@ -83,10 +83,10 @@
|
||||
</p>
|
||||
<p>
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: reader_hideEmptyLayers">{{ _('Hide empty layers') }} <label class="label">{{ _('Causes reload') }}</label>
|
||||
<input type="checkbox" data-bind="checked: reader_hideEmptyLayers">{{ _('Hide empty layers') }} <span class="label">{{ _('Causes reload') }}</span>
|
||||
</label>
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: reader_sortLayers">{{ _('Sort layers') }} <label class="label">{{ _('Causes reload') }}</label>
|
||||
<input type="checkbox" data-bind="checked: reader_sortLayers">{{ _('Sort layers') }} <span class="label">{{ _('Causes reload') }}</span>
|
||||
</label>
|
||||
</p>
|
||||
<p>
|
||||
|
||||
@@ -18,6 +18,7 @@ except ImportError:
|
||||
import requests
|
||||
import re
|
||||
|
||||
import octoprint.plugin
|
||||
import octoprint.util as util
|
||||
|
||||
from octoprint.settings import settings
|
||||
@@ -369,6 +370,11 @@ class Timelapse(object):
|
||||
|
||||
self._fps = fps
|
||||
|
||||
|
||||
self._pluginManager = octoprint.plugin.plugin_manager()
|
||||
self._pre_capture_hooks = self._pluginManager.get_hooks("octoprint.timelapse.capture.pre")
|
||||
self._post_capture_hooks = self._pluginManager.get_hooks("octoprint.timelapse.capture.post")
|
||||
|
||||
self._capture_mutex = threading.Lock()
|
||||
self._capture_queue = queue.Queue()
|
||||
self._capture_queue_active = True
|
||||
@@ -578,6 +584,13 @@ class Timelapse(object):
|
||||
entry["callback"](*args, **kwargs)
|
||||
|
||||
def _perform_capture(self, filename, onerror=None):
|
||||
# pre-capture hook
|
||||
for name, hook in self._pre_capture_hooks.items():
|
||||
try:
|
||||
hook(filename)
|
||||
except:
|
||||
self._logger.exception("Error while processing hook {name}.".format(**locals()))
|
||||
|
||||
eventManager().fire(Events.CAPTURE_START, dict(file=filename))
|
||||
try:
|
||||
self._logger.debug("Going to capture {} from {}".format(filename, self._snapshot_url))
|
||||
@@ -596,17 +609,31 @@ class Timelapse(object):
|
||||
self._logger.debug("Image {} captured from {}".format(filename, self._snapshot_url))
|
||||
except Exception as e:
|
||||
self._logger.exception("Could not capture image {} from {}".format(filename, self._snapshot_url))
|
||||
self._capture_errors += 1
|
||||
success = False
|
||||
else:
|
||||
self._capture_success += 1
|
||||
success = True
|
||||
|
||||
# post-capture hook
|
||||
for name, hook in self._post_capture_hooks.items():
|
||||
try:
|
||||
hook(filename, success)
|
||||
except:
|
||||
self._logger.exception("Error while processing hook {name}.".format(**locals()))
|
||||
|
||||
# handle events and onerror call
|
||||
if success:
|
||||
eventManager().fire(Events.CAPTURE_DONE, dict(file=filename))
|
||||
return True
|
||||
else:
|
||||
if callable(onerror):
|
||||
onerror()
|
||||
eventManager().fire(Events.CAPTURE_FAILED, dict(file=filename,
|
||||
error=str(e),
|
||||
url=self._snapshot_url))
|
||||
self._capture_errors += 1
|
||||
return False
|
||||
else:
|
||||
eventManager().fire(Events.CAPTURE_DONE, dict(file=filename))
|
||||
self._capture_success += 1
|
||||
return True
|
||||
|
||||
|
||||
def _copying_postroll(self):
|
||||
with self._capture_mutex:
|
||||
|
||||
@@ -576,7 +576,7 @@ msgstr "Vorhandene Datei überschreiben"
|
||||
#: src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2:53
|
||||
msgid "\n"
|
||||
" You can import your existing profile <code>.ini</code> files from <strong>Cura 15.04.x or older</strong>\n"
|
||||
" here. Anything but those are <strong>not supported</strong>. That especiallymeans that <code>.json</code>\n"
|
||||
" here. Anything but those are <strong>not supported</strong>. That especially means that <code>.json</code>\n"
|
||||
" profiles from Cura 15.06.x and <code>.curaprofile</code> profiles from Cura 2.x will not work, and neither\n"
|
||||
" will custom Cura profile formats that third party tools like e.g. Repetier create.\n"
|
||||
" "
|
||||
|
||||
+94
-8
@@ -5,7 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask_login import UserMixin
|
||||
from flask_login import UserMixin, AnonymousUserMixin
|
||||
from flask_principal import Identity
|
||||
from werkzeug.local import LocalProxy
|
||||
import hashlib
|
||||
@@ -418,6 +418,65 @@ class UnknownRole(Exception):
|
||||
|
||||
##~~ User object
|
||||
|
||||
class MethodReplacedByBooleanProperty(object):
|
||||
|
||||
def __init__(self, name, message, getter):
|
||||
self._name = name
|
||||
self._message = message
|
||||
self._getter = getter
|
||||
|
||||
@property
|
||||
def _attr(self):
|
||||
return self._getter()
|
||||
|
||||
def __call__(self):
|
||||
from warnings import warn
|
||||
warn(DeprecationWarning(self._message.format(name=self._name)), stacklevel=2)
|
||||
return self._attr
|
||||
|
||||
def __eq__(self, other):
|
||||
return self._attr == other
|
||||
|
||||
def __ne__(self, other):
|
||||
return self._attr != other
|
||||
|
||||
def __bool__(self):
|
||||
# Python 3
|
||||
return self._attr
|
||||
|
||||
def __nonzero__(self):
|
||||
# Python 2
|
||||
return self._attr
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self._attr)
|
||||
|
||||
def __repr__(self):
|
||||
return "MethodReplacedByProperty({}, {}, {})".format(self._name, self._message, self._getter)
|
||||
|
||||
def __str__(self):
|
||||
return str(self._attr)
|
||||
|
||||
|
||||
# TODO: Remove compatibility layer in OctoPrint 1.5.0
|
||||
class FlaskLoginMethodReplacedByBooleanProperty(MethodReplacedByBooleanProperty):
|
||||
|
||||
def __init__(self, name, getter):
|
||||
message = "{name} is now a property in Flask-Login versions >= 0.3.0, which OctoPrint now uses. " + \
|
||||
"Use {name} instead of {name}(). This compatibility layer will be removed in OctoPrint 1.5.0."
|
||||
MethodReplacedByBooleanProperty.__init__(self, name, message, getter)
|
||||
|
||||
|
||||
# TODO: Remove compatibility layer in OctoPrint 1.5.0
|
||||
class OctoPrintUserMethodReplacedByBooleanProperty(MethodReplacedByBooleanProperty):
|
||||
|
||||
def __init__(self, name, getter):
|
||||
message = "{name} is now a property for consistency reasons with Flask-Login versions >= 0.3.0, which " + \
|
||||
"OctoPrint now uses. Use {name} instead of {name}(). This compatibility layer will be removed " + \
|
||||
"in OctoPrint 1.5.0."
|
||||
MethodReplacedByBooleanProperty.__init__(self, name, message, getter)
|
||||
|
||||
|
||||
class User(UserMixin):
|
||||
def __init__(self, username, passwordHash, active, roles, apikey=None, settings=None):
|
||||
self._username = username
|
||||
@@ -433,9 +492,9 @@ class User(UserMixin):
|
||||
def asDict(self):
|
||||
return {
|
||||
"name": self._username,
|
||||
"active": self.is_active(),
|
||||
"admin": self.is_admin(),
|
||||
"user": self.is_user(),
|
||||
"active": bool(self.is_active),
|
||||
"admin": bool(self.is_admin),
|
||||
"user": bool(self.is_user),
|
||||
"apikey": self._apikey,
|
||||
"settings": self._settings
|
||||
}
|
||||
@@ -449,14 +508,25 @@ class User(UserMixin):
|
||||
def get_name(self):
|
||||
return self._username
|
||||
|
||||
@property
|
||||
def is_anonymous(self):
|
||||
return FlaskLoginMethodReplacedByBooleanProperty("is_anonymous", lambda: False)
|
||||
|
||||
@property
|
||||
def is_authenticated(self):
|
||||
return FlaskLoginMethodReplacedByBooleanProperty("is_authenticated", lambda: True)
|
||||
|
||||
@property
|
||||
def is_active(self):
|
||||
return self._active
|
||||
return FlaskLoginMethodReplacedByBooleanProperty("is_active", lambda: self._active)
|
||||
|
||||
@property
|
||||
def is_user(self):
|
||||
return "user" in self._roles
|
||||
return OctoPrintUserMethodReplacedByBooleanProperty("is_user", lambda: "user" in self._roles)
|
||||
|
||||
@property
|
||||
def is_admin(self):
|
||||
return "admin" in self._roles
|
||||
return OctoPrintUserMethodReplacedByBooleanProperty("is_admin", lambda: "admin" in self._roles)
|
||||
|
||||
def get_all_settings(self):
|
||||
return self._settings
|
||||
@@ -505,7 +575,23 @@ class User(UserMixin):
|
||||
return True
|
||||
|
||||
def __repr__(self):
|
||||
return "User(id=%s,name=%s,active=%r,user=%r,admin=%r)" % (self.get_id(), self.get_name(), self.is_active(), self.is_user(), self.is_admin())
|
||||
return "User(id=%s,name=%s,active=%r,user=%r,admin=%r)" % (self.get_id(), self.get_name(), bool(self.is_active), bool(self.is_user), bool(self.is_admin))
|
||||
|
||||
|
||||
class AnonymousUser(AnonymousUserMixin):
|
||||
|
||||
@property
|
||||
def is_anonymous(self):
|
||||
return FlaskLoginMethodReplacedByBooleanProperty("is_anonymous", lambda: True)
|
||||
|
||||
@property
|
||||
def is_authenticated(self):
|
||||
return FlaskLoginMethodReplacedByBooleanProperty("is_authenticated", lambda: False)
|
||||
|
||||
@property
|
||||
def is_active(self):
|
||||
return FlaskLoginMethodReplacedByBooleanProperty("is_active", lambda: False)
|
||||
|
||||
|
||||
class SessionUser(wrapt.ObjectProxy):
|
||||
def __init__(self, user):
|
||||
|
||||
+69
-40
@@ -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)
|
||||
@@ -215,6 +215,7 @@ def serialList():
|
||||
+ glob.glob("/dev/tty.usb*") \
|
||||
+ glob.glob("/dev/cu.*") \
|
||||
+ glob.glob("/dev/cuaU*") \
|
||||
+ glob.glob("/dev/ttyS*") \
|
||||
+ glob.glob("/dev/rfcomm*")
|
||||
|
||||
additionalPorts = settings().get(["serial", "additionalPorts"])
|
||||
@@ -417,7 +418,7 @@ class MachineCom(object):
|
||||
self._printerProfileManager = printerProfileManager
|
||||
self._state = self.STATE_NONE
|
||||
self._serial = None
|
||||
self._baudrateDetectList = baudrateList()
|
||||
self._baudrateDetectList = []
|
||||
self._baudrateDetectRetry = 0
|
||||
self._temperatureTargetSetThreshold = 25
|
||||
self._tempOffsets = dict()
|
||||
@@ -908,7 +909,7 @@ class MachineCom(object):
|
||||
if not cmd:
|
||||
return False
|
||||
|
||||
if self.isPrinting() and not self.isSdFileSelected() and not self.job_on_hold:
|
||||
if self.isPrinting() and not self.isSdFileSelected() and not self.job_on_hold and not force:
|
||||
try:
|
||||
self._command_queue.put((cmd, cmd_type, on_sent, tags), item_type=cmd_type)
|
||||
return True
|
||||
@@ -1410,10 +1411,15 @@ class MachineCom(object):
|
||||
|
||||
self._log("Connected to: %s, starting monitor" % self._serial)
|
||||
if self._baudrate == 0:
|
||||
self._serial.timeout = 0.01
|
||||
try_hello = False
|
||||
self._log("Starting baud rate detection")
|
||||
self._log("Starting baud rate detection...")
|
||||
self._changeState(self.STATE_DETECT_BAUDRATE)
|
||||
|
||||
# Some controllers (e.g. Original Prusa) don't appear to like too fast serial interaction after
|
||||
# open, so let's wait a bit before the first baudrate detection step
|
||||
time.sleep(settings().getFloat(["serial", "timeout", "baudrateDetectionPause"]))
|
||||
|
||||
self._perform_baudrate_detection_step(init=True)
|
||||
else:
|
||||
self._changeState(self.STATE_CONNECTING)
|
||||
|
||||
@@ -1425,9 +1431,6 @@ class MachineCom(object):
|
||||
supportRepetierTargetTemp = settings().getBoolean(["serial", "repetierTargetTemp"])
|
||||
supportWait = settings().getBoolean(["serial", "supportWait"])
|
||||
|
||||
connection_timeout = settings().getFloat(["serial", "timeout", "connection"])
|
||||
detection_timeout = settings().getFloat(["serial", "timeout", "detection"])
|
||||
|
||||
# enqueue the "hello command" first thing
|
||||
if try_hello:
|
||||
self.sayHello()
|
||||
@@ -1660,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")
|
||||
@@ -1670,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.
|
||||
@@ -1874,30 +1881,8 @@ class MachineCom(object):
|
||||
### Baudrate detection
|
||||
if self._state == self.STATE_DETECT_BAUDRATE:
|
||||
if line == '' or time.time() > self._timeout:
|
||||
if self._baudrateDetectRetry > 0:
|
||||
self._serial.timeout = detection_timeout
|
||||
self._baudrateDetectRetry -= 1
|
||||
self._serial.write('\n')
|
||||
self._log("Baudrate test retry: %d" % (self._baudrateDetectRetry))
|
||||
self.sayHello(tags={"trigger:baudrate_detection",})
|
||||
elif len(self._baudrateDetectList) > 0:
|
||||
baudrate = self._baudrateDetectList.pop(0)
|
||||
try:
|
||||
self._serial.baudrate = baudrate
|
||||
if self._serial.timeout != connection_timeout:
|
||||
self._serial.timeout = connection_timeout
|
||||
self._log("Trying baudrate: %d" % (baudrate))
|
||||
self._baudrateDetectRetry = 5
|
||||
self._timeout = get_new_timeout("communicationBusy" if self._busy_protocol_detected else "communication", self._timeout_intervals)
|
||||
self._serial.write('\n')
|
||||
self.sayHello(tags={"trigger:baudrate_detection",})
|
||||
except:
|
||||
self._log("Unexpected error while setting baudrate {}: {}".format(baudrate, get_exception_string()))
|
||||
self._logger.exception("Unexpceted error while setting baudrate {}".format(baudrate))
|
||||
else:
|
||||
error_text = "No more baudrates to test, and no suitable baudrate found."
|
||||
self._trigger_error(error_text, "autodetect_baudrate")
|
||||
elif 'start' in line or 'ok' in line:
|
||||
self._perform_baudrate_detection_step()
|
||||
elif 'start' in line or line.startswith('ok'):
|
||||
self._onConnected()
|
||||
if 'start' in line:
|
||||
self._clear_to_send.set()
|
||||
@@ -2043,6 +2028,43 @@ class MachineCom(object):
|
||||
self._log(message + " " + general_message)
|
||||
self._clear_to_send.set()
|
||||
|
||||
def _perform_baudrate_detection_step(self, init=False):
|
||||
if init:
|
||||
timeout = settings().getFloat(["serial", "timeout", "connection"])
|
||||
self._baudrateDetectList = baudrateList()
|
||||
else:
|
||||
timeout = settings().getFloat(["serial", "timeout", "detection"])
|
||||
|
||||
if self._baudrateDetectRetry > 0:
|
||||
if self._serial.timeout != timeout:
|
||||
self._serial.timeout = timeout
|
||||
self._timeout = time.time() + timeout
|
||||
|
||||
self._log("Baudrate test retry #{}".format(5 - self._baudrateDetectRetry))
|
||||
self._baudrateDetectRetry -= 1
|
||||
self._do_send_without_checksum("", log=False) # new line to reset things
|
||||
self.sayHello(tags={"trigger:baudrate_detection", })
|
||||
|
||||
elif len(self._baudrateDetectList) > 0:
|
||||
baudrate = self._baudrateDetectList.pop(0)
|
||||
try:
|
||||
self._serial.baudrate = baudrate
|
||||
if self._serial.timeout != timeout:
|
||||
self._serial.timeout = timeout
|
||||
self._timeout = time.time() + timeout
|
||||
|
||||
self._log("Trying baudrate: {}".format(baudrate))
|
||||
self._baudrateDetectRetry = 4
|
||||
self._do_send_without_checksum("", log=False) # new line to reset things
|
||||
self.sayHello(tags={"trigger:baudrate_detection", })
|
||||
except:
|
||||
self._log("Unexpected error while setting baudrate {}: {}".format(baudrate, get_exception_string()))
|
||||
self._logger.exception("Unexpected error while setting baudrate {}".format(baudrate))
|
||||
|
||||
else:
|
||||
error_text = "No more baudrates to test, and no suitable baudrate found."
|
||||
self._trigger_error(error_text, "autodetect_baudrate")
|
||||
|
||||
def _finish_heatup(self):
|
||||
if self._heating:
|
||||
if self._heatupWaitStartTime:
|
||||
@@ -2110,7 +2132,7 @@ class MachineCom(object):
|
||||
|
||||
def _poll_temperature(self):
|
||||
"""
|
||||
Polls the temperature after the temperature timeout, re-enqueues itself.
|
||||
Polls the temperature.
|
||||
|
||||
If the printer is not operational, capable of auto-reporting temperatures, closing the connection, not printing
|
||||
from sd, busy with a long running command or heating, no poll will be done.
|
||||
@@ -2121,7 +2143,7 @@ class MachineCom(object):
|
||||
|
||||
def _poll_sd_status(self):
|
||||
"""
|
||||
Polls the sd printing status after the sd status timeout, re-enqueues itself.
|
||||
Polls the sd printing status.
|
||||
|
||||
If the printer is not operational, closing the connection, not printing from sd, busy with a long running
|
||||
command or heating, no poll will be done.
|
||||
@@ -2286,7 +2308,7 @@ class MachineCom(object):
|
||||
if baudrate == 0:
|
||||
baudrates = baudrateList()
|
||||
serial_obj = serial.Serial(str(port),
|
||||
115200 if 115200 in baudrates else baudrates[0],
|
||||
baudrates[0],
|
||||
timeout=read_timeout,
|
||||
writeTimeout=10000, # TODO 1.3.8 rename to write_timeout for pyserial >= 3.x
|
||||
parity=serial.PARITY_ODD)
|
||||
@@ -2988,11 +3010,12 @@ class MachineCom(object):
|
||||
command_to_send = command_to_send + "*" + str(checksum)
|
||||
self._do_send_without_checksum(command_to_send)
|
||||
|
||||
def _do_send_without_checksum(self, cmd):
|
||||
def _do_send_without_checksum(self, cmd, log=True):
|
||||
if self._serial is None:
|
||||
return
|
||||
|
||||
self._log("Send: " + str(cmd))
|
||||
if log:
|
||||
self._log("Send: " + str(cmd))
|
||||
|
||||
cmd += "\n"
|
||||
written = 0
|
||||
@@ -3995,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):
|
||||
|
||||
@@ -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
|
||||
Whitespace-only changes.
+5
@@ -0,0 +1,5 @@
|
||||
try:
|
||||
__import__('pkg_resources').declare_namespace(__name__)
|
||||
except ImportError:
|
||||
from pkgutil import extend_path
|
||||
__path__ = extend_path(__path__, __name__)
|
||||
@@ -0,0 +1,4 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from .router import SockJSRouter
|
||||
from .conn import SockJSConnection
|
||||
+130
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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)
|
||||
@@ -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
@@ -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
@@ -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
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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
@@ -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
|
||||
@@ -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()
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user