Merge branch 'maintenance' into devel
This commit is contained in:
commit
ff494fad8f
131 files changed
+2064
-1152
No files matched your search
+36
-2
@@ -12,11 +12,13 @@ repos:
|
||||
- id: check-merge-conflict
|
||||
- id: fix-encoding-pragma
|
||||
args: ["--remove"]
|
||||
exclude: "setup.py|versioneer.py|src/octoprint_setuptools/__init__.py"
|
||||
- repo: https://github.com/asottile/pyupgrade
|
||||
rev: v2.10.0
|
||||
hooks:
|
||||
- id: pyupgrade
|
||||
args: ["--py37-plus"]
|
||||
exclude: "setup.py|versioneer.py|src/octoprint_setuptools/__init__.py"
|
||||
- repo: https://github.com/OctoPrint/codemods
|
||||
rev: devel
|
||||
hooks:
|
||||
@@ -24,10 +26,42 @@ repos:
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- id: codemod_not_in
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- id: codemod_detect_past_builtins_imports
|
||||
args:
|
||||
[
|
||||
"--ignore",
|
||||
"src/octoprint/vendor",
|
||||
"--ignore",
|
||||
"setup.py",
|
||||
"--ignore",
|
||||
"versioneer.py",
|
||||
"--ignore",
|
||||
"src/octoprint_setuptools/__init__.py",
|
||||
]
|
||||
- id: codemod_remove_float_conversion
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
args:
|
||||
[
|
||||
"--ignore",
|
||||
"src/octoprint/vendor",
|
||||
"--ignore",
|
||||
"setup.py",
|
||||
"--ignore",
|
||||
"versioneer.py",
|
||||
"--ignore",
|
||||
"src/octoprint_setuptools/__init__.py",
|
||||
]
|
||||
- id: codemod_remove_future_imports
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
args:
|
||||
[
|
||||
"--ignore",
|
||||
"src/octoprint/vendor",
|
||||
"--ignore",
|
||||
"setup.py",
|
||||
"--ignore",
|
||||
"versioneer.py",
|
||||
"--ignore",
|
||||
"src/octoprint_setuptools/__init__.py",
|
||||
]
|
||||
- repo: https://github.com/pre-commit/mirrors-isort
|
||||
rev: v5.5.4
|
||||
hooks:
|
||||
|
||||
+3
-3
@@ -24,10 +24,10 @@ maintenance 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
|
||||
fix/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
|
||||
improve/.* 1.8.0 3fe45661cd79c5137d9d4f5f4adb4d9519bc2084 pep440-dev
|
||||
|
||||
# staging/bugfix is the branch for preparation of the 1.7.3 bugfix release
|
||||
# staging/bugfix is the branch for preparation of the 1.7.4 bugfix release
|
||||
# so are any bug/... branches
|
||||
staging/bugfix 1.7.2 d60c5a631aedf2328e4492125d9b86f595e43d00 pep440-dev
|
||||
bug/.* 1.7.2 d60c5a631aedf2328e4492125d9b86f595e43d00 pep440-dev
|
||||
staging/bugfix 1.7.4 59cbfadf8922d85b9df40f8d0173e8c21724c3b8 pep440-dev
|
||||
bug/.* 1.7.4 59cbfadf8922d85b9df40f8d0173e8c21724c3b8 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.7.0rc4
|
||||
# so is regressionfix/...
|
||||
|
||||
@@ -154,10 +154,14 @@ date of first contribution):
|
||||
* [Bryan Kenote](https://github.com/bryankenote)
|
||||
* [Quinn Damerell](https://github.com/QuinnDamerell)
|
||||
* [Sven Samoray](https://github.com/thelastWallE)
|
||||
* [Carey Metcalfe](https://github.com/pR0Ps)
|
||||
* [Christian Würthner](https://github.com/crysxd)
|
||||
* [Maciej Urbański](https://github.com/rooterkyberian)
|
||||
* [Adam Wolf](https://github.com/adamwolf)
|
||||
* [Carey Metcalfe](https://github.com/pR0Ps)
|
||||
* [Didi Kohen](https://github.com/kohend)
|
||||
* [Taylor Talkington](https://github.com/The-EG)
|
||||
* [Shell M. Shrader](https://github.com/synman)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||
|
||||
@@ -7,4 +7,6 @@ include versioneer.py
|
||||
include src/octoprint/_version.py
|
||||
include requirements.txt
|
||||
include *.md
|
||||
exclude CODE_OF_CONDUCT.md
|
||||
exclude SECURITY.md
|
||||
exclude CONTRIBUTING.md
|
||||
@@ -69,7 +69,7 @@ which is a custom SD card image that includes OctoPrint plus dependencies.
|
||||
The generic steps that should basically be done regardless of operating system
|
||||
and runtime environment are the following (as *regular
|
||||
user*, please keep your hands *off* of the `sudo` command here!) - this assumes
|
||||
you already have Python 3.6, 3.7 or 3.8, pip and virtualenv and their dependencies set up on your system:
|
||||
you already have Python 3.7+, pip and virtualenv and their dependencies set up on your system:
|
||||
|
||||
1. Create a user-owned virtual environment therein: `virtualenv venv`. If you want to specify a specific python
|
||||
to use instead of whatever version your system defaults to, you can also explicitly require that via the `--python`
|
||||
@@ -87,7 +87,7 @@ access control as necessary.
|
||||
OctoPrint depends on a few python modules to do its job. Those are automatically installed when installing
|
||||
OctoPrint via `pip`.
|
||||
|
||||
OctoPrint currently supports Python 3.6, 3.7 and 3.8.
|
||||
OctoPrint currently supports Python 3.7, 3.8, 3.9 and 3.10.
|
||||
|
||||
## Usage
|
||||
|
||||
|
||||
+6
-4
@@ -14,9 +14,7 @@ thanks to everyone who contributed!
|
||||
* BigTreeTech
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* BRANDON ROBERTSON
|
||||
* BuildBee
|
||||
* Chris Lynch
|
||||
* Christian Petropolis
|
||||
* Christian Wolf
|
||||
* Christian Würthner
|
||||
@@ -25,6 +23,7 @@ thanks to everyone who contributed!
|
||||
* David Bounds
|
||||
* DeltaMaker 3D Printers
|
||||
* Dennis Breining
|
||||
* Douglas Floyd
|
||||
* Dr. Frank Wester
|
||||
* Eric Betts
|
||||
* Ernesto Martinez
|
||||
@@ -33,6 +32,7 @@ thanks to everyone who contributed!
|
||||
* Greg Holloway
|
||||
* Hog Duske
|
||||
* Itay Shem-tov
|
||||
* James Mackay
|
||||
* Jeff Moe
|
||||
* Jeremy Cole
|
||||
* Joshua Wills
|
||||
@@ -58,7 +58,6 @@ thanks to everyone who contributed!
|
||||
* Nat Friedman
|
||||
* Neil R. Goldberg
|
||||
* Norman Jaffe
|
||||
* Ory Weaver
|
||||
* Peopoly
|
||||
* Pete Barnwell
|
||||
* Raise3D
|
||||
@@ -71,11 +70,14 @@ thanks to everyone who contributed!
|
||||
* Ronald Griehsler
|
||||
* Sebastien Andrivet
|
||||
* Stefan Krister
|
||||
* Steve Dougherty
|
||||
* Steve Thompson
|
||||
* Sven Mueller
|
||||
* TH3D
|
||||
* The Spaghetti Detective
|
||||
* TJ Horner
|
||||
* Ulderico Cirello
|
||||
* Ulrich Kempken
|
||||
* Yehuda Katz
|
||||
|
||||
and 2247 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
|
||||
and 2285 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [GitHub Sponsors](https://github.com/users/foosel/sponsorship)!
|
||||
+26
-9
@@ -399,7 +399,9 @@ Upload file or create folder
|
||||
}
|
||||
}
|
||||
},
|
||||
"done": false
|
||||
"done": false,
|
||||
"effectiveSelect": true,
|
||||
"effectivePrint": true
|
||||
}
|
||||
|
||||
**Example with UTF-8 encoded filename following RFC 5987**
|
||||
@@ -440,7 +442,9 @@ Upload file or create folder
|
||||
}
|
||||
}
|
||||
},
|
||||
"done": true
|
||||
"done": true,
|
||||
"effectiveSelect": false,
|
||||
"effectivePrint": false
|
||||
}
|
||||
|
||||
**Example for creating a folder**
|
||||
@@ -486,9 +490,12 @@ Upload file or create folder
|
||||
filename or ``foldername`` - basically the parent folder). If unset will be taken from the provided
|
||||
``file``'s name or ``foldername`` and default to the root folder of the ``location``.
|
||||
:form select: Whether to select the file directly after upload (``true``) or not (``false``). Optional, defaults
|
||||
to ``false``. Ignored when creating a folder.
|
||||
to ``false``. If the printer is not operational, this will have no
|
||||
effect and the ``effectiveSelect`` field in the response will be set 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 implicitly ``true`` as well. Optional, defaults to ``false``. Ignored when creating a folder.
|
||||
is implicitly ``true`` as well. Optional, defaults to ``false``. If the
|
||||
printer is not operational, this will have no effect and the ``effectivePrint`` field in the response will be set
|
||||
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.
|
||||
@@ -869,9 +876,8 @@ Upload response
|
||||
* - ``files``
|
||||
- 0..1
|
||||
- Object
|
||||
- Abridged information regarding the file that was just uploaded. If only uploaded to ``local`` this will only
|
||||
- (File only) Abridged information regarding the file that was just uploaded. If only uploaded to ``local`` this will only
|
||||
contain the ``local`` property. If uploaded to SD card, this will contain both ``local`` and ``sdcard`` properties.
|
||||
Only contained if a file was uploaded, not present if only a new folder was created.
|
||||
* - ``files.local``
|
||||
- 1
|
||||
- :ref:`sec-api-datamodel-files-fileabridged`
|
||||
@@ -883,12 +889,23 @@ Upload response
|
||||
* - ``folder``
|
||||
- 0..1
|
||||
- :ref:`sec-api-datamodel-files-fileabridged`
|
||||
- Abridged information regarding the folder that was just created. Only contained if a folder
|
||||
was created, not present if a file was uploaded.
|
||||
- (Folder only) Abridged information regarding the folder that was just created.
|
||||
* - ``done``
|
||||
- 1
|
||||
- Boolean
|
||||
- Whether any file processing after upload has already finished (``true``) or not, e.g. due to first needing
|
||||
to perform a slicing step (``false``). Clients may use this information to direct progress displays related to
|
||||
the upload.
|
||||
the upload. Always ``true`` for folders.
|
||||
* - ``effectiveSelect``
|
||||
- 0..1
|
||||
- Boolean
|
||||
- (File only) Whether the file that was just uploaded was selected for printing (``true``) or not (``false``). If this
|
||||
is ``false`` but was requested to be ``true`` in the upload request, the user lacked permissions, the printer was not
|
||||
operational or already printing and thus the request could not be fulfilled.
|
||||
* - ``effectivePrint``
|
||||
- 0..1
|
||||
- Boolean
|
||||
- (File only) Whether the file that was just uploaded was started to print (``true``) or not (``false``). If this
|
||||
is ``false`` but was requested to be ``true`` in the upload request, the user lacked permissions, the printer was not
|
||||
operational or already printing and thus the request could not be fulfilled.
|
||||
|
||||
+28
-3
@@ -27,12 +27,17 @@ Retrieve a list of timelapses and the current config
|
||||
Delete a timelapse
|
||||
==================
|
||||
|
||||
.. http:delete:: /api/timelapse/(string:filename)
|
||||
.. http:delete:: /api/timelapse/(string:name)
|
||||
|
||||
Delete the timelapse ``filename``.
|
||||
Delete the timelapse ``name``.
|
||||
|
||||
Returns a :ref:`timelapse list <sec-api-timelapse-datamodel-list>` in the
|
||||
response body with the updated information.
|
||||
|
||||
Requires the ``TIMELAPSE_DELETE`` permission.
|
||||
|
||||
:param unrendered: If provided and true, also include unrendered timelapses in the response
|
||||
|
||||
.. _sec-api-timelapse-render:
|
||||
|
||||
Issue a command for an unrendered timelapse
|
||||
@@ -56,8 +61,13 @@ Delete an unrendered timelapse
|
||||
|
||||
Delete the unrendered timelapse ``name``.
|
||||
|
||||
Returns a :ref:`timelapse list <sec-api-timelapse-datamodel-list>` in the
|
||||
response body.
|
||||
|
||||
Requires the ``TIMELAPSE_DELETE`` permission.
|
||||
|
||||
:param unrendered: If provided and true, also include unrendered timelapses in the response
|
||||
|
||||
.. _sec-api-timelapse-saveconfig:
|
||||
|
||||
Change current timelapse config
|
||||
@@ -65,12 +75,19 @@ Change current timelapse config
|
||||
|
||||
.. http:post:: /api/timelapse
|
||||
|
||||
Save a new :ref:`timelapse configuration <sec-api-timelapse-datamodel-config>` to use for the next print.
|
||||
Save a new :ref:`timelapse configuration <sec-api-timelapse-datamodel-config>` to use for the next print. Set the optional ``save`` flag in the
|
||||
configuration to ``true`` in order to make the new configuration persist accross restarts.
|
||||
|
||||
The configuration is expected as the request body.
|
||||
|
||||
Returns a :ref:`timelapse list <sec-api-timelapse-datamodel-list>` in the
|
||||
response body.
|
||||
|
||||
Requires the ``TIMELAPSE_ADMIN`` permission.
|
||||
|
||||
:param unrendered: If provided and true, also include unrendered timelapses in the response
|
||||
|
||||
|
||||
.. _sec-api-timelapse-datamodel:
|
||||
|
||||
Data model
|
||||
@@ -135,6 +152,10 @@ Rendered timelapse
|
||||
- 1
|
||||
- string
|
||||
- URL for downloading the timelapse
|
||||
* - ``thumbnail``
|
||||
- 1
|
||||
- string
|
||||
- URL for downloading a thumbnail of the timelapse (optional)
|
||||
|
||||
.. _sec-api-timelapse-datamodel-unrendered:
|
||||
|
||||
@@ -196,6 +217,10 @@ Timelapse configuration
|
||||
- 1
|
||||
- string
|
||||
- Type of the timelapse, either ``off``, ``zchange`` or ``timed``.
|
||||
* - ``save``
|
||||
- 1
|
||||
- bool
|
||||
- Optional flag to be included when when saving a configuration to make the configuration persist accross restarts
|
||||
|
||||
Further fields are timelapse type specific, see below for details.
|
||||
|
||||
|
||||
@@ -338,6 +338,15 @@ supported:
|
||||
Additional config parameters:
|
||||
|
||||
* ``pip``: The URL to use for installing. Presence implies ``method: pip``.
|
||||
* ``pip_command``: The command to use for installing. Defaults to the ``pip`` instance belong to OctoPrint's environment.
|
||||
* ``pip_cwd``: The working directory to use for installing. Defaults to the current working directory.
|
||||
* ``force_reinstall``: Whether to force reinstallation of the package. Defaults to ``false``. Helpful
|
||||
for development and version checks that don't guarantee a Python package version change (e.g. commit based
|
||||
version checks like ``git_commit``, ``github_commit``, ``bitbucket_commit``).
|
||||
|
||||
.. versionchanged:: 1.8.0
|
||||
|
||||
Added ``force_reinstall`` parameter.
|
||||
|
||||
* ``single_file_plugin``: Update a single file plugin by re-downloading it from a configured URL.
|
||||
Additional config parameters:
|
||||
|
||||
@@ -709,7 +709,7 @@ Use the following settings to configure the serial connection to the printer:
|
||||
- M1
|
||||
|
||||
# Commands which should not be sent to the printer and just silently ignored.
|
||||
# An example of when you may wish to use this could be useful if you wish to manually change a filament on M600,
|
||||
# An example of when you may wish to use this could be useful if you wish to manually change a filament on M600,
|
||||
# by using that as a Pausing command (below)
|
||||
ignoredCommands:
|
||||
|
||||
@@ -808,6 +808,12 @@ Use the following settings to configure the serial connection to the printer:
|
||||
# Whether to support resends without follow-up ok or not
|
||||
supportResendsWithoutOk: false
|
||||
|
||||
# encoding to use when talking to a machine
|
||||
# (ascii limits access to characters 0-127)
|
||||
# (latin_1 enables access to the "extended" ascii characters 0-255)
|
||||
# other values can be used: https://docs.python.org/3/library/codecs.html#standard-encodings
|
||||
encoding: ascii
|
||||
|
||||
# Whether to "manually" trigger an ok for M29 (a lot of versions of this command are buggy and
|
||||
# the response skips on the ok)
|
||||
triggerOkForM29: true
|
||||
|
||||
@@ -14,7 +14,7 @@ below.
|
||||
|
||||
* Prerequisites:
|
||||
|
||||
* `Python 3.8 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
|
||||
* `Latest stable Python 3 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
|
||||
* `Git <https://git-scm.com>`_
|
||||
|
||||
* Checkout the OctoPrint sources from their Git repository:
|
||||
@@ -24,14 +24,12 @@ below.
|
||||
* Enter the checked out source folder: ``cd OctoPrint``
|
||||
* Create a virtual environment in the checked out source folder to use for
|
||||
installing and running OctoPrint and its dependencies. Creating virtual environments avoids potential versioning
|
||||
issues for the dependencies with system wide installed instances:
|
||||
|
||||
* ``virtualenv --python=python3 venv``
|
||||
issues for the dependencies with system wide installed instances: ``virtualenv --python=python3 venv``
|
||||
|
||||
.. note::
|
||||
|
||||
This assumes that `python3` is a binary available directly on your ``PATH``. If your Python 3
|
||||
binary cannot be found on your ``PATH`` like this you'll need to specify the full path to it here,
|
||||
This assumes that the ``python3`` binary is available directly on your ``PATH``. If
|
||||
it cannot be found on your ``PATH`` like this you'll need to specify the full path here,
|
||||
e.g. ``virtualenv --python=/path/to/python3/bin/python venv``
|
||||
|
||||
* Activate the virtual environment: ``source venv/bin/activate`` (Linux, macOS) or ``source venv/Scripts/activate`` (Git Bash under Windows, see below)
|
||||
@@ -71,7 +69,7 @@ Linux
|
||||
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
|
||||
location, please substitute accordingly.
|
||||
|
||||
First make sure you have python 2 and 3 including their header files, pip, setuptools, virtualenv, git and some build requirements
|
||||
First make sure you have python 3 including its header files, pip, setuptools, virtualenv, git and some build requirements
|
||||
installed:
|
||||
|
||||
* On apt based distributions (e.g. Debian, Ubuntu, ...):
|
||||
@@ -100,7 +98,6 @@ Then:
|
||||
pre-commit install
|
||||
git config blame.ignoreRevsFile .git-blame-ignore-revs
|
||||
|
||||
You can then start OctoPrint via ``octoprint`` after activating one of the two virtual environments.
|
||||
|
||||
.. _sec-development-environment-windows:
|
||||
|
||||
@@ -134,9 +131,9 @@ Open the Git Bash you just installed and in that:
|
||||
cd /c/Devel
|
||||
git clone https://github.com/OctoPrint/OctoPrint.git
|
||||
cd OctoPrint
|
||||
virtualenv --python=C:/Python3/python.exe venv3
|
||||
virtualenv --python=C:/Python3/python.exe venv
|
||||
source ./venv/Scripts/activate
|
||||
python -m pip install --upgrade pip
|
||||
pip install --upgrade pip
|
||||
python -m pip install -e '.[develop,plugins,docs]'
|
||||
pre-commit install
|
||||
git config blame.ignoreRevsFile .git-blame-ignore-revs
|
||||
@@ -176,12 +173,6 @@ Mac OS X
|
||||
This guide is based on the `Setup Guide for Mac OS X on OctoPrint's Community Forum <https://community.octoprint.org/t/setting-up-octoprint-on-macos/13425>`_.
|
||||
Please report back if it works for you, due to lack of access to a Mac I cannot test it myself. Thanks.
|
||||
|
||||
.. todo::
|
||||
|
||||
This guide is not yet adapted to the concurrent use of Python 2 and 3 environments during development. Please send a
|
||||
`Pull Request <https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
|
||||
steps into this guide!
|
||||
|
||||
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
|
||||
location, please substitute accordingly.
|
||||
|
||||
@@ -194,7 +185,7 @@ You'll need a user account with administrator privileges.
|
||||
* ``sudo xcodebuild`` (ensure the license was accepted)
|
||||
* If you have more than one Xcode installed: ``sudo xcode-select -s /Applications/Xcode.app/Contents/Developer``
|
||||
|
||||
* Install Homebrew and use that to install Python:
|
||||
* Install Homebrew and use that to install Python 3:
|
||||
|
||||
* ``ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"``
|
||||
* ``brew install python``
|
||||
@@ -245,7 +236,7 @@ PyCharm
|
||||
- **(macOS)** "PyCharm" > "Preferences ..." > "Project: OctoPrint" > "Project Interpreter" > "Add ..." >
|
||||
"Virtualenv Environment > "Existing Environment", select OctoPrint ``venv`` folder (e.g. ``~/devel/OctoPrint/venv``).
|
||||
|
||||
If desired, repeat for any other additional Python venvs (e.g. different versions).
|
||||
If desired, repeat for any other additional Python venvs (e.g. for separate Python 3 versions).
|
||||
|
||||
- Right click "src" in project tree, mark as source folder
|
||||
- Add Run/Debug Configuration, select "Python":
|
||||
@@ -303,7 +294,7 @@ PyCharm
|
||||
* Name: pre-commit
|
||||
* File type: Python
|
||||
* Scope: Module 'OctoPrint'
|
||||
* Program: ``$PyInterpreterDirectory$/bin/pre-commit`` (Linux) or ``$PyInterpreterDirectory$/Scripts/pre-commit`` (Windows)
|
||||
* Program: ``<OctoPrint venv folder>/bin/pre-commit`` (Linux) or ``<OctoPrint venv folder>/Scripts/pre-commit`` (Windows)
|
||||
* Arguments: ``run --hook-stage manual --files $FilePath$``
|
||||
* Output paths to refresh: ``$FilePath$``
|
||||
* Working directory: ``$ProjectFileDir$``
|
||||
@@ -334,7 +325,7 @@ Visual Studio Code (vscode)
|
||||
.. code-block:: json
|
||||
|
||||
{
|
||||
"python.defaultInterpreterPath": "venv3/bin/python",
|
||||
"python.defaultInterpreterPath": "venv/bin/python",
|
||||
"python.formatting.provider": "black",
|
||||
"python.formatting.blackArgs": [
|
||||
"--config",
|
||||
|
||||
@@ -220,8 +220,10 @@ Upload
|
||||
* ``name``: the file's name
|
||||
* ``path``: the file's path within its storage location
|
||||
* ``target``: the target storage location to which the file was uploaded, either ``local`` or ``sdcard``
|
||||
* ``select``: whether the file will immediately be selected, as requested on the API by the corresponding parameter
|
||||
* ``print``: whether the file will immediately start printing, as requested on the API by the corresponding parameter
|
||||
* ``select``: whether an immediate selection of the file was requested on the API by the corresponding parameter
|
||||
* ``print``: whether an immediate print start of the file was requested on the API by the corresponding parameter
|
||||
* ``effective_select``: whether the file will actually be selected (``select`` request got granted)
|
||||
* ``effective_print``: whether the file will actually start printing (``print`` request got granted)
|
||||
* ``userdata``: optional ``userdata`` if provided on the API, will only be present if supplied in the upload request
|
||||
|
||||
.. deprecated:: 1.3.0
|
||||
|
||||
@@ -57,10 +57,13 @@ The following properties are recognized:
|
||||
|
||||
``__plugin_pythoncompat__``
|
||||
Python compatibility string of your plugin, optional, defaults to ``>=2.7,<3`` if not set and thus Python 2 but no
|
||||
Python 3 compatibility.
|
||||
Python 3 compatibility. This is used as a precaution against issues with some of the Python 2 only plugins
|
||||
that are still out there, as OctoPrint will not even attempt to load plugins whose Python compatibility
|
||||
information doesn't match its current environment.
|
||||
|
||||
If your plugin is compatible to Python 3, you should set this to ``>=2.7,<4``, otherwise your plugin will not load
|
||||
on OctoPrint instances installed under Python 3.
|
||||
If your plugin is compatible to Python 3 only, you should set this to ``>=3.7,<4``.
|
||||
|
||||
If your plugin is compatible to Python 2 and Python 3, you should set this to ``>=2.7,<4``.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
|
||||
@@ -57,13 +57,10 @@ We'll start at the most basic form a plugin can take - just a few simple lines o
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_version__ = "1.0.0"
|
||||
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
|
||||
Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you something resembling these log entries upon server startup::
|
||||
|
||||
@@ -81,8 +78,9 @@ OctoPrint found that plugin in the folder and took a look into it. The name and
|
||||
entry it got from the ``__plugin_name__`` and ``__plugin_version__`` lines. It also read the description from
|
||||
``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now. Additionally
|
||||
there is ``__plugin_pythoncompat__`` which tells OctoPrint here that your plugin can be run under any Python versions
|
||||
between 2.7 and 4. That is necessary so that your plugin will be loadable in OctoPrint instances running under either
|
||||
Python 2 or Python 3, and compatibility to both should be your goal.
|
||||
between 3.7 and 4. That is necessary so that your plugin will be loadable in OctoPrint instances running under Python 3
|
||||
but not Python 2 (so you can use modern language features), and going forward you really should no longer have to care about
|
||||
the end-of-life Python 2.
|
||||
|
||||
.. _sec-plugins-gettingstarted-sayinghello:
|
||||
|
||||
@@ -96,9 +94,6 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t
|
||||
:emphasize-lines: 4-8,14
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin):
|
||||
@@ -108,7 +103,7 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_version__ = "1.0.0"
|
||||
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
and restart OctoPrint. You now get this output in the log::
|
||||
@@ -297,16 +292,13 @@ and ``__plugin_description__`` from ``__init__.py``, but leave ``__plugin_implem
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin):
|
||||
def on_after_startup(self):
|
||||
self._logger.info("Hello World!")
|
||||
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
and restart OctoPrint::
|
||||
@@ -320,12 +312,9 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the
|
||||
"OctoPrint-HelloWorld". That's a bit redundant and squashed, so we'll override that bit via ``__plugin_name__`` again:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 10
|
||||
:emphasize-lines: 7
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin):
|
||||
@@ -333,7 +322,7 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the
|
||||
self._logger.info("Hello World!")
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
|
||||
@@ -369,12 +358,9 @@ navigation bar right at the top that links to the Wikipedia node about "Hello Wo
|
||||
add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 7
|
||||
:emphasize-lines: 4
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
|
||||
@@ -383,7 +369,7 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class:
|
||||
self._logger.info("Hello World!")
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Next, we'll create a sub folder ``templates`` underneath our ``octoprint_helloworld`` folder, and within that a file
|
||||
@@ -436,12 +422,9 @@ mixin.
|
||||
Let's take a look at how all that would look in our plugin's ``__init__.py``:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 8, 10, 12-13
|
||||
:emphasize-lines: 5, 7, 9-10
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
|
||||
@@ -454,7 +437,7 @@ Let's take a look at how all that would look in our plugin's ``__init__.py``:
|
||||
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Restart OctoPrint. You should see something like this::
|
||||
@@ -471,12 +454,9 @@ to add our URL as a template variable.
|
||||
Adjust your plugin's ``__init__.py`` like this:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 15-16
|
||||
:emphasize-lines: 12-13
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
|
||||
@@ -492,7 +472,7 @@ Adjust your plugin's ``__init__.py`` like this:
|
||||
return dict(url=self._settings.get(["url"]))
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this:
|
||||
@@ -579,12 +559,9 @@ for both our ``navbar`` and our ``settings`` plugin. We'll also remove the overr
|
||||
again since we don't use that anymore:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 15-19
|
||||
:emphasize-lines: 12-16
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
|
||||
@@ -603,7 +580,7 @@ again since we don't use that anymore:
|
||||
]
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Restart OctoPrint and shift-reload your browser. Your link in the navigation bar should still point to the URL we
|
||||
@@ -677,12 +654,9 @@ just need to subclass :class:`~octoprint.plugin.AssetPlugin` and override its me
|
||||
like so:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 9,22-25
|
||||
:emphasize-lines: 6,19-22
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
|
||||
@@ -707,7 +681,7 @@ like so:
|
||||
)
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
Note how we did not add another entry to the return value of :func:`~octoprint.plugin.TemplatePlugin.get_template_configs`.
|
||||
@@ -858,12 +832,9 @@ Then adjust our plugin's ``__init__.py`` so that the :func:`~octoprint.plugin.As
|
||||
a reference to our CSS file:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 26
|
||||
:emphasize-lines: 23
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
|
||||
@@ -890,7 +861,7 @@ a reference to our CSS file:
|
||||
)
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
OctoPrint by default bundles all CSS, JavaScript and LESS files to reduce the amount of requests necessary to fully
|
||||
@@ -944,12 +915,9 @@ in the process. The folder structure of our plugin should now look like this::
|
||||
Then adjust our returned assets to include our LESS file as well:
|
||||
|
||||
.. code-block:: python
|
||||
:emphasize-lines: 27
|
||||
:emphasize-lines: 24
|
||||
:linenos:
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
|
||||
@@ -977,7 +945,7 @@ Then adjust our returned assets to include our LESS file as well:
|
||||
)
|
||||
|
||||
__plugin_name__ = "Hello World"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = HelloWorldPlugin()
|
||||
|
||||
|
||||
|
||||
@@ -28,7 +28,6 @@ or as ``postfix`` (after the existing lines).
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
from past import basestring
|
||||
self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.scripts")
|
||||
|
||||
# ...
|
||||
@@ -45,7 +44,7 @@ or as ``postfix`` (after the existing lines).
|
||||
continue
|
||||
|
||||
def to_list(data):
|
||||
if isinstance(data, basestring):
|
||||
if isinstance(data, str):
|
||||
data = map(x.strip() for x in data.split("\n"))
|
||||
|
||||
if isinstance(data, (list, tuple)):
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import sys
|
||||
|
||||
basedir = os.path.dirname(os.path.realpath(__file__))
|
||||
|
||||
old = os.path.join(basedir, "octoprint")
|
||||
if os.path.exists(old):
|
||||
# rename left-overs from old file structure
|
||||
print(
|
||||
"""
|
||||
Found left-overs from old file structure, renaming to
|
||||
"octoprint.backup". Please remove this manually (I don't
|
||||
dare to do so myself since you might have changes in there
|
||||
I don't know anything about).
|
||||
"""
|
||||
)
|
||||
os.rename(old, os.path.join(basedir, "octoprint.backup"))
|
||||
|
||||
sys.path.insert(0, os.path.join(basedir, "src"))
|
||||
|
||||
import octoprint # noqa: E402
|
||||
|
||||
if len(sys.argv) == 1:
|
||||
sys.argv.append("serve")
|
||||
octoprint.main()
|
||||
+6
-1
@@ -28,7 +28,12 @@ Download the systemd files to the locations shown:
|
||||
octoprint.service => /etc/systemd/system/octoprint.service
|
||||
```
|
||||
|
||||
Next, enable and start the `octoprint` service:
|
||||
Next, make necessary modifications (if any) then notify systemd:
|
||||
```sh
|
||||
sudo systemctl daemon-reload
|
||||
```
|
||||
|
||||
Finally, enable and start the `octoprint` service:
|
||||
|
||||
```sh
|
||||
# Enable octoprint service
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
### NOTE #################################################################################
|
||||
# This file has to stay format compatible to Python 2, or pip under Python 2 will
|
||||
# not be able to detect that OctoPrint requires Python 3 but instead fail with a
|
||||
# syntax error.
|
||||
#
|
||||
# So, no f-strings, no walrus operators, no pyupgrade or codemods.
|
||||
##########################################################################################
|
||||
|
||||
import os
|
||||
import sys
|
||||
from distutils.command.build_py import build_py as _build_py
|
||||
@@ -12,75 +22,71 @@ import octoprint_setuptools # noqa: F401,E402
|
||||
# ----------------------------------------------------------------------------------------
|
||||
|
||||
# Supported python versions
|
||||
PYTHON_REQUIRES = ">=3.7,<4"
|
||||
PYTHON_REQUIRES = ">=3.7, <4"
|
||||
|
||||
# Requirements for setup.py
|
||||
SETUP_REQUIRES = [
|
||||
"markdown>=3.2.2,<4",
|
||||
]
|
||||
SETUP_REQUIRES = []
|
||||
|
||||
# Requirements for our application
|
||||
INSTALL_REQUIRES = [
|
||||
# additional OctoPrint plugins that are maintained on a different release cycle
|
||||
bundled_plugins = [
|
||||
"OctoPrint-FileCheck>=2021.2.23",
|
||||
"OctoPrint-FirmwareCheck>=2021.10.11",
|
||||
"OctoPrint-PiSupport>=2021.10.28",
|
||||
# the following dependencies are non trivial to update since later versions
|
||||
# introduce backwards incompatible changes that might affect plugins, or due to
|
||||
# other observed problems
|
||||
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
|
||||
"wrapt>=1.12.1,<1.13", # newer versions fail to build on OctoPi 0.15
|
||||
# anything below this should be checked on releases for new versions
|
||||
"tornado>=6.0.4,<7",
|
||||
"markdown>=3.2.2,<4",
|
||||
"flask>=2,<3",
|
||||
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
|
||||
"Flask-Babel>=2.0,<3",
|
||||
"Flask-Assets>=2.0,<3",
|
||||
]
|
||||
core_deps = [
|
||||
"cachelib>=0.2,<0.3",
|
||||
"PyYAML>=5.4.1,<6",
|
||||
"pyserial>=3.4,<4",
|
||||
"netaddr>=0.7.19,<1",
|
||||
"watchdog==1.0.0",
|
||||
"sarge==0.1.5post0",
|
||||
"netifaces>=0.10.9,<1",
|
||||
"pylru>=1.2,<2",
|
||||
"rsa>=4.0,<5",
|
||||
"pkginfo>=1.5.0.1,<2",
|
||||
"requests>=2.23.0,<3",
|
||||
"semantic_version>=2.8.5,<3",
|
||||
"psutil>=5.8,<6",
|
||||
"Click>=8.0.3,<9",
|
||||
"feedparser>=6.0.8,<7",
|
||||
"future>=0.18.2,<1", # not really needed anymore, but leaving in for py2/3 compat plugins
|
||||
"websocket-client>=1.2.1,<2",
|
||||
"wrapt>=1.12.1,<2",
|
||||
"emoji>=1.4.2,<2",
|
||||
"sentry-sdk>=1.5.0,<2",
|
||||
"filetype>=1.0.7,<2",
|
||||
"frozendict>=2.0,<3",
|
||||
"zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases
|
||||
"zipstream-ng>=1.3.1,<2.0.0",
|
||||
"pathvalidate>=2.4.1,<3",
|
||||
"colorlog>=5.0.1,<6",
|
||||
# vendor bundled dependencies
|
||||
"emoji>=1.4.2,<2",
|
||||
"feedparser>=6.0.8,<7",
|
||||
"filetype>=1.0.7,<2",
|
||||
"Flask-Assets>=2.0,<3",
|
||||
"Flask-Babel>=2.0,<3",
|
||||
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
|
||||
"flask>=2,<3",
|
||||
"frozendict>=2.0,<3",
|
||||
"future>=0.18.2,<1", # not really needed anymore, but leaving in for py2/3 compat plugins
|
||||
"markdown>=3.2.2,<4",
|
||||
"netaddr>=0.8,<0.9", # changelog hints at breaking changes on minor version increases
|
||||
"netifaces>=0.11,<1",
|
||||
"pathvalidate>=2.4.1,<3",
|
||||
"pkginfo>=1.7.1,<2",
|
||||
"psutil>=5.8,<6",
|
||||
"pylru>=1.2,<2",
|
||||
"pyserial>=3.4,<4",
|
||||
"PyYAML>=5.4.1,<6",
|
||||
"requests>=2.26.0,<3",
|
||||
"sarge==0.1.6",
|
||||
"semantic_version>=2.8.5,<3",
|
||||
"sentry-sdk>=1.3.1,<2",
|
||||
"tornado>=6.0.4,<7",
|
||||
"watchdog==1.0.0",
|
||||
"websocket-client>=1.2.1,<2",
|
||||
"wrapt>=1.13.3,<1.14",
|
||||
"zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases
|
||||
"zipstream-ng>=1.3.4,<2.0.0",
|
||||
]
|
||||
vendored_deps = [
|
||||
"blinker>=1.4,<2", # dependency of flask_principal
|
||||
"unidecode", # dependency of awesome-slugify, leave w/o range to not cause dependency hell w/ Octolapse deps
|
||||
"regex", # dependency of awesome-slugify
|
||||
"unidecode", # dependency of awesome-slugify
|
||||
]
|
||||
|
||||
# OSX specific requirements
|
||||
INSTALL_REQUIRES_OSX = [
|
||||
"appdirs>=1.4.4,<2",
|
||||
]
|
||||
INSTALL_REQUIRES = bundled_plugins + core_deps + vendored_deps
|
||||
|
||||
# Additional requirements for optional install options
|
||||
# Additional requirements for optional install options and/or OS-specific dependencies
|
||||
EXTRA_REQUIRES = {
|
||||
# Dependencies for OSX
|
||||
":sys_platform == 'darwin'": [
|
||||
"appdirs>=1.4.4,<2",
|
||||
],
|
||||
# Dependencies for core development
|
||||
"develop": [
|
||||
# Testing dependencies
|
||||
"mock>=4,<5",
|
||||
"pytest>=6.2.5,<7",
|
||||
"pytest-doctest-custom>=1.0.0,<2",
|
||||
"ddt",
|
||||
"mock>=4,<5",
|
||||
"pytest-doctest-custom>=1.0.0,<2",
|
||||
"pytest>=6.2.5,<7",
|
||||
# pre-commit
|
||||
"pre-commit",
|
||||
# profiler
|
||||
@@ -90,39 +96,36 @@ EXTRA_REQUIRES = {
|
||||
"plugins": ["cookiecutter>=1.7.2,<1.8"],
|
||||
# Dependencies for building the documentation
|
||||
"docs": [
|
||||
"readthedocs-sphinx-ext",
|
||||
"sphinx_rtd_theme",
|
||||
"sphinx>=3,<4",
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinxcontrib-mermaid",
|
||||
"sphinx_rtd_theme",
|
||||
"readthedocs-sphinx-ext",
|
||||
],
|
||||
}
|
||||
|
||||
# Dependency links for any of the aforementioned dependencies
|
||||
DEPENDENCY_LINKS = []
|
||||
|
||||
EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX
|
||||
|
||||
# -----------------------------------------------------------------------------------------------------------------------
|
||||
# ----------------------------------------------------------------------------------------
|
||||
# Anything below here is just command setup and general setup configuration
|
||||
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
|
||||
def read_file_contents(path):
|
||||
import codecs
|
||||
import io
|
||||
|
||||
with codecs.open(path, encoding="utf-8") as f:
|
||||
with io.open(path, encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def md_to_html_build_py_factory(files, baseclass):
|
||||
class md_to_html_build_py(baseclass):
|
||||
def copy_files_build_py_factory(files, baseclass):
|
||||
class copy_files_build_py(baseclass):
|
||||
files = {}
|
||||
|
||||
def run(self):
|
||||
print("RUNNING md_to_html_build_py")
|
||||
print("RUNNING copy_files_build_py")
|
||||
if not self.dry_run:
|
||||
import shutil
|
||||
|
||||
for directory, files in self.files.items():
|
||||
target_dir = os.path.join(self.build_lib, directory)
|
||||
self.mkpath(target_dir)
|
||||
@@ -134,17 +137,15 @@ def md_to_html_build_py_factory(files, baseclass):
|
||||
source, dest = entry[0], os.path.join(target_dir, entry[1])
|
||||
else:
|
||||
source = entry
|
||||
dest = os.path.join(target_dir, source + ".html")
|
||||
dest = os.path.join(target_dir, source)
|
||||
|
||||
print(f"Rendering markdown from {source} to {dest}")
|
||||
print("Copying {} to {}".format(source, dest))
|
||||
shutil.copy2(source, dest)
|
||||
|
||||
from markdown import markdownFromFile
|
||||
|
||||
markdownFromFile(input=source, output=dest, encoding="utf-8")
|
||||
baseclass.run(self)
|
||||
|
||||
return type(md_to_html_build_py)(
|
||||
md_to_html_build_py.__name__, (md_to_html_build_py,), {"files": files}
|
||||
return type(copy_files_build_py)(
|
||||
copy_files_build_py.__name__, (copy_files_build_py,), {"files": files}
|
||||
)
|
||||
|
||||
|
||||
@@ -177,7 +178,7 @@ def get_cmdclass():
|
||||
)
|
||||
)
|
||||
|
||||
cmdclass["build_py"] = md_to_html_build_py_factory(
|
||||
cmdclass["build_py"] = copy_files_build_py_factory(
|
||||
{
|
||||
"octoprint/templates/_data": [
|
||||
"AUTHORS.md",
|
||||
@@ -193,7 +194,7 @@ def get_cmdclass():
|
||||
|
||||
def params():
|
||||
# make sure these are always available, even when run by dependabot
|
||||
global versioneer, get_cmdclass, read_file_contents, here, PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES, DEPENDENCY_LINKS
|
||||
global versioneer, get_cmdclass, read_file_contents, here, PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES
|
||||
|
||||
name = "OctoPrint"
|
||||
version = versioneer.get_version()
|
||||
@@ -207,7 +208,6 @@ def params():
|
||||
setup_requires = SETUP_REQUIRES
|
||||
install_requires = INSTALL_REQUIRES
|
||||
extras_require = EXTRA_REQUIRES
|
||||
dependency_links = DEPENDENCY_LINKS
|
||||
|
||||
classifiers = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
@@ -225,7 +225,6 @@ def params():
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.6",
|
||||
"Programming Language :: Python :: 3.7",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
@@ -264,8 +263,7 @@ def params():
|
||||
|
||||
if os.environ.get("READTHEDOCS", None) == "True":
|
||||
# we can't tell read the docs to please perform a pip install -e .[docs], so we help
|
||||
# it a bit here by explicitly adding the development dependencies, which include our
|
||||
# documentation dependencies
|
||||
# it a bit here by explicitly adding the docs dependencies
|
||||
install_requires = install_requires + extras_require["docs"]
|
||||
|
||||
entry_points = {"console_scripts": ["octoprint = octoprint:main"]}
|
||||
|
||||
@@ -7,6 +7,7 @@ import sys
|
||||
import click
|
||||
|
||||
import octoprint
|
||||
from octoprint.cli.common import LazyGroup
|
||||
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
@@ -274,16 +275,56 @@ legacy_options = bulk_options(
|
||||
Kept available for reasons of backwards compatibility, but hidden from the
|
||||
generated help pages."""
|
||||
|
||||
# ~~ command groups from sub modules
|
||||
|
||||
|
||||
@click.group()
|
||||
def subcommands():
|
||||
pass
|
||||
|
||||
|
||||
@subcommands.group(
|
||||
name="analysis", cls=LazyGroup, import_name="octoprint.cli.analysis:cli"
|
||||
)
|
||||
def analysis():
|
||||
"""Analysis tools."""
|
||||
pass
|
||||
|
||||
|
||||
@subcommands.group(name="client", cls=LazyGroup, import_name="octoprint.cli.client:cli")
|
||||
def client():
|
||||
"""Basic API client."""
|
||||
pass
|
||||
|
||||
|
||||
@subcommands.group(name="config", cls=LazyGroup, import_name="octoprint.cli.config:cli")
|
||||
def config():
|
||||
"""Basic config manipulation."""
|
||||
pass
|
||||
|
||||
|
||||
@subcommands.group(name="dev", cls=LazyGroup, import_name="octoprint.cli.dev:cli")
|
||||
def dev():
|
||||
"""Additional commands for development tasks."""
|
||||
pass
|
||||
|
||||
|
||||
@subcommands.group(name="plugins", cls=LazyGroup, import_name="octoprint.cli.plugins:cli")
|
||||
def plugins():
|
||||
"""Additional commands provided by plugins."""
|
||||
pass
|
||||
|
||||
|
||||
@subcommands.group(name="user", cls=LazyGroup, import_name="octoprint.cli.user:cli")
|
||||
def user():
|
||||
"""User management."""
|
||||
pass
|
||||
|
||||
|
||||
# ~~ "octoprint" command, merges server_commands and plugin_commands groups
|
||||
|
||||
from .analysis import analysis_commands # noqa: E402
|
||||
from .client import client_commands # noqa: E402
|
||||
from .config import config_commands # noqa: E402
|
||||
from .dev import dev_commands # noqa: E402
|
||||
from .plugins import plugin_commands # noqa: E402
|
||||
from .server import server_commands # noqa: E402
|
||||
from .systeminfo import systeminfo_commands # noqa: E402
|
||||
from .user import user_commands # noqa: E402
|
||||
from .server import cli as server_commands # noqa: E402
|
||||
from .systeminfo import cli as systeminfo_commands # noqa: E402
|
||||
|
||||
|
||||
@click.group(
|
||||
@@ -291,13 +332,8 @@ from .user import user_commands # noqa: E402
|
||||
invoke_without_command=True,
|
||||
cls=click.CommandCollection,
|
||||
sources=[
|
||||
subcommands,
|
||||
server_commands,
|
||||
plugin_commands,
|
||||
dev_commands,
|
||||
client_commands,
|
||||
config_commands,
|
||||
analysis_commands,
|
||||
user_commands,
|
||||
systeminfo_commands,
|
||||
],
|
||||
)
|
||||
|
||||
@@ -55,17 +55,12 @@ def validate_result(result):
|
||||
|
||||
|
||||
@click.group()
|
||||
def analysis_commands():
|
||||
pass
|
||||
|
||||
|
||||
@analysis_commands.group(name="analysis")
|
||||
def util():
|
||||
def cli():
|
||||
"""Analysis tools."""
|
||||
pass
|
||||
|
||||
|
||||
@util.command(name="gcode")
|
||||
@cli.command(name="gcode")
|
||||
@click.option("--throttle", "throttle", type=float, default=None)
|
||||
@click.option("--throttle-lines", "throttle_lines", type=int, default=None)
|
||||
@click.option("--speed-x", "speedx", type=float, default=6000)
|
||||
|
||||
+10
-15
@@ -78,15 +78,10 @@ client_options = bulk_options(
|
||||
"""Common options to configure an API client."""
|
||||
|
||||
|
||||
@click.group()
|
||||
def client_commands():
|
||||
pass
|
||||
|
||||
|
||||
@client_commands.group("client", context_settings={"ignore_unknown_options": True})
|
||||
@click.group(context_settings={"ignore_unknown_options": True})
|
||||
@client_options
|
||||
@click.pass_context
|
||||
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
|
||||
def cli(ctx, apikey, host, port, httpuser, httppass, https, prefix):
|
||||
"""Basic API client."""
|
||||
try:
|
||||
settings = None
|
||||
@@ -124,7 +119,7 @@ def log_response(response, status_code=True, body=True, headers=False):
|
||||
click.echo(response.text)
|
||||
|
||||
|
||||
@client.command("get")
|
||||
@cli.command("get")
|
||||
@click.argument("path")
|
||||
@click.option("--timeout", type=float, default=None)
|
||||
@click.pass_context
|
||||
@@ -134,7 +129,7 @@ def get(ctx, path, timeout):
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("post_json")
|
||||
@cli.command("post_json")
|
||||
@click.argument("path")
|
||||
@click.argument("data", type=JsonStringParamType())
|
||||
@click.option("--timeout", type=float, default=None)
|
||||
@@ -145,7 +140,7 @@ def post_json(ctx, path, data, timeout):
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("patch_json")
|
||||
@cli.command("patch_json")
|
||||
@click.argument("path")
|
||||
@click.argument("data", type=JsonStringParamType())
|
||||
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||
@@ -156,7 +151,7 @@ def patch_json(ctx, path, data, timeout):
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("post_from_file")
|
||||
@cli.command("post_from_file")
|
||||
@click.argument("path")
|
||||
@click.argument(
|
||||
"file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)
|
||||
@@ -184,7 +179,7 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("command")
|
||||
@cli.command("command")
|
||||
@click.argument("path")
|
||||
@click.argument("command")
|
||||
@click.option(
|
||||
@@ -228,7 +223,7 @@ def command(
|
||||
log_response(r, body=False)
|
||||
|
||||
|
||||
@client.command("upload")
|
||||
@cli.command("upload")
|
||||
@click.argument("path")
|
||||
@click.argument(
|
||||
"file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)
|
||||
@@ -262,7 +257,7 @@ def upload(ctx, path, file_path, params, file_name, content_type, timeout):
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("delete")
|
||||
@cli.command("delete")
|
||||
@click.argument("path")
|
||||
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||
@click.pass_context
|
||||
@@ -272,7 +267,7 @@ def delete(ctx, path, timeout):
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("listen")
|
||||
@cli.command("listen")
|
||||
@click.pass_context
|
||||
def listen(ctx):
|
||||
def on_connect(ws):
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
from importlib import import_module
|
||||
|
||||
import click
|
||||
from werkzeug.utils import cached_property
|
||||
|
||||
|
||||
class LazyGroup(click.Group):
|
||||
"""
|
||||
A click Group that imports the actual implementation only when
|
||||
needed. This allows for more resilient CLIs where the top-level
|
||||
command does not fail when a subcommand is broken enough to fail
|
||||
at import time.
|
||||
"""
|
||||
|
||||
# shared by https://github.com/indico/indico in pallets/click#945
|
||||
|
||||
def __init__(self, import_name, **kwargs):
|
||||
self._import_name = import_name
|
||||
click.Group.__init__(self, **kwargs)
|
||||
|
||||
@cached_property
|
||||
def _impl(self):
|
||||
module, name = self._import_name.split(":", 1)
|
||||
return getattr(import_module(module), name)
|
||||
|
||||
def get_command(self, ctx, cmd_name):
|
||||
return self._impl.get_command(ctx, cmd_name)
|
||||
|
||||
def list_commands(self, ctx):
|
||||
return self._impl.list_commands(ctx)
|
||||
|
||||
def invoke(self, ctx):
|
||||
return self._impl.invoke(ctx)
|
||||
|
||||
def get_usage(self, ctx):
|
||||
return self._impl.get_usage(ctx)
|
||||
|
||||
def get_params(self, ctx):
|
||||
return self._impl.get_params(ctx)
|
||||
@@ -45,13 +45,8 @@ def _set_helper(settings, path, value, data_type=None):
|
||||
|
||||
|
||||
@click.group()
|
||||
def config_commands():
|
||||
pass
|
||||
|
||||
|
||||
@config_commands.group(name="config")
|
||||
@click.pass_context
|
||||
def config(ctx):
|
||||
def cli(ctx):
|
||||
"""Basic config manipulation."""
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG
|
||||
@@ -70,7 +65,7 @@ def config(ctx):
|
||||
ctx.exit(-1)
|
||||
|
||||
|
||||
@config.command(name="set")
|
||||
@cli.command(name="set")
|
||||
@standard_options(hidden=True)
|
||||
@click.argument("path", type=click.STRING)
|
||||
@click.argument("value", type=click.STRING)
|
||||
@@ -99,7 +94,7 @@ def set_command(ctx, path, value, as_bool, as_float, as_int, as_json):
|
||||
_set_helper(ctx.obj.settings, path, value, data_type=data_type)
|
||||
|
||||
|
||||
@config.command(name="remove")
|
||||
@cli.command(name="remove")
|
||||
@standard_options(hidden=True)
|
||||
@click.argument("path", type=click.STRING)
|
||||
@click.pass_context
|
||||
@@ -108,7 +103,7 @@ def remove_command(ctx, path):
|
||||
_set_helper(ctx.obj.settings, path, None)
|
||||
|
||||
|
||||
@config.command(name="append_value")
|
||||
@cli.command(name="append_value")
|
||||
@standard_options(hidden=True)
|
||||
@click.argument("path", type=click.STRING)
|
||||
@click.argument("value", type=click.STRING)
|
||||
@@ -136,7 +131,7 @@ def append_value_command(ctx, path, value, as_json=False):
|
||||
_set_helper(ctx.obj.settings, path, current)
|
||||
|
||||
|
||||
@config.command(name="insert_value")
|
||||
@cli.command(name="insert_value")
|
||||
@standard_options(hidden=True)
|
||||
@click.argument("path", type=click.STRING)
|
||||
@click.argument("index", type=click.INT)
|
||||
@@ -165,7 +160,7 @@ def insert_value_command(ctx, path, index, value, as_json=False):
|
||||
_set_helper(ctx.obj.settings, path, current)
|
||||
|
||||
|
||||
@config.command(name="remove_value")
|
||||
@cli.command(name="remove_value")
|
||||
@standard_options(hidden=True)
|
||||
@click.argument("path", type=click.STRING)
|
||||
@click.argument("value", type=click.STRING)
|
||||
@@ -197,7 +192,7 @@ def remove_value_command(ctx, path, value, as_json=False):
|
||||
_set_helper(ctx.obj.settings, path, current)
|
||||
|
||||
|
||||
@config.command(name="get")
|
||||
@cli.command(name="get")
|
||||
@click.argument("path", type=click.STRING)
|
||||
@click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON")
|
||||
@click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML")
|
||||
@@ -223,7 +218,7 @@ def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
|
||||
click.echo(output)
|
||||
|
||||
|
||||
@config.command(name="effective")
|
||||
@cli.command(name="effective")
|
||||
@click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON")
|
||||
@click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML")
|
||||
@click.option(
|
||||
|
||||
@@ -250,12 +250,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
|
||||
return command
|
||||
|
||||
|
||||
@click.group()
|
||||
def dev_commands():
|
||||
pass
|
||||
|
||||
|
||||
@dev_commands.group(name="dev", cls=OctoPrintDevelCommands)
|
||||
def dev():
|
||||
@click.group(cls=OctoPrintDevelCommands)
|
||||
def cli():
|
||||
"""Additional commands for development tasks."""
|
||||
pass
|
||||
@@ -138,13 +138,8 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
return result
|
||||
|
||||
|
||||
@click.group()
|
||||
@click.group(cls=OctoPrintPluginCommands)
|
||||
@pass_octoprint_ctx
|
||||
def plugin_commands(obj):
|
||||
pass
|
||||
|
||||
|
||||
@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands)
|
||||
def plugins():
|
||||
def cli(obj):
|
||||
"""Additional commands provided by plugins."""
|
||||
pass
|
||||
@@ -248,11 +248,11 @@ daemon_options = bulk_options(
|
||||
|
||||
|
||||
@click.group()
|
||||
def server_commands():
|
||||
def cli():
|
||||
pass
|
||||
|
||||
|
||||
@server_commands.command(name="safemode")
|
||||
@cli.command(name="safemode")
|
||||
@standard_options()
|
||||
@click.pass_context
|
||||
def enable_safemode(ctx, **kwargs):
|
||||
@@ -283,7 +283,7 @@ def enable_safemode(ctx, **kwargs):
|
||||
)
|
||||
|
||||
|
||||
@server_commands.command(name="serve")
|
||||
@cli.command(name="serve")
|
||||
@standard_options()
|
||||
@server_options
|
||||
@click.pass_context
|
||||
@@ -330,7 +330,7 @@ def serve_command(ctx, **kwargs):
|
||||
if sys.platform != "win32" and sys.platform != "darwin":
|
||||
# we do not support daemon mode under windows or macosx
|
||||
|
||||
@server_commands.command(name="daemon")
|
||||
@cli.command(name="daemon")
|
||||
@standard_options()
|
||||
@server_options
|
||||
@daemon_options
|
||||
|
||||
@@ -79,7 +79,7 @@ def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None
|
||||
|
||||
# Add printer log, if available
|
||||
if hasattr(printer, "_log"):
|
||||
z.add(to_bytes("\n".join(printer._log)), "terminal.txt")
|
||||
z.add(to_bytes("\n".join(printer._log)), arcname="terminal.txt")
|
||||
|
||||
# add systeminfo
|
||||
systeminfotxt = []
|
||||
@@ -137,11 +137,11 @@ def get_systeminfo_bundle_name():
|
||||
|
||||
|
||||
@click.group()
|
||||
def systeminfo_commands():
|
||||
def cli():
|
||||
pass
|
||||
|
||||
|
||||
@systeminfo_commands.command(name="systeminfo")
|
||||
@cli.command(name="systeminfo")
|
||||
@standard_options()
|
||||
@click.argument(
|
||||
"path",
|
||||
|
||||
@@ -23,13 +23,8 @@ click.disable_unicode_literals_warning = True
|
||||
|
||||
|
||||
@click.group()
|
||||
def user_commands():
|
||||
pass
|
||||
|
||||
|
||||
@user_commands.group(name="user")
|
||||
@click.pass_context
|
||||
def user(ctx):
|
||||
def cli(ctx):
|
||||
"""
|
||||
User management.
|
||||
|
||||
@@ -84,7 +79,7 @@ def user(ctx):
|
||||
ctx.exit(-1)
|
||||
|
||||
|
||||
@user.command(name="list")
|
||||
@cli.command(name="list")
|
||||
@click.pass_context
|
||||
def list_users_command(ctx):
|
||||
"""Lists user information"""
|
||||
@@ -92,7 +87,7 @@ def list_users_command(ctx):
|
||||
_print_list(users)
|
||||
|
||||
|
||||
@user.command(name="add")
|
||||
@cli.command(name="add")
|
||||
@click.argument("username", type=click.STRING, required=True)
|
||||
@click.password_option("--password", "password", help="Password for the user")
|
||||
@click.option("-g", "--group", "groups", multiple=True, help="Groups to set on the user")
|
||||
@@ -133,7 +128,7 @@ def add_user_command(ctx, username, password, groups, permissions, is_admin):
|
||||
click.echo(f"A user with the name {username} does already exist!", err=True)
|
||||
|
||||
|
||||
@user.command(name="remove")
|
||||
@cli.command(name="remove")
|
||||
@click.argument("username", type=click.STRING)
|
||||
@click.pass_context
|
||||
def remove_user_command(ctx, username):
|
||||
@@ -150,7 +145,7 @@ def remove_user_command(ctx, username):
|
||||
click.echo(f"User {username} not removed.")
|
||||
|
||||
|
||||
@user.command(name="password")
|
||||
@cli.command(name="password")
|
||||
@click.argument("username", type=click.STRING)
|
||||
@click.password_option("--password", "password", help="New password for user")
|
||||
@click.pass_context
|
||||
@@ -163,7 +158,7 @@ def change_password_command(ctx, username, password):
|
||||
click.echo(f"User {username} does not exist!", err=True)
|
||||
|
||||
|
||||
@user.command(name="activate")
|
||||
@cli.command(name="activate")
|
||||
@click.argument("username", type=click.STRING)
|
||||
@click.pass_context
|
||||
def activate_command(ctx, username):
|
||||
@@ -180,7 +175,7 @@ def activate_command(ctx, username):
|
||||
click.echo(f"User {username} does not exist!", err=True)
|
||||
|
||||
|
||||
@user.command(name="deactivate")
|
||||
@cli.command(name="deactivate")
|
||||
@click.argument("username", type=click.STRING)
|
||||
@click.pass_context
|
||||
def deactivate_command(ctx, username):
|
||||
|
||||
@@ -125,7 +125,7 @@ class MultiStream(io.RawIOBase):
|
||||
"""
|
||||
|
||||
def __init__(self, *streams):
|
||||
io.RawIOBase.__init__(self)
|
||||
super().__init__()
|
||||
self.streams = streams
|
||||
self.current_stream = 0
|
||||
|
||||
@@ -184,7 +184,7 @@ class LineProcessorStream(io.RawIOBase):
|
||||
"""
|
||||
|
||||
def __init__(self, input_stream):
|
||||
io.RawIOBase.__init__(self)
|
||||
super().__init__()
|
||||
self.input_stream = io.BufferedReader(input_stream)
|
||||
self.leftover = bytearray()
|
||||
|
||||
|
||||
@@ -84,17 +84,17 @@ def get_divider_line(c, message=None, length=78, indent=3):
|
||||
|
||||
Examples:
|
||||
|
||||
>>> get_divider_line("-") # doctest: +ALLOW_UNICODE
|
||||
>>> get_divider_line("-")
|
||||
'------------------------------------------------------------------------------'
|
||||
>>> get_divider_line("=", length=10) # doctest: +ALLOW_UNICODE
|
||||
>>> get_divider_line("=", length=10)
|
||||
'=========='
|
||||
>>> get_divider_line("-", message="Hi", length=10) # doctest: +ALLOW_UNICODE
|
||||
>>> get_divider_line("-", message="Hi", length=10)
|
||||
'--- Hi ---'
|
||||
>>> get_divider_line("-", message="A slightly longer text") # doctest: +ALLOW_UNICODE
|
||||
>>> get_divider_line("-", message="A slightly longer text")
|
||||
'--- A slightly longer text ---------------------------------------------------'
|
||||
>>> get_divider_line("-", message="A slightly longer text", indent=5) # doctest: +ALLOW_UNICODE
|
||||
>>> get_divider_line("-", message="A slightly longer text", indent=5)
|
||||
'----- A slightly longer text -------------------------------------------------'
|
||||
>>> get_divider_line("-", message="Hello World!", length=10) # doctest: +ALLOW_UNICODE
|
||||
>>> get_divider_line("-", message="Hello World!", length=10)
|
||||
'--- Hello World!'
|
||||
>>> get_divider_line(None)
|
||||
Traceback (most recent call last):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import logging
|
||||
from urllib import parse as urlparse
|
||||
import urllib.parse
|
||||
|
||||
|
||||
class TornadoAccessFilter(logging.Filter):
|
||||
@@ -9,8 +9,8 @@ class TornadoAccessFilter(logging.Filter):
|
||||
|
||||
if status == 409:
|
||||
|
||||
method, url, client = request_line.split()
|
||||
u = urlparse.urlparse(url)
|
||||
_, url, _ = request_line.split()
|
||||
u = urllib.parse.urlparse(url)
|
||||
if u.path in ("/api/printer",):
|
||||
record.levelno = logging.INFO
|
||||
record.levelname = logging.getLevelName(record.levelno)
|
||||
|
||||
@@ -69,7 +69,7 @@ def parse_plugin_metadata(path):
|
||||
# we only support parsing plain text source files
|
||||
return result
|
||||
|
||||
logger.debug(f"Parsing plugin metadata from AST of {path}".format(path))
|
||||
logger.debug(f"Parsing plugin metadata from AST of {path}")
|
||||
|
||||
try:
|
||||
import ast
|
||||
@@ -781,9 +781,7 @@ class PluginInfo:
|
||||
try:
|
||||
return parse_plugin_metadata(self.location)
|
||||
except SyntaxError:
|
||||
self._logger.exception(
|
||||
f"Invalid syntax in plugin file of plugin {self.key}".format(self.key)
|
||||
)
|
||||
self._logger.exception(f"Invalid syntax in plugin file of plugin {self.key}")
|
||||
self.invalid_syntax = True
|
||||
return {}
|
||||
|
||||
@@ -891,13 +889,9 @@ class PluginManager:
|
||||
|
||||
def _detect_python_environment(self):
|
||||
import sys
|
||||
from distutils.command.install import install as cmd_install
|
||||
from distutils.dist import Distribution
|
||||
import sysconfig
|
||||
|
||||
cmd = cmd_install(Distribution())
|
||||
cmd.finalize_options()
|
||||
|
||||
self._python_install_dir = cmd.install_lib
|
||||
self._python_install_dir = sysconfig.get_path("purelib")
|
||||
self._python_prefix = os.path.realpath(sys.prefix)
|
||||
self._python_virtual_env = hasattr(sys, "real_prefix") or (
|
||||
hasattr(sys, "base_prefix")
|
||||
@@ -2333,8 +2327,6 @@ class EntryPointMetadata(pkginfo.Distribution):
|
||||
return self.entry_point.dist.get_metadata(metadata_file)
|
||||
except OSError: # noqa: B014
|
||||
# file not found, metadata file might be missing, ignore
|
||||
# IOError: file not found in Py2
|
||||
# OSError (specifically FileNotFoundError): file not found in Py3
|
||||
pass
|
||||
|
||||
warnings.warn(
|
||||
|
||||
@@ -2073,12 +2073,11 @@ class SlicerPlugin(OctoPrintPlugin):
|
||||
.. versionadded:: 1.3.0
|
||||
"""
|
||||
import os
|
||||
from os import scandir
|
||||
|
||||
lms = [os.stat(profile_path).st_mtime]
|
||||
lms += [
|
||||
os.stat(entry.path).st_mtime
|
||||
for entry in scandir(profile_path)
|
||||
for entry in os.scandir(profile_path)
|
||||
if entry.name.endswith(".profile")
|
||||
]
|
||||
return max(lms)
|
||||
|
||||
@@ -141,7 +141,7 @@ __plugin_disabling_discouraged__ = gettext(
|
||||
" notifications in OctoPrint"
|
||||
)
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = ActionCommandNotificationPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
|
||||
|
||||
@@ -290,7 +290,7 @@ __plugin_disabling_discouraged__ = gettext(
|
||||
" confirmation or selection prompts in OctoPrint"
|
||||
)
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = ActionCommandPromptPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
|
||||
|
||||
@@ -6,7 +6,6 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms
|
||||
import calendar
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
@@ -27,8 +26,6 @@ from octoprint.server.util.flask import (
|
||||
from octoprint.util import count, utmify
|
||||
from octoprint.util.text import sanitize
|
||||
|
||||
PY2 = sys.version_info[0] < 3
|
||||
|
||||
|
||||
class AnnouncementPlugin(
|
||||
octoprint.plugin.AssetPlugin,
|
||||
@@ -523,11 +520,11 @@ _image_tag_re = re.compile(r"<img.*?/?>")
|
||||
|
||||
def _strip_images(text):
|
||||
"""
|
||||
>>> _strip_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>") # doctest: +ALLOW_UNICODE
|
||||
>>> _strip_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
|
||||
"<a href='test.html'>I'm a link</a> and this is an image: "
|
||||
>>> _strip_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">") # doctest: +ALLOW_UNICODE
|
||||
>>> _strip_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">")
|
||||
'One and two and three and four '
|
||||
>>> _strip_images("No images here") # doctest: +ALLOW_UNICODE
|
||||
>>> _strip_images("No images here")
|
||||
'No images here'
|
||||
"""
|
||||
return _image_tag_re.sub("", text)
|
||||
@@ -536,9 +533,9 @@ def _strip_images(text):
|
||||
def _replace_images(text, callback):
|
||||
"""
|
||||
>>> callback = lambda img: "foobar"
|
||||
>>> _replace_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", callback) # doctest: +ALLOW_UNICODE
|
||||
>>> _replace_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", callback)
|
||||
"<a href='test.html'>I'm a link</a> and this is an image: foobar"
|
||||
>>> _replace_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", callback) # doctest: +ALLOW_UNICODE
|
||||
>>> _replace_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", callback)
|
||||
'One foobar and two foobar and three foobar and four foobar'
|
||||
"""
|
||||
result = text
|
||||
@@ -554,13 +551,13 @@ _image_src_re = re.compile(r'src=(?P<quote>[\'"]*)(?P<src>.*?)(?P=quote)(?=\s+|>
|
||||
|
||||
def _lazy_images(text, placeholder=None):
|
||||
"""
|
||||
>>> _lazy_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>") # doctest: +ALLOW_UNICODE
|
||||
>>> _lazy_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
|
||||
'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
|
||||
>>> _lazy_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", placeholder="ph.png") # doctest: +ALLOW_UNICODE
|
||||
>>> _lazy_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", placeholder="ph.png")
|
||||
'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="ph.png" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
|
||||
>>> _lazy_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", placeholder="ph.png") # doctest: +ALLOW_UNICODE
|
||||
>>> _lazy_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", placeholder="ph.png")
|
||||
'One <img src="ph.png" data-src="one.jpg"> and two <img src="ph.png" data-src=\\'two.jpg\\' > and three <img src="ph.png" data-src=three.jpg> and four <img src="ph.png" data-src="four.png" alt="four">'
|
||||
>>> _lazy_images("No images here") # doctest: +ALLOW_UNICODE
|
||||
>>> _lazy_images("No images here")
|
||||
'No images here'
|
||||
"""
|
||||
if placeholder is None:
|
||||
@@ -583,9 +580,9 @@ def _lazy_images(text, placeholder=None):
|
||||
|
||||
def _strip_tags(text):
|
||||
"""
|
||||
>>> _strip_tags("<a href='test.html'>Hello world</a><img src='foo.jpg'>") # doctest: +ALLOW_UNICODE
|
||||
>>> _strip_tags("<a href='test.html'>Hello world</a><img src='foo.jpg'>")
|
||||
"Hello world<img src='foo.jpg'>"
|
||||
>>> _strip_tags("> > Foo") # doctest: +ALLOW_UNICODE
|
||||
>>> _strip_tags("> > Foo")
|
||||
'> > Foo'
|
||||
"""
|
||||
from html.parser import HTMLParser
|
||||
@@ -607,7 +604,7 @@ def _strip_tags(text):
|
||||
def get_data(self):
|
||||
return "".join(self._fed)
|
||||
|
||||
tag_stripper = TagStripper() if PY2 else TagStripper(convert_charrefs=False)
|
||||
tag_stripper = TagStripper(convert_charrefs=False)
|
||||
tag_stripper.feed(text)
|
||||
return tag_stripper.get_data()
|
||||
|
||||
@@ -620,7 +617,7 @@ __plugin_disabling_discouraged__ = gettext(
|
||||
"regarding security or other critical issues concerning OctoPrint."
|
||||
)
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = AnnouncementPlugin()
|
||||
|
||||
__plugin_hooks__ = {
|
||||
|
||||
@@ -541,7 +541,7 @@ __plugin_disabling_discouraged__ = gettext(
|
||||
"obtain an API key without you manually copy-pasting it."
|
||||
)
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = AppKeysPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key,
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
__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"
|
||||
|
||||
from os import scandir
|
||||
|
||||
import octoprint.plugin
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
@@ -729,7 +727,7 @@ class BackupPlugin(
|
||||
|
||||
def _get_backups(self):
|
||||
backups = []
|
||||
for entry in scandir(self.get_plugin_data_folder()):
|
||||
for entry in os.scandir(self.get_plugin_data_folder()):
|
||||
if is_hidden_path(entry.path):
|
||||
continue
|
||||
if not entry.is_file():
|
||||
@@ -828,7 +826,7 @@ class BackupPlugin(
|
||||
return 0
|
||||
|
||||
total = 0
|
||||
for entry in scandir(path):
|
||||
for entry in os.scandir(path):
|
||||
if entry.is_dir():
|
||||
total += cls._get_disk_size(entry.path, ignored=ignored)
|
||||
elif entry.is_file():
|
||||
@@ -1015,7 +1013,7 @@ class BackupPlugin(
|
||||
return
|
||||
|
||||
if os.path.isdir(source):
|
||||
for entry in scandir(source):
|
||||
for entry in os.scandir(source):
|
||||
add_to_zip(
|
||||
entry.path,
|
||||
os.path.join(target, entry.name),
|
||||
@@ -1402,7 +1400,7 @@ __plugin_disabling_discouraged__ = gettext(
|
||||
"& restore your OctoPrint settings and data."
|
||||
)
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = BackupPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.server.http.routes": __plugin_implementation__.route_hook,
|
||||
|
||||
@@ -133,5 +133,5 @@ __plugin_disabling_discouraged__ = gettext(
|
||||
"setup steps that might be required after an update."
|
||||
)
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = CoreWizardPlugin()
|
||||
@@ -57,7 +57,7 @@ class DiscoveryPlugin(
|
||||
self.port = None
|
||||
|
||||
# zeroconf
|
||||
self._zeroconf = zeroconf.Zeroconf()
|
||||
self._zeroconf = None
|
||||
self._zeroconf_registrations = collections.defaultdict(list)
|
||||
|
||||
# upnp/ssdp
|
||||
@@ -66,6 +66,9 @@ class DiscoveryPlugin(
|
||||
self._ssdp_notify_timeout = 30
|
||||
self._ssdp_last_notify = 0
|
||||
|
||||
def initialize(self):
|
||||
self._zeroconf = zeroconf.Zeroconf(interfaces=self.get_interface_addresses())
|
||||
|
||||
##~~ SettingsPlugin API
|
||||
|
||||
def get_settings_defaults(self):
|
||||
@@ -87,7 +90,9 @@ class DiscoveryPlugin(
|
||||
"vendorUrl": None,
|
||||
},
|
||||
"addresses": None,
|
||||
"ignoredAddresses": None,
|
||||
"interfaces": None,
|
||||
"ignoredInterfaces": None,
|
||||
}
|
||||
|
||||
##~~ BlueprintPlugin API -- used for providing the SSDP device descriptor XML
|
||||
@@ -187,7 +192,7 @@ class DiscoveryPlugin(
|
||||
|
||||
def _format_zeroconf_name(self, name, service_type):
|
||||
service_type = self._format_zeroconf_service_type(service_type)
|
||||
return name + "." + service_type
|
||||
return f"{name}.{service_type}"
|
||||
|
||||
def _format_zeroconf_txt(self, record):
|
||||
result = {}
|
||||
@@ -779,8 +784,11 @@ class DiscoveryPlugin(
|
||||
if addresses:
|
||||
return addresses
|
||||
else:
|
||||
return octoprint.util.interface_addresses(
|
||||
interfaces=self._settings.get(["interfaces"])
|
||||
return list(
|
||||
octoprint.util.interface_addresses(
|
||||
interfaces=self._settings.get(["interfaces"]),
|
||||
ignored=self._settings.get(["ignoredInterfaces"]),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -795,4 +803,4 @@ __plugin_disabling_discouraged__ = gettext(
|
||||
"discoverable on the network via Bonjour and uPnP."
|
||||
)
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
@@ -18,10 +18,10 @@ from octoprint.util.version import (
|
||||
)
|
||||
|
||||
SENTRY_URL_SERVER = (
|
||||
"https://690e174698034bcc95928e6bfa8573f7@o118517.ingest.sentry.io/1373987"
|
||||
"https://871751d3af18492bbfe9db952cb1929c@o118517.ingest.sentry.io/1373987"
|
||||
)
|
||||
SENTRY_URL_COREUI = (
|
||||
"https://186f1dc5da7d46ab9d6b6de564d839bb@o118517.ingest.sentry.io/1374096"
|
||||
"https://1c7e28064b0646c3aa109793a49eea81@o118517.ingest.sentry.io/1374096"
|
||||
)
|
||||
|
||||
SETTINGS_DEFAULTS = {
|
||||
@@ -250,5 +250,5 @@ def __plugin_enable__():
|
||||
__plugin_name__ = "Error Tracking"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = ErrorTrackingPlugin()
|
||||
@@ -53,7 +53,7 @@ class EventManagerPlugin(
|
||||
|
||||
|
||||
__plugin_name__ = gettext("Event Manager")
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_author__ = "jneilliii"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_description__ = gettext(
|
||||
|
||||
@@ -56,6 +56,9 @@
|
||||
<input type="checkbox" data-bind="checked: debug" />
|
||||
</div>
|
||||
</div>
|
||||
<p><small>
|
||||
{{ _('Please note that any event handlers you define here will be processed <em>asynchronously</em> to OctoPrint\'s own processing of the event. You cannot stall, block or otherwise influence internal execution with event handlers.') }}
|
||||
</small></p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<div class="row-fluid">
|
||||
|
||||
@@ -75,7 +75,7 @@ __plugin_disabling_discouraged__ = gettext(
|
||||
"Without this plugin the GCode Viewer in OctoPrint will no longer be " "available."
|
||||
)
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = GcodeviewerPlugin()
|
||||
# __plugin_hooks__ = {
|
||||
# "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
|
||||
@@ -2,7 +2,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import os
|
||||
from os import scandir
|
||||
|
||||
from flask import abort, jsonify, request, url_for
|
||||
from flask_babel import gettext
|
||||
@@ -137,7 +136,7 @@ class LoggingPlugin(
|
||||
def _getLogFiles(self):
|
||||
files = []
|
||||
basedir = settings().getBaseFolder("logs", check_writable=False)
|
||||
for entry in scandir(basedir):
|
||||
for entry in os.scandir(basedir):
|
||||
if is_hidden_path(entry.path) or not entry.name.endswith(".log"):
|
||||
continue
|
||||
|
||||
@@ -274,7 +273,7 @@ __plugin_disabling_discouraged__ = gettext(
|
||||
"the web interface."
|
||||
)
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_implementation__ = LoggingPlugin()
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
|
||||
|
||||
@@ -12,10 +12,10 @@ import tempfile
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from os import scandir
|
||||
|
||||
import filetype
|
||||
import pkg_resources
|
||||
import pylru
|
||||
import requests
|
||||
import sarge
|
||||
from flask import Response, abort, jsonify, request
|
||||
@@ -23,7 +23,7 @@ from flask_babel import gettext
|
||||
|
||||
import octoprint.plugin
|
||||
import octoprint.plugin.core
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
from octoprint.access import ADMIN_GROUP, READONLY_GROUP, USER_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.events import Events
|
||||
from octoprint.server import safe_mode
|
||||
@@ -33,9 +33,15 @@ from octoprint.server.util.flask import (
|
||||
with_revalidation_checking,
|
||||
)
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.util import TemporaryDirectory, deprecated, to_bytes
|
||||
from octoprint.util import deprecated, to_bytes
|
||||
from octoprint.util.net import download_file
|
||||
from octoprint.util.pip import create_pip_caller
|
||||
from octoprint.util.pip import (
|
||||
OUTPUT_SUCCESS,
|
||||
create_pip_caller,
|
||||
get_result_line,
|
||||
is_already_installed,
|
||||
is_python_mismatch,
|
||||
)
|
||||
from octoprint.util.platform import get_os, is_os_compatible
|
||||
from octoprint.util.version import (
|
||||
get_octoprint_version,
|
||||
@@ -217,6 +223,13 @@ class PluginManagerPlugin(
|
||||
|
||||
def get_additional_permissions(self):
|
||||
return [
|
||||
{
|
||||
"key": "LIST",
|
||||
"name": "List plugins",
|
||||
"description": gettext("Allows to list installed plugins."),
|
||||
"default_groups": [READONLY_GROUP, USER_GROUP, ADMIN_GROUP],
|
||||
"roles": ["manage"],
|
||||
},
|
||||
{
|
||||
"key": "MANAGE",
|
||||
"name": "Manage plugins",
|
||||
@@ -488,6 +501,13 @@ class PluginManagerPlugin(
|
||||
unless=lambda: refresh,
|
||||
)(view)()
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/plugins/versions")
|
||||
@Permissions.PLUGIN_PLUGINMANAGER_LIST.require(403)
|
||||
def retrieve_plugin_list(self):
|
||||
return jsonify(
|
||||
{p["key"]: p["version"] for p in self._get_plugins() if p["enabled"]}
|
||||
)
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/plugins/<string:key>")
|
||||
@Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403)
|
||||
def retrieve_specific_plugin(self, key):
|
||||
@@ -746,7 +766,7 @@ class PluginManagerPlugin(
|
||||
|
||||
if url is not None:
|
||||
# fetch URL
|
||||
folder = TemporaryDirectory()
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
path = download_file(url, folder.name)
|
||||
source = url
|
||||
source_type = "url"
|
||||
@@ -863,10 +883,6 @@ class PluginManagerPlugin(
|
||||
path_url = "file://" + url_quote(path)
|
||||
shell_quote = sarge.shell_quote
|
||||
|
||||
already_installed_check = (
|
||||
lambda line: path_url in line.lower()
|
||||
) # lower case in case of windows
|
||||
|
||||
self._logger.info(f"Installing plugin from {source}")
|
||||
pip_args = [
|
||||
"--disable-pip-version-check",
|
||||
@@ -881,28 +897,9 @@ class PluginManagerPlugin(
|
||||
all_plugins_before = self._plugin_manager.find_plugins(existing={})
|
||||
|
||||
try:
|
||||
returncode, stdout, stderr = self._call_pip(pip_args)
|
||||
_, stdout, stderr = self._call_pip(pip_args)
|
||||
|
||||
# pip's output for a package that is already installed looks something like any of these:
|
||||
#
|
||||
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \
|
||||
# https://example.com/foobar.zip in <lib>
|
||||
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin in <lib>
|
||||
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \
|
||||
# file:///tmp/foobar.zip in <lib>
|
||||
# Requirement already satisfied (use --upgrade to upgrade): OctoPrint-Plugin==1.0 from \
|
||||
# file:///C:/Temp/foobar.zip in <lib>
|
||||
#
|
||||
# If we detect any of these matching what we just tried to install, we'll need to trigger a second
|
||||
# install with reinstall flags.
|
||||
|
||||
if not force and any(
|
||||
map(
|
||||
lambda x: x.strip().startswith(already_installed_string)
|
||||
and already_installed_check(x),
|
||||
stdout,
|
||||
)
|
||||
):
|
||||
if not force and is_already_installed(stdout):
|
||||
self._logger.info(
|
||||
"Plugin to be installed from {} was already installed, forcing a reinstall".format(
|
||||
source
|
||||
@@ -926,52 +923,34 @@ class PluginManagerPlugin(
|
||||
self._send_result_notification("install", result)
|
||||
return result
|
||||
|
||||
else:
|
||||
if force:
|
||||
# We don't use --upgrade here because that will also happily update all our dependencies - we'd rather
|
||||
# do that in a controlled manner
|
||||
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
||||
try:
|
||||
returncode, stdout, stderr = self._call_pip(pip_args)
|
||||
except Exception as e:
|
||||
self._logger.exception(f"Could not install plugin from {source}")
|
||||
self._logger.exception("Reason: {}".format(repr(e)))
|
||||
result = {
|
||||
"result": False,
|
||||
"source": source,
|
||||
"source_type": source_type,
|
||||
"reason": "Could not install plugin from source {}, see the log for more details".format(
|
||||
source
|
||||
),
|
||||
}
|
||||
self._send_result_notification("install", result)
|
||||
return result
|
||||
if is_python_mismatch(stderr):
|
||||
return self.handle_python_mismatch(source, source_type)
|
||||
|
||||
if any(map(lambda x: python_mismatch_string in x, stderr)):
|
||||
self._logger.error(
|
||||
"Installing the plugin from {} failed, pip reported a Python version mismatch".format(
|
||||
source
|
||||
)
|
||||
)
|
||||
result = {
|
||||
"result": False,
|
||||
"source": source,
|
||||
"source_type": source_type,
|
||||
"reason": "Pip reported a Python version mismatch",
|
||||
"faq": "https://faq.octoprint.org/plugin-python-mismatch",
|
||||
}
|
||||
self._send_result_notification("install", result)
|
||||
return result
|
||||
if force:
|
||||
# We don't use --upgrade here because that will also happily update all our dependencies - we'd rather
|
||||
# do that in a controlled manner
|
||||
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
||||
try:
|
||||
_, stdout, stderr = self._call_pip(pip_args)
|
||||
except Exception as e:
|
||||
self._logger.exception(f"Could not install plugin from {source}")
|
||||
self._logger.exception("Reason: {}".format(repr(e)))
|
||||
result = {
|
||||
"result": False,
|
||||
"source": source,
|
||||
"source_type": source_type,
|
||||
"reason": "Could not install plugin from source {}, see the log for more details".format(
|
||||
source
|
||||
),
|
||||
}
|
||||
self._send_result_notification("install", result)
|
||||
return result
|
||||
|
||||
try:
|
||||
result_line = list(
|
||||
filter(
|
||||
lambda x: x.startswith(success_string)
|
||||
or x.startswith(failure_string),
|
||||
stdout,
|
||||
)
|
||||
)[-1]
|
||||
except IndexError:
|
||||
if is_python_mismatch(stderr):
|
||||
return self.handle_python_mismatch(source, source_type)
|
||||
|
||||
result_line = get_result_line(stdout)
|
||||
if not result_line:
|
||||
self._logger.error(
|
||||
"Installing the plugin from {} failed, could not parse output from pip. "
|
||||
"See plugin_pluginmanager_console.log for generated output".format(source)
|
||||
@@ -986,16 +965,7 @@ class PluginManagerPlugin(
|
||||
self._send_result_notification("install", result)
|
||||
return result
|
||||
|
||||
# The final output of a pip install command looks something like this:
|
||||
#
|
||||
# Successfully installed OctoPrint-Plugin-1.0 Dependency-One-0.1 Dependency-Two-9.3
|
||||
#
|
||||
# or this:
|
||||
#
|
||||
# Successfully installed OctoPrint-Plugin Dependency-One Dependency-Two
|
||||
# Cleaning up...
|
||||
#
|
||||
# So we'll need to fetch the "Successfully installed" line, strip the "Successfully" part, then split
|
||||
# We'll need to fetch the "Successfully installed" line, strip the "Successfully" part, then split
|
||||
# by whitespace and strip to get all installed packages.
|
||||
#
|
||||
# We then need to iterate over all known plugins and see if either the package name or the package name plus
|
||||
@@ -1007,7 +977,7 @@ class PluginManagerPlugin(
|
||||
# so that it can report on more than one installed plugin.
|
||||
|
||||
result_line = result_line.strip()
|
||||
if not result_line.startswith(success_string):
|
||||
if not result_line.startswith(OUTPUT_SUCCESS):
|
||||
self._logger.error(
|
||||
"Installing the plugin from {} failed, pip did not report successful installation".format(
|
||||
source
|
||||
@@ -1023,7 +993,7 @@ class PluginManagerPlugin(
|
||||
return result
|
||||
|
||||
installed = list(
|
||||
map(lambda x: x.strip(), result_line[len(success_string) :].split(" "))
|
||||
map(lambda x: x.strip(), result_line[len(OUTPUT_SUCCESS) :].split(" "))
|
||||
)
|
||||
all_plugins_after = self._plugin_manager.find_plugins(
|
||||
existing={}, ignore_uninstalled=False
|
||||
@@ -1105,6 +1075,22 @@ class PluginManagerPlugin(
|
||||
self._send_result_notification("install", result)
|
||||
return result
|
||||
|
||||
def _handle_python_mismatch(self, source, source_type):
|
||||
self._logger.error(
|
||||
"Installing the plugin from {} failed, pip reported a Python version mismatch".format(
|
||||
source
|
||||
)
|
||||
)
|
||||
result = {
|
||||
"result": False,
|
||||
"source": source,
|
||||
"source_type": source_type,
|
||||
"reason": "Pip reported a Python version mismatch",
|
||||
"faq": "https://faq.octoprint.org/plugin-python-mismatch",
|
||||
}
|
||||
self._send_result_notification("install", result)
|
||||
return result
|
||||
|
||||
# noinspection DuplicatedCode
|
||||
def _command_install_pythonfile(self, path, source=None, source_type=None, name=None):
|
||||
if name is None:
|
||||
@@ -1929,7 +1915,7 @@ class PluginManagerPlugin(
|
||||
orphans[key]["settings"] = True
|
||||
|
||||
# data
|
||||
for entry in scandir(self._settings.getBaseFolder("data")):
|
||||
for entry in os.scandir(self._settings.getBaseFolder("data")):
|
||||
if not entry.is_dir():
|
||||
continue
|
||||
|
||||
@@ -2077,6 +2063,11 @@ class PluginManagerPlugin(
|
||||
}
|
||||
|
||||
|
||||
@pylru.lrudecorator(size=127)
|
||||
def parse_requirement(line):
|
||||
return pkg_resources.Requirement.parse(line)
|
||||
|
||||
|
||||
def _filter_relevant_notification(notification, plugin_version, octoprint_version):
|
||||
if "pluginversions" in notification:
|
||||
pluginversions = notification["pluginversions"]
|
||||
@@ -2084,7 +2075,7 @@ def _filter_relevant_notification(notification, plugin_version, octoprint_versio
|
||||
is_range = lambda x: "=" in x or ">" in x or "<" in x
|
||||
version_ranges = list(
|
||||
map(
|
||||
lambda x: pkg_resources.Requirement.parse(notification["plugin"] + x),
|
||||
lambda x: parse_requirement(notification["plugin"] + x),
|
||||
filter(is_range, pluginversions),
|
||||
)
|
||||
)
|
||||
@@ -2124,7 +2115,7 @@ __plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html"
|
||||
__plugin_description__ = "Allows installing and managing OctoPrint plugins"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
__plugin_hidden__ = True
|
||||
|
||||
|
||||
|
||||
@@ -104,7 +104,7 @@
|
||||
<h3>{{ _('Installed Plugins') }}</h3>
|
||||
|
||||
<div style="margin-bottom: 1em" class="clearfix">
|
||||
<input type="text" class="input-block search-query pull-left" data-bind="value: listingSearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}">
|
||||
<input type="text" class="input-block search-query pull-left" data-bind="value: listingSearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}" spellcheck="false">
|
||||
|
||||
<div class="pull-right">
|
||||
<div class="btn-group">
|
||||
@@ -235,7 +235,7 @@
|
||||
|
||||
<div style="margin-bottom: 1em" class="clearfix">
|
||||
<form class="form-search" data-bind="submit: performRepositorySearch">
|
||||
<input type="text" class="input-block search-query pull-left" data-bind="value: repositorySearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}">
|
||||
<input type="text" class="input-block search-query pull-left" data-bind="value: repositorySearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}" spellcheck="false">
|
||||
</form>
|
||||
<div class="dropdown pull-right">
|
||||
<div class="btn-group">
|
||||
|
||||
@@ -2054,7 +2054,12 @@ class SoftwareUpdatePlugin(
|
||||
raise exceptions.UnknownUpdateType()
|
||||
|
||||
update_result = updater.perform_update(
|
||||
target, populated_check, target_version, log_cb=self._log, online=online
|
||||
target,
|
||||
populated_check,
|
||||
target_version,
|
||||
log_cb=self._log,
|
||||
online=online,
|
||||
force=force,
|
||||
)
|
||||
target_result = ("success", update_result)
|
||||
self._logger.info(f"Update of {target} to {target_version} successful!")
|
||||
@@ -2413,7 +2418,7 @@ __plugin_disabling_discouraged__ = gettext(
|
||||
"your system at risk."
|
||||
)
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
|
||||
|
||||
def __plugin_load__():
|
||||
|
||||
@@ -51,7 +51,7 @@ def _to_unicode(s_or_u, encoding="utf-8", errors="strict"):
|
||||
|
||||
def _to_bytes(s_or_u, encoding="utf-8", errors="strict"):
|
||||
"""Make sure ``s_or_u`` is a str."""
|
||||
if isinstance(s_or_u, (str, bytes)):
|
||||
if isinstance(s_or_u, str):
|
||||
return s_or_u.encode(encoding, errors=errors)
|
||||
else:
|
||||
return s_or_u
|
||||
|
||||
@@ -130,14 +130,13 @@
|
||||
</tbody>
|
||||
</table>
|
||||
<small class="muted">
|
||||
<i class="far fa-bell"></i> = {{ _('Update notifications enabled') }},
|
||||
<i class="far fa-bell-slash"></i> = {{ _('Update notifications muted') }},
|
||||
{{ _('click to toggle') }}.
|
||||
{% trans %}
|
||||
"Update all" will update all items for which updates are availalbe &
|
||||
update notifications are enabled as well, "Update all available" will
|
||||
update all items for which updates are available regardless of update
|
||||
notifications being enabled or muted.
|
||||
{% trans enabled_icon="<i class=\"far fa-bell\"></i>", muted_icon="<i class=\"far fa-bell-slash\"></i>" %}
|
||||
{{ enabled_icon }} = Update notifications enabled, {{ muted_icon }} =
|
||||
Update notifications muted, click to toggle. "Update all" will update
|
||||
all items for which updates are available & update notifications are
|
||||
enabled as well, "Update all available" will update all items for
|
||||
which updates are available regardless of update notifications being
|
||||
enabled or muted.
|
||||
{% endtrans %}
|
||||
</small>
|
||||
</div>
|
||||
|
||||
@@ -7,9 +7,12 @@ import collections
|
||||
import logging
|
||||
import threading
|
||||
|
||||
import pkg_resources
|
||||
|
||||
from octoprint.util.pip import UnknownPip, create_pip_caller
|
||||
from octoprint.util.pip import (
|
||||
UnknownPip,
|
||||
create_pip_caller,
|
||||
is_already_installed,
|
||||
is_egg_problem,
|
||||
)
|
||||
from octoprint.util.version import get_comparable_version
|
||||
|
||||
from .. import exceptions
|
||||
@@ -19,13 +22,8 @@ console_logger = logging.getLogger(
|
||||
"octoprint.plugins.softwareupdate.updaters.pip.console"
|
||||
)
|
||||
|
||||
_ALREADY_INSTALLED = "Requirement already satisfied (use --upgrade to upgrade)"
|
||||
_POTENTIAL_EGG_PROBLEM_POSIX = "No such file or directory"
|
||||
_POTENTIAL_EGG_PROBLEM_WINDOWS = "The system cannot find the file specified"
|
||||
|
||||
_pip_callers = {}
|
||||
_pip_caller_mutex = collections.defaultdict(threading.RLock)
|
||||
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
|
||||
|
||||
|
||||
def can_perform_update(target, check, online=True):
|
||||
@@ -68,6 +66,8 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
|
||||
if not online and not check.get("offline", False):
|
||||
raise exceptions.CannotUpdateOffline()
|
||||
|
||||
force = force or check.get("force_reinstall", False)
|
||||
|
||||
pip_caller = _get_pip_caller(command=pip_command)
|
||||
if pip_caller is None:
|
||||
raise exceptions.UpdateError("Can't run pip", None)
|
||||
@@ -101,7 +101,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
|
||||
logger.debug(f"Target: {target}, executing pip install {install_arg}")
|
||||
pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"]
|
||||
pip_kwargs = {
|
||||
"env": {"PYTHONWARNINGS": b"ignore:DEPRECATION::pip._internal.cli.base_command"}
|
||||
"env": {"PYTHONWARNINGS": "ignore:DEPRECATION::pip._internal.cli.base_command"}
|
||||
}
|
||||
if pip_working_directory is not None:
|
||||
pip_kwargs.update(cwd=pip_working_directory)
|
||||
@@ -111,21 +111,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
|
||||
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
|
||||
if returncode != 0:
|
||||
# This could be caused by an issue with pip/setuptools: If something (target or dependency of target) was
|
||||
# installed as an egg at an earlier date (e.g. thanks to just running python setup.py install), pip install
|
||||
# will throw an error after updating that something to a newer (non-egg) version since it will still have
|
||||
# the egg on its sys.path and expect to read data from it. Running the exact same command a second time
|
||||
# solved this during hunt for a workaround, so this is what we'll now do if it indeed looks like this
|
||||
# specific problem
|
||||
def is_egg_problem(line):
|
||||
return (
|
||||
_POTENTIAL_EGG_PROBLEM_POSIX in line
|
||||
or _POTENTIAL_EGG_PROBLEM_WINDOWS in line
|
||||
) and ".egg" in line
|
||||
|
||||
if any(map(lambda x: is_egg_problem(x), stderr)) or any(
|
||||
map(lambda x: is_egg_problem(x), stdout)
|
||||
):
|
||||
if is_egg_problem(stdout) or is_egg_problem(stderr):
|
||||
_log_message(
|
||||
'This looks like an error caused by a specific issue in upgrading Python "eggs"',
|
||||
"via current versions of pip.",
|
||||
@@ -141,13 +127,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
|
||||
"Error while executing pip install", (stdout, stderr)
|
||||
)
|
||||
|
||||
if not force and any(
|
||||
map(
|
||||
lambda x: x.strip().startswith(_ALREADY_INSTALLED)
|
||||
and (install_arg in x or install_arg in x.lower()),
|
||||
stdout,
|
||||
)
|
||||
):
|
||||
if not force and is_already_installed(stdout):
|
||||
_log_message(
|
||||
"Looks like we were already installed in this version. Forcing a reinstall."
|
||||
)
|
||||
|
||||
@@ -12,24 +12,26 @@ def can_perform_update(target, check, online=True):
|
||||
)
|
||||
|
||||
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True, force=False):
|
||||
from ..exceptions import CannotUpdateOffline
|
||||
|
||||
if not online and not check("offline", False):
|
||||
raise CannotUpdateOffline()
|
||||
|
||||
kwargs = {"log_cb": log_cb, "online": online, "force": force}
|
||||
try:
|
||||
return check["python_updater"].perform_update(
|
||||
target, check, target_version, log_cb=log_cb, online=online
|
||||
target, check, target_version, **kwargs
|
||||
)
|
||||
except Exception:
|
||||
import inspect
|
||||
|
||||
args, _, _, _ = inspect.getargspec(check["python_updater"].perform_update)
|
||||
if "online" not in args:
|
||||
# old python_updater footprint, simply leave out the online parameter
|
||||
if not all(k in args for k in kwargs):
|
||||
# old python_updater footprint, leave out what it doesn't understand
|
||||
old_kwargs = {k: v for k, v in kwargs.items() if k in args}
|
||||
return check["python_updater"].perform_update(
|
||||
target, check, target_version, log_cb=log_cb
|
||||
target, check, target_version, **old_kwargs
|
||||
)
|
||||
|
||||
# some other error, raise again
|
||||
|
||||
@@ -5,9 +5,9 @@ import ast
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import TemporaryDirectory
|
||||
from octoprint.util.net import download_file
|
||||
|
||||
from .. import exceptions
|
||||
@@ -46,7 +46,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
|
||||
try:
|
||||
try:
|
||||
_log_message(f"Download file from {url}")
|
||||
folder = TemporaryDirectory()
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
path = download_file(url, folder.name)
|
||||
except Exception as exc:
|
||||
raise exceptions.NetworkError(cause=exc)
|
||||
|
||||
@@ -9,7 +9,7 @@ def can_perform_update(target, check, online=True):
|
||||
return True
|
||||
|
||||
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True, force=False):
|
||||
duration = check.get("duration", 30)
|
||||
|
||||
now = time.monotonic()
|
||||
|
||||
@@ -52,7 +52,7 @@ def can_perform_update(target, check, online=True):
|
||||
)
|
||||
|
||||
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
def perform_update(target, check, target_version, log_cb=None, online=True, force=False):
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.update_script")
|
||||
|
||||
if not online and not check("offline", False):
|
||||
|
||||
@@ -564,6 +564,6 @@ __plugin_description__ = (
|
||||
__plugin_url__ = "https://tracking.octoprint.org"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
|
||||
__plugin_implementation__ = TrackingPlugin()
|
||||
@@ -134,7 +134,7 @@ __plugin_homepage__ = (
|
||||
)
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_description__ = "Provides a virtual printer via a virtual serial port for development and testing purposes"
|
||||
__plugin_pythoncompat__ = ">=2.7,<4"
|
||||
__plugin_pythoncompat__ = ">=3.7,<4"
|
||||
|
||||
|
||||
def __plugin_load__():
|
||||
|
||||
@@ -10,7 +10,6 @@ import queue
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from os import scandir
|
||||
from typing import Any
|
||||
|
||||
from serial import SerialTimeoutException
|
||||
@@ -560,7 +559,7 @@ class VirtualPrinter:
|
||||
self._send(f"echo:T{t} Invalid extruder ")
|
||||
|
||||
# noinspection PyUnusedLocal
|
||||
def _gcode_F(self, code, data):
|
||||
def _gcode_F(self, code: str, data: str) -> bool:
|
||||
if self._supportF:
|
||||
self._send("echo:changed F value")
|
||||
return False
|
||||
@@ -677,8 +676,7 @@ class VirtualPrinter:
|
||||
self._busyInterval = interval
|
||||
|
||||
# noinspection PyUnusedLocal
|
||||
def _gcode_M114(self, data):
|
||||
# type: (str) -> bool
|
||||
def _gcode_M114(self, data: str) -> bool:
|
||||
output = self._generatePositionOutput()
|
||||
if not self._okBeforeCommandOutput:
|
||||
ok = self._ok()
|
||||
@@ -704,8 +702,7 @@ class VirtualPrinter:
|
||||
except AttributeError:
|
||||
self._send("echo:")
|
||||
|
||||
def _gcode_M154(self, data):
|
||||
# type: (str) -> None
|
||||
def _gcode_M154(self, data: str) -> None:
|
||||
matchS = re.search(r"S([0-9]+)", data)
|
||||
if matchS is not None:
|
||||
interval = int(matchS.group(1))
|
||||
@@ -720,8 +717,7 @@ class VirtualPrinter:
|
||||
else:
|
||||
self._pos_reporter = None
|
||||
|
||||
def _gcode_M155(self, data):
|
||||
# type: (str) -> None
|
||||
def _gcode_M155(self, data: str) -> None:
|
||||
matchS = re.search(r"S([0-9]+)", data)
|
||||
if matchS is not None:
|
||||
interval = int(matchS.group(1))
|
||||
@@ -751,7 +747,7 @@ class VirtualPrinter:
|
||||
self.buffered.join()
|
||||
|
||||
# noinspection PyUnusedLocal
|
||||
def _gcode_M600(self, data: str) -> bool:
|
||||
def _gcode_M600(self, data: str) -> None:
|
||||
self._send("//action:paused")
|
||||
self._showPrompt(
|
||||
"Heater Timeout",
|
||||
@@ -854,10 +850,10 @@ class VirtualPrinter:
|
||||
# Passcode Feature - lock with M510, unlock with M511 P<passcode>.
|
||||
# https://marlinfw.org/docs/gcode/M510.html / https://marlinfw.org/docs/gcode/M511.html
|
||||
|
||||
def _gcode_M510(self, data):
|
||||
def _gcode_M510(self, data: str) -> None:
|
||||
self._locked = True
|
||||
|
||||
def _gcode_M511(self, data):
|
||||
def _gcode_M511(self, data: str) -> None:
|
||||
if self._locked:
|
||||
matchP = re.search(r"P([0-9]+)", data)
|
||||
if matchP:
|
||||
@@ -869,14 +865,14 @@ class VirtualPrinter:
|
||||
|
||||
# EEPROM management commands
|
||||
|
||||
def _gcode_M500(self, data):
|
||||
def _gcode_M500(self, data: str) -> None:
|
||||
# Stores settings to disk
|
||||
if self._virtual_eeprom:
|
||||
self._virtual_eeprom.save_settings()
|
||||
else:
|
||||
self._send(self._error("command_unknown", "M500"))
|
||||
|
||||
def _gcode_M501(self, data):
|
||||
def _gcode_M501(self, data: str) -> None:
|
||||
# Read from EEPROM
|
||||
if self._virtual_eeprom:
|
||||
self._virtual_eeprom.read_settings()
|
||||
@@ -885,7 +881,7 @@ class VirtualPrinter:
|
||||
else:
|
||||
self._send(self._error("command_unknown", "M501"))
|
||||
|
||||
def _gcode_M502(self, data):
|
||||
def _gcode_M502(self, data: str) -> None:
|
||||
# reset to default values
|
||||
if self._virtual_eeprom:
|
||||
self._virtual_eeprom.load_defaults()
|
||||
@@ -894,7 +890,7 @@ class VirtualPrinter:
|
||||
else:
|
||||
self._send(self._error("command_unknown", "M502"))
|
||||
|
||||
def _gcode_M503(self, data):
|
||||
def _gcode_M503(self, data: str) -> None:
|
||||
# echo all eeprom data
|
||||
if self._virtual_eeprom and self._support_M503:
|
||||
for line in self._construct_eeprom_values():
|
||||
@@ -902,7 +898,7 @@ class VirtualPrinter:
|
||||
else:
|
||||
self._send(self._error("command_unknown", "M503"))
|
||||
|
||||
def _gcode_M504(self, data):
|
||||
def _gcode_M504(self, data: str) -> None:
|
||||
if self._virtual_eeprom:
|
||||
self._send("echo:EEPROM OK")
|
||||
else:
|
||||
@@ -910,7 +906,7 @@ class VirtualPrinter:
|
||||
|
||||
# EEPROM settings commands
|
||||
|
||||
def _gcode_M92(self, data):
|
||||
def _gcode_M92(self, data: str) -> None:
|
||||
# Steps per unit
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M92"))
|
||||
@@ -922,7 +918,7 @@ class VirtualPrinter:
|
||||
for key, value in self._parse_eeprom_params("XYZE", data).items():
|
||||
self._virtual_eeprom.eeprom["steps"]["params"][key] = float(value)
|
||||
|
||||
def _gcode_M203(self, data):
|
||||
def _gcode_M203(self, data: str) -> None:
|
||||
# Maximum feedrates (units/s)
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M203"))
|
||||
@@ -934,7 +930,7 @@ class VirtualPrinter:
|
||||
for key, value in self._parse_eeprom_params("XYZE", data).items():
|
||||
self._virtual_eeprom.eeprom["feedrate"]["params"][key] = float(value)
|
||||
|
||||
def _gcode_M201(self, data):
|
||||
def _gcode_M201(self, data: str) -> None:
|
||||
# Maximum Acceleration (units/s2)
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M201"))
|
||||
@@ -946,7 +942,7 @@ class VirtualPrinter:
|
||||
for key, value in self._parse_eeprom_params("EXYZ", data).items():
|
||||
self._virtual_eeprom.eeprom["max_accel"]["params"][key] = float(value)
|
||||
|
||||
def _gcode_M204(self, data):
|
||||
def _gcode_M204(self, data: str) -> None:
|
||||
# Starting Acceleration (units/s2)
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M204"))
|
||||
@@ -958,7 +954,7 @@ class VirtualPrinter:
|
||||
for key, value in self._parse_eeprom_params("PRTS", data).items():
|
||||
self._virtual_eeprom.eeprom["start_accel"]["params"][key] = float(value)
|
||||
|
||||
def _gcode_M206(self, data):
|
||||
def _gcode_M206(self, data: str) -> None:
|
||||
# Home offset
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M206"))
|
||||
@@ -970,7 +966,7 @@ class VirtualPrinter:
|
||||
for key, value in self._parse_eeprom_params("XYZ", data).items():
|
||||
self._virtual_eeprom.eeprom["home_offset"]["params"][key] = float(value)
|
||||
|
||||
def _gcode_M851(self, data):
|
||||
def _gcode_M851(self, data: str) -> None:
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M851"))
|
||||
return
|
||||
@@ -980,7 +976,7 @@ class VirtualPrinter:
|
||||
for key, value in self._parse_eeprom_params("XYZ", data).items():
|
||||
self._virtual_eeprom.eeprom["probe_offset"]["params"][key] = float(value)
|
||||
|
||||
def _gcode_M200(self, data):
|
||||
def _gcode_M200(self, data: str) -> None:
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M200"))
|
||||
return
|
||||
@@ -990,7 +986,7 @@ class VirtualPrinter:
|
||||
for key, value in self._parse_eeprom_params("DS", data).items():
|
||||
self._virtual_eeprom.eeprom["filament"]["params"][key] = float(value)
|
||||
|
||||
def _gcode_M666(self, data):
|
||||
def _gcode_M666(self, data: str) -> None:
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M666"))
|
||||
return
|
||||
@@ -1000,7 +996,7 @@ class VirtualPrinter:
|
||||
for key, value in self._parse_eeprom_params("XYZ", data).items():
|
||||
self._virtual_eeprom.eeprom["endstop"]["params"][key] = float(value)
|
||||
|
||||
def _gcode_M665(self, data):
|
||||
def _gcode_M665(self, data: str) -> None:
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M665"))
|
||||
return
|
||||
@@ -1010,7 +1006,7 @@ class VirtualPrinter:
|
||||
for key, value in self._parse_eeprom_params("BHLRSXYZ", data).items():
|
||||
self._virtual_eeprom.eeprom["delta"]["params"][key] = float(value)
|
||||
|
||||
def _gcode_M420(self, data):
|
||||
def _gcode_M420(self, data: str) -> None:
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M420"))
|
||||
return
|
||||
@@ -1020,7 +1016,7 @@ class VirtualPrinter:
|
||||
for key, value in self._parse_eeprom_params("SZ", data).items():
|
||||
self._virtual_eeprom.eeprom["auto_level"]["params"][key] = float(value)
|
||||
|
||||
def _gcode_M900(self, data):
|
||||
def _gcode_M900(self, data: str) -> None:
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M900"))
|
||||
return
|
||||
@@ -1032,7 +1028,7 @@ class VirtualPrinter:
|
||||
value
|
||||
)
|
||||
|
||||
def _gcode_M205(self, data):
|
||||
def _gcode_M205(self, data: str) -> None:
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M205"))
|
||||
return
|
||||
@@ -1042,7 +1038,7 @@ class VirtualPrinter:
|
||||
for key, value in self._parse_eeprom_params("BSTXYZEJ", data).items():
|
||||
self._virtual_eeprom.eeprom["advanced"]["params"][key] = float(value)
|
||||
|
||||
def _gcode_M145(self, data):
|
||||
def _gcode_M145(self, data: str) -> None:
|
||||
# M145 is a bit special, since it refers to 2 sets of values under the same params
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M145"))
|
||||
@@ -1069,7 +1065,7 @@ class VirtualPrinter:
|
||||
key
|
||||
] = float(value)
|
||||
|
||||
def _gcode_M301(self, data):
|
||||
def _gcode_M301(self, data: str) -> None:
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M301"))
|
||||
return
|
||||
@@ -1079,7 +1075,7 @@ class VirtualPrinter:
|
||||
for key, value in self._parse_eeprom_params("PID", data).items():
|
||||
self._virtual_eeprom.eeprom["pid"]["params"][key] = float(value)
|
||||
|
||||
def _gcode_M304(self, data):
|
||||
def _gcode_M304(self, data: str) -> None:
|
||||
if not self._virtual_eeprom:
|
||||
self._send(self._error("command_unknown", "M304"))
|
||||
return
|
||||
@@ -1118,7 +1114,7 @@ class VirtualPrinter:
|
||||
return lines
|
||||
|
||||
@staticmethod
|
||||
def _parse_eeprom_params(letters, line):
|
||||
def _parse_eeprom_params(letters: str, line: str) -> dict:
|
||||
# letters provided in a string (eg "XYZ") and line (eg. M92 X20 Y20 Z20)
|
||||
# are parsed into a dict
|
||||
params = list(letters)
|
||||
@@ -1408,10 +1404,9 @@ class VirtualPrinter:
|
||||
self._send(item)
|
||||
self._send("End file list")
|
||||
|
||||
def _mappedSdList(self):
|
||||
# type: () -> collections.OrderedDict
|
||||
def _mappedSdList(self) -> collections.OrderedDict:
|
||||
result = collections.OrderedDict()
|
||||
for entry in scandir(self._virtualSd):
|
||||
for entry in os.scandir(self._virtualSd):
|
||||
if not entry.is_file():
|
||||
continue
|
||||
dosname = get_dos_filename(
|
||||
@@ -1475,8 +1470,7 @@ class VirtualPrinter:
|
||||
else:
|
||||
self._send("Not SD printing")
|
||||
|
||||
def _generatePositionOutput(self):
|
||||
# type: () -> str
|
||||
def _generatePositionOutput(self) -> str:
|
||||
m114FormatString = self._settings.get(["m114FormatString"])
|
||||
e = {index: value for index, value in enumerate(self._lastE)}
|
||||
e["current"] = self._lastE[self.currentExtruder]
|
||||
@@ -1498,8 +1492,7 @@ class VirtualPrinter:
|
||||
)
|
||||
return output
|
||||
|
||||
def _generateTemperatureOutput(self):
|
||||
# type: () -> str
|
||||
def _generateTemperatureOutput(self) -> str:
|
||||
if self._settings.get_boolean(["repetierStyleTargetTemperature"]):
|
||||
template = self._settings.get(["m105NoTargetFormatString"])
|
||||
else:
|
||||
@@ -1589,8 +1582,7 @@ class VirtualPrinter:
|
||||
if self._settings.get_boolean(["repetierStyleTargetTemperature"]):
|
||||
self._send("TargetExtr%d:%d" % (tool, self.targetTemp[tool]))
|
||||
|
||||
def _parseBedCommand(self, line, wait=False, support_r=False):
|
||||
# type: (str, bool, bool) -> None
|
||||
def _parseBedCommand(self, line: str, wait: bool = False, support_r: bool = False):
|
||||
if not self._settings.get_boolean(["hasBed"]):
|
||||
return
|
||||
|
||||
@@ -1729,8 +1721,7 @@ class VirtualPrinter:
|
||||
else:
|
||||
time.sleep(duration)
|
||||
|
||||
def _setPosition(self, line):
|
||||
# type: (str) -> None
|
||||
def _setPosition(self, line: str) -> None:
|
||||
matchX = re.search(r"X(-?[0-9.]+)", line)
|
||||
matchY = re.search(r"Y(-?[0-9.]+)", line)
|
||||
matchZ = re.search(r"Z(-?[0-9.]+)", line)
|
||||
@@ -1869,8 +1860,7 @@ class VirtualPrinter:
|
||||
self._sdPrinting = False
|
||||
self._sdPrinter = None
|
||||
|
||||
def _waitForHeatup(self, heater, only_wait_if_higher):
|
||||
# type: (str, bool) -> None
|
||||
def _waitForHeatup(self, heater: str, only_wait_if_higher: bool) -> None:
|
||||
delta = 1
|
||||
delay = 1
|
||||
last_busy = time.monotonic()
|
||||
@@ -2006,7 +1996,7 @@ class VirtualPrinter:
|
||||
def _hidePrompt(self):
|
||||
self._send("//action:prompt_end")
|
||||
|
||||
def write(self, data: str) -> int:
|
||||
def write(self, data: bytes) -> int:
|
||||
data = to_bytes(data, errors="replace")
|
||||
u_data = to_unicode(data, errors="replace")
|
||||
|
||||
@@ -2095,8 +2085,7 @@ class VirtualPrinter:
|
||||
if self.outgoing is not None:
|
||||
self._send("wait")
|
||||
|
||||
def _send(self, line):
|
||||
# type: (str) -> None
|
||||
def _send(self, line: str) -> None:
|
||||
if self.outgoing is not None:
|
||||
self.outgoing.put(line)
|
||||
|
||||
|
||||
@@ -147,7 +147,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import copy
|
||||
import logging
|
||||
import os
|
||||
from os import scandir
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import (
|
||||
@@ -429,7 +428,7 @@ class PrinterProfileManager:
|
||||
dates = [os.stat(self._folder).st_mtime]
|
||||
dates += [
|
||||
entry.stat().st_mtime
|
||||
for entry in scandir(self._folder)
|
||||
for entry in os.scandir(self._folder)
|
||||
if entry.name.endswith(".profile")
|
||||
]
|
||||
return max(dates)
|
||||
@@ -491,7 +490,7 @@ class PrinterProfileManager:
|
||||
|
||||
def _load_all_identifiers(self):
|
||||
results = {}
|
||||
for entry in scandir(self._folder):
|
||||
for entry in os.scandir(self._folder):
|
||||
if is_hidden_path(entry.name) or not entry.name.endswith(".profile"):
|
||||
continue
|
||||
|
||||
|
||||
@@ -64,16 +64,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._targetTemp = None
|
||||
self._targetBedTemp = None
|
||||
self._targetChamberTemp = None
|
||||
|
||||
self._temps = TemperatureHistory(
|
||||
cutoff=settings().getInt(["temperature", "cutoff"]) * 60
|
||||
)
|
||||
self._tempBacklog = []
|
||||
|
||||
self._messages = deque([], 300)
|
||||
self._messageBacklog = []
|
||||
|
||||
self._log = deque([], 300)
|
||||
self._logBacklog = []
|
||||
|
||||
self._state = None
|
||||
|
||||
@@ -857,6 +853,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if "chamber" in offsets and offsets["chamber"] is not None
|
||||
else 0,
|
||||
}
|
||||
if self._custom is not None:
|
||||
for custom_key in self._custom.keys():
|
||||
result[custom_key] = {
|
||||
"actual": self._custom[custom_key][0],
|
||||
"target": self._custom[custom_key][1],
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
@@ -901,7 +903,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
def is_ready(self, *args, **kwargs):
|
||||
return (
|
||||
self.is_operational()
|
||||
and not self.is_printing()
|
||||
and not self._comm.isBusy()
|
||||
# isBusy is true when paused
|
||||
and not self._comm.isStreaming()
|
||||
)
|
||||
|
||||
|
||||
@@ -751,9 +751,10 @@ class Server:
|
||||
)
|
||||
}
|
||||
|
||||
valid_timelapse = lambda path: not octoprint.util.is_hidden_path(
|
||||
path
|
||||
) and octoprint.timelapse.valid_timelapse(path)
|
||||
valid_timelapse = lambda path: not octoprint.util.is_hidden_path(path) and (
|
||||
octoprint.timelapse.valid_timelapse(path)
|
||||
or octoprint.timelapse.valid_timelapse_thumbnail(path)
|
||||
)
|
||||
timelapse_path_validator = {
|
||||
"path_validation": util.tornado.path_validation_factory(
|
||||
valid_timelapse,
|
||||
@@ -1558,18 +1559,10 @@ class Server:
|
||||
|
||||
loaders = [app.jinja_loader, app.jinja_env.prefix_loader]
|
||||
if octoprint.util.is_running_from_source():
|
||||
from markdown import markdown
|
||||
|
||||
root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
|
||||
allowed = ["AUTHORS.md", "SUPPORTERS.md", "THIRDPARTYLICENSES.md"]
|
||||
files = {
|
||||
"_data/" + name + ".html": os.path.join(root, name) for name in allowed
|
||||
}
|
||||
loaders.append(
|
||||
octoprint.util.jinja.SelectedFilesWithConversionLoader(
|
||||
files, conversion=markdown
|
||||
)
|
||||
)
|
||||
files = {"_data/" + name: os.path.join(root, name) for name in allowed}
|
||||
loaders.append(octoprint.util.jinja.SelectedFilesWithConversionLoader(files))
|
||||
|
||||
# TODO: Remove this in 2.0.0
|
||||
warning_message = "Loading plugin template '{template}' from '{filename}' without plugin prefix, this is deprecated and will soon no longer be supported."
|
||||
@@ -1781,9 +1774,7 @@ class Server:
|
||||
|
||||
blueprints = [api]
|
||||
api_endpoints = ["/api"]
|
||||
registrators = [
|
||||
functools.partial(app.register_blueprint, api, url_prefix="/api"),
|
||||
]
|
||||
registrators = [functools.partial(app.register_blueprint, api, url_prefix="/api")]
|
||||
|
||||
# also register any blueprints defined in BlueprintPlugins
|
||||
(
|
||||
@@ -1796,10 +1787,7 @@ class Server:
|
||||
registrators += registrators_from_plugins
|
||||
|
||||
# and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves
|
||||
(
|
||||
blueprints_from_assets,
|
||||
registrators_from_assets,
|
||||
) = self._prepare_asset_plugins()
|
||||
(blueprints_from_assets, registrators_from_assets) = self._prepare_asset_plugins()
|
||||
blueprints += blueprints_from_assets
|
||||
registrators += registrators_from_assets
|
||||
|
||||
@@ -1979,7 +1967,6 @@ class Server:
|
||||
global assets
|
||||
global pluginManager
|
||||
|
||||
util.flask.fix_webassets_cache()
|
||||
util.flask.fix_webassets_filtertool()
|
||||
|
||||
base_folder = self._settings.getBaseFolder("generated")
|
||||
@@ -1989,14 +1976,21 @@ class Server:
|
||||
import errno
|
||||
import shutil
|
||||
|
||||
for entry in ("webassets", ".webassets-cache"):
|
||||
for entry, recreate in (
|
||||
("webassets", True),
|
||||
(".webassets-cache", False), # no longer used, but clean up just in case
|
||||
(".webassets-manifest.json", False),
|
||||
):
|
||||
path = os.path.join(base_folder, entry)
|
||||
|
||||
# delete path if it exists
|
||||
if os.path.isdir(path):
|
||||
if os.path.exists(path):
|
||||
try:
|
||||
self._logger.debug("Deleting {path}...".format(**locals()))
|
||||
shutil.rmtree(path)
|
||||
if os.path.isdir(path):
|
||||
shutil.rmtree(path)
|
||||
else:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while trying to delete {path}, "
|
||||
@@ -2004,52 +1998,53 @@ class Server:
|
||||
)
|
||||
continue
|
||||
|
||||
# re-create path
|
||||
self._logger.debug("Creating {path}...".format(**locals()))
|
||||
error_text = (
|
||||
"Error while trying to re-create {path}, that might cause "
|
||||
"errors with the webassets cache".format(**locals())
|
||||
)
|
||||
try:
|
||||
os.makedirs(path)
|
||||
except OSError as e:
|
||||
if e.errno == errno.EACCES:
|
||||
# that might be caused by the user still having the folder open somewhere, let's try again after
|
||||
# waiting a bit
|
||||
import time
|
||||
# re-create path if necessary
|
||||
if recreate:
|
||||
self._logger.debug("Creating {path}...".format(**locals()))
|
||||
error_text = (
|
||||
"Error while trying to re-create {path}, that might cause "
|
||||
"errors with the webassets cache".format(**locals())
|
||||
)
|
||||
try:
|
||||
os.makedirs(path)
|
||||
except OSError as e:
|
||||
if e.errno == errno.EACCES:
|
||||
# that might be caused by the user still having the folder open somewhere, let's try again after
|
||||
# waiting a bit
|
||||
import time
|
||||
|
||||
for n in range(3):
|
||||
time.sleep(0.5)
|
||||
self._logger.debug(
|
||||
"Creating {path}: Retry #{retry} after {time}s".format(
|
||||
path=path, retry=n + 1, time=(n + 1) * 0.5
|
||||
)
|
||||
)
|
||||
try:
|
||||
os.makedirs(path)
|
||||
break
|
||||
except Exception:
|
||||
if self._logger.isEnabledFor(logging.DEBUG):
|
||||
self._logger.exception(
|
||||
"Ignored error while creating "
|
||||
"directory {path}".format(**locals())
|
||||
for n in range(3):
|
||||
time.sleep(0.5)
|
||||
self._logger.debug(
|
||||
"Creating {path}: Retry #{retry} after {time}s".format(
|
||||
path=path, retry=n + 1, time=(n + 1) * 0.5
|
||||
)
|
||||
pass
|
||||
)
|
||||
try:
|
||||
os.makedirs(path)
|
||||
break
|
||||
except Exception:
|
||||
if self._logger.isEnabledFor(logging.DEBUG):
|
||||
self._logger.exception(
|
||||
"Ignored error while creating "
|
||||
"directory {path}".format(**locals())
|
||||
)
|
||||
pass
|
||||
else:
|
||||
# this will only get executed if we never did
|
||||
# successfully execute makedirs above
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
else:
|
||||
# this will only get executed if we never did
|
||||
# successfully execute makedirs above
|
||||
# not an access error, so something we don't understand
|
||||
# went wrong -> log an error and stop
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
else:
|
||||
# not an access error, so something we don't understand
|
||||
except Exception:
|
||||
# not an OSError, so something we don't understand
|
||||
# went wrong -> log an error and stop
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
except Exception:
|
||||
# not an OSError, so something we don't understand
|
||||
# went wrong -> log an error and stop
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
|
||||
self._logger.info("Reset webasset folder {path}...".format(**locals()))
|
||||
|
||||
@@ -2067,6 +2062,12 @@ class Server:
|
||||
assets = CustomDirectoryEnvironment(app)
|
||||
assets.debug = not self._settings.getBoolean(["devel", "webassets", "bundle"])
|
||||
|
||||
# we should rarely if ever regenerate the webassets in production and can wait a
|
||||
# few seconds for regeneration in development, if it means we can get rid of
|
||||
# a whole monkey patch and in internal use of pickle with non-tamperproof files
|
||||
assets.cache = False
|
||||
assets.manifest = "json:.webassets-manifest.json"
|
||||
|
||||
UpdaterType = type(util.flask.SettingsCheckUpdater)(
|
||||
util.flask.SettingsCheckUpdater.__name__,
|
||||
(util.flask.SettingsCheckUpdater,),
|
||||
|
||||
@@ -6,6 +6,7 @@ import hashlib
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from urllib.parse import quote as urlquote
|
||||
|
||||
import psutil
|
||||
from flask import abort, jsonify, make_response, request, url_for
|
||||
@@ -34,11 +35,6 @@ from octoprint.server.util.flask import (
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.util import sv, time_this
|
||||
|
||||
try:
|
||||
from urllib.parse import quote as urlquote
|
||||
except ImportError:
|
||||
from urllib import quote as urlquote # noqa: F401
|
||||
|
||||
# ~~ GCODE file handling
|
||||
|
||||
_file_cache = {}
|
||||
@@ -207,7 +203,7 @@ def runFilesTest():
|
||||
),
|
||||
):
|
||||
counter += 1
|
||||
suggestion = name + f"_{counter}" + ext
|
||||
suggestion = f"{name}_{counter}{ext}"
|
||||
return jsonify(exists=True, suggestion=suggestion)
|
||||
else:
|
||||
return jsonify(exists=False)
|
||||
@@ -521,23 +517,13 @@ def uploadGcodeFile(target):
|
||||
except Exception:
|
||||
abort(400, description="userdata contains invalid JSON")
|
||||
|
||||
# check preconditions for SD upload
|
||||
if target == FileDestinations.SDCARD and not settings().getBoolean(
|
||||
["feature", "sdSupport"]
|
||||
):
|
||||
abort(404)
|
||||
|
||||
sd = target == FileDestinations.SDCARD
|
||||
selectAfterUpload = (
|
||||
"select" in request.values
|
||||
and request.values["select"] in valid_boolean_trues
|
||||
and Permissions.FILES_SELECT.can()
|
||||
)
|
||||
printAfterSelect = (
|
||||
"print" in request.values
|
||||
and request.values["print"] in valid_boolean_trues
|
||||
and Permissions.PRINT.can()
|
||||
)
|
||||
|
||||
if sd:
|
||||
# validate that all preconditions for SD upload are met before attempting it
|
||||
if not (
|
||||
@@ -551,6 +537,33 @@ def uploadGcodeFile(target):
|
||||
if not printer.is_sd_ready():
|
||||
abort(409, description="Can not upload to SD card, not yet initialized")
|
||||
|
||||
# evaluate select and print parameter and if set check permissions & preconditions
|
||||
# and adjust as necessary
|
||||
#
|
||||
# we do NOT abort(409) here since this would be a backwards incompatible behaviour change
|
||||
# on the API, but instead return the actually effective select and print flags in the response
|
||||
#
|
||||
# note that this behaviour might change in a future API version
|
||||
select_request = (
|
||||
"select" in request.values
|
||||
and request.values["select"] in valid_boolean_trues
|
||||
and Permissions.FILES_SELECT.can()
|
||||
)
|
||||
print_request = (
|
||||
"print" in request.values
|
||||
and request.values["print"] in valid_boolean_trues
|
||||
and Permissions.PRINT.can()
|
||||
)
|
||||
|
||||
to_select = select_request
|
||||
to_print = print_request
|
||||
if (to_select or to_print) and not (
|
||||
printer.is_operational()
|
||||
and not (printer.is_printing() or printer.is_paused())
|
||||
):
|
||||
# can't select or print files if not operational or ready
|
||||
to_select = to_print = False
|
||||
|
||||
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||
try:
|
||||
# FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet
|
||||
@@ -572,7 +585,7 @@ def uploadGcodeFile(target):
|
||||
futureFilename = None
|
||||
|
||||
if futureFilename is None:
|
||||
abort(415, description="Can not upload file, wrong format?")
|
||||
abort(400, description="Can not upload file, invalid file name")
|
||||
|
||||
# prohibit overwriting currently selected file while it's being printed
|
||||
futureFullPath = fileManager.join_path(
|
||||
@@ -603,7 +616,7 @@ def uploadGcodeFile(target):
|
||||
Callback for when the file processing (upload, optional slicing, addition to analysis queue) has
|
||||
finished.
|
||||
|
||||
Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint.
|
||||
Depending on the file's destination triggers either streaming to SD card or directly calls to_select.
|
||||
"""
|
||||
|
||||
if (
|
||||
@@ -626,16 +639,16 @@ def uploadGcodeFile(target):
|
||||
the case after they have finished streaming to the printer, which is why this callback is also used
|
||||
for the corresponding call to addSdFile.
|
||||
|
||||
Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the
|
||||
Selects the just uploaded file if either to_select or to_print are True, or if the
|
||||
exact file is already selected, such reloading it.
|
||||
"""
|
||||
if octoprint.filemanager.valid_file_type(added_file, "gcode") and (
|
||||
selectAfterUpload or printAfterSelect or reselect
|
||||
to_select or to_print or reselect
|
||||
):
|
||||
printer.select_file(
|
||||
absFilename,
|
||||
destination == FileDestinations.SDCARD,
|
||||
printAfterSelect,
|
||||
to_print,
|
||||
user,
|
||||
)
|
||||
|
||||
@@ -649,13 +662,9 @@ def uploadGcodeFile(target):
|
||||
)
|
||||
except octoprint.filemanager.storage.StorageError as e:
|
||||
if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE:
|
||||
abort(400, description="Could not upload file, invalid type")
|
||||
abort(415, description="Could not upload file, invalid type")
|
||||
else:
|
||||
abort(500, description="Could not upload file")
|
||||
|
||||
if octoprint.filemanager.valid_file_type(added_file, "stl"):
|
||||
filename = added_file
|
||||
done = True
|
||||
else:
|
||||
filename = fileProcessingFinished(
|
||||
added_file,
|
||||
@@ -678,8 +687,10 @@ def uploadGcodeFile(target):
|
||||
"name": futureFilename,
|
||||
"path": filename,
|
||||
"target": target,
|
||||
"select": selectAfterUpload,
|
||||
"print": printAfterSelect,
|
||||
"select": select_request,
|
||||
"print": print_request,
|
||||
"effective_select": to_select,
|
||||
"effective_print": to_print,
|
||||
}
|
||||
if userdata is not None:
|
||||
payload["userdata"] = userdata
|
||||
@@ -728,7 +739,15 @@ def uploadGcodeFile(target):
|
||||
}
|
||||
)
|
||||
|
||||
r = make_response(jsonify(files=files, done=done), 201)
|
||||
r = make_response(
|
||||
jsonify(
|
||||
files=files,
|
||||
done=done,
|
||||
effectiveSelect=to_select,
|
||||
effectivePrint=to_print,
|
||||
),
|
||||
201,
|
||||
)
|
||||
r.headers["Location"] = location
|
||||
return r
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import os
|
||||
import tarfile
|
||||
import zipfile
|
||||
from collections import defaultdict
|
||||
from os import scandir
|
||||
|
||||
from flask import abort, jsonify, request
|
||||
from flask_babel import Locale
|
||||
@@ -32,7 +31,7 @@ def getInstalledLanguagePacks():
|
||||
plugin_packs = defaultdict(
|
||||
lambda: {"identifier": None, "display": None, "languages": []}
|
||||
)
|
||||
for entry in scandir(translation_folder):
|
||||
for entry in os.scandir(translation_folder):
|
||||
if not entry.is_dir():
|
||||
continue
|
||||
|
||||
@@ -63,7 +62,7 @@ def getInstalledLanguagePacks():
|
||||
return meta
|
||||
|
||||
if entry.name == "_plugins":
|
||||
for plugin_entry in scandir(entry.path):
|
||||
for plugin_entry in os.scandir(entry.path):
|
||||
if not plugin_entry.is_dir():
|
||||
continue
|
||||
|
||||
@@ -75,7 +74,7 @@ def getInstalledLanguagePacks():
|
||||
plugin_packs[plugin_entry.name]["identifier"] = plugin_entry.name
|
||||
plugin_packs[plugin_entry.name]["display"] = plugin_info.name
|
||||
|
||||
for language_entry in scandir(plugin_entry.path):
|
||||
for language_entry in os.scandir(plugin_entry.path):
|
||||
try:
|
||||
plugin_packs[plugin_entry.name]["languages"].append(
|
||||
load_meta(language_entry.path, language_entry.name)
|
||||
|
||||
@@ -260,6 +260,7 @@ def getSettings():
|
||||
"resendRatioThreshold": s.getInt(["serial", "resendRatioThreshold"]),
|
||||
"resendRatioStart": s.getInt(["serial", "resendRatioStart"]),
|
||||
"ignoreEmptyPorts": s.getBoolean(["serial", "ignoreEmptyPorts"]),
|
||||
"encoding": s.get(["serial", "encoding"]),
|
||||
},
|
||||
"folder": {
|
||||
"uploads": s.getBaseFolder("uploads"),
|
||||
@@ -947,6 +948,9 @@ def _saveSettings(data):
|
||||
["serial", "ignoreEmptyPorts"], data["serial"]["ignoreEmptyPorts"]
|
||||
)
|
||||
|
||||
if "encoding" in data["serial"]:
|
||||
s.set(["serial", "encoding"], data["serial"]["encoding"])
|
||||
|
||||
oldLog = s.getBoolean(["serial", "log"])
|
||||
if "log" in data["serial"]:
|
||||
s.setBoolean(["serial", "log"], data["serial"]["log"])
|
||||
|
||||
@@ -5,6 +5,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from urllib.parse import quote as urlquote
|
||||
|
||||
from flask import abort, jsonify, request, url_for
|
||||
|
||||
@@ -21,11 +22,6 @@ from octoprint.server.util.flask import (
|
||||
)
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
|
||||
try:
|
||||
from urllib.parse import quote as urlquote
|
||||
except ImportError:
|
||||
from urllib import quote as urlquote # noqa: F401
|
||||
|
||||
_DATA_FORMAT_VERSION = "v2"
|
||||
|
||||
# ~~ timelapse handling
|
||||
@@ -143,6 +139,13 @@ def getTimelapseData():
|
||||
for f in files:
|
||||
output = dict(f)
|
||||
output["url"] = url_for("index") + "downloads/timelapse/" + urlquote(f["name"])
|
||||
if output["thumbnail"] is not None:
|
||||
output["thumbnail"] = (
|
||||
url_for("index") + "downloads/timelapse/" + urlquote(f["thumbnail"])
|
||||
)
|
||||
else:
|
||||
output.pop("thumbnail", None)
|
||||
|
||||
finished_list.append(output)
|
||||
|
||||
result = {
|
||||
@@ -172,6 +175,7 @@ def downloadTimelapse(filename):
|
||||
def deleteTimelapse(filename):
|
||||
timelapse_folder = settings().getBaseFolder("timelapse")
|
||||
full_path = os.path.realpath(os.path.join(timelapse_folder, filename))
|
||||
thumb_path = octoprint.timelapse.create_thumbnail_path(full_path)
|
||||
if (
|
||||
octoprint.timelapse.valid_timelapse(full_path)
|
||||
and full_path.startswith(timelapse_folder)
|
||||
@@ -186,6 +190,20 @@ def deleteTimelapse(filename):
|
||||
)
|
||||
abort(500, description=f"Unexpected error: {ex}")
|
||||
|
||||
if (
|
||||
octoprint.timelapse.valid_timelapse_thumbnail(thumb_path)
|
||||
and thumb_path.startswith(timelapse_folder)
|
||||
and os.path.exists(thumb_path)
|
||||
and not util.is_hidden_path(thumb_path)
|
||||
):
|
||||
try:
|
||||
os.remove(thumb_path)
|
||||
except Exception as ex:
|
||||
# Do not treat this as an error, log and ignore
|
||||
logging.getLogger(__file__).warning(
|
||||
f"Unable to delete thumbnail {thumb_path} ({ex})"
|
||||
)
|
||||
|
||||
return getTimelapseData()
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import base64
|
||||
import logging
|
||||
import sys
|
||||
|
||||
PY3 = sys.version_info[0] == 3 # keeping this for backwards compatibility
|
||||
PY3 = sys.version_info[0] == 3 # should now always be true, kept for plugins
|
||||
|
||||
import flask as _flask
|
||||
import flask_login
|
||||
|
||||
@@ -9,7 +9,6 @@ import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from os import scandir
|
||||
|
||||
import flask
|
||||
import flask.json
|
||||
@@ -60,11 +59,11 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
|
||||
if not os.path.isdir(dirname):
|
||||
return []
|
||||
result = []
|
||||
for entry in scandir(dirname):
|
||||
for entry in os.scandir(dirname):
|
||||
locale_dir = os.path.join(entry.path, "LC_MESSAGES")
|
||||
if not os.path.isdir(locale_dir):
|
||||
continue
|
||||
if any(filter(lambda x: x.name.endswith(".mo"), scandir(locale_dir))):
|
||||
if any(filter(lambda x: x.name.endswith(".mo"), os.scandir(locale_dir))):
|
||||
result.append(Locale.parse(entry.name))
|
||||
return result
|
||||
|
||||
@@ -161,81 +160,6 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
|
||||
flask_babel.get_translations = fixed_get_translations
|
||||
|
||||
|
||||
def fix_webassets_cache():
|
||||
from webassets import cache
|
||||
|
||||
error_logger = logging.getLogger(__name__ + ".fix_webassets_cache")
|
||||
|
||||
def fixed_set(self, key, data):
|
||||
import os
|
||||
import pickle
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
if not os.path.exists(self.directory):
|
||||
error_logger.warning(
|
||||
"Cache directory {} doesn't exist, not going "
|
||||
"to attempt to write cache file".format(self.directory)
|
||||
)
|
||||
|
||||
md5 = "%s" % cache.make_md5(self.V, key)
|
||||
filename = os.path.join(self.directory, md5)
|
||||
fd, temp_filename = tempfile.mkstemp(prefix="." + md5, dir=self.directory)
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as f:
|
||||
pickle.dump(data, f)
|
||||
f.flush()
|
||||
shutil.move(temp_filename, filename)
|
||||
except Exception:
|
||||
os.remove(temp_filename)
|
||||
raise
|
||||
|
||||
def fixed_get(self, key):
|
||||
import errno
|
||||
import os
|
||||
import warnings
|
||||
|
||||
from webassets.cache import make_md5
|
||||
|
||||
if not os.path.exists(self.directory):
|
||||
error_logger.warning(
|
||||
"Cache directory {} doesn't exist, not going "
|
||||
"to attempt to read cache file".format(self.directory)
|
||||
)
|
||||
return None
|
||||
|
||||
try:
|
||||
hash = make_md5(self.V, key)
|
||||
except OSError as e:
|
||||
if e.errno != errno.ENOENT:
|
||||
raise
|
||||
return None
|
||||
|
||||
filename = os.path.join(self.directory, "%s" % hash)
|
||||
try:
|
||||
f = open(filename, "rb")
|
||||
except OSError as e:
|
||||
if e.errno != errno.ENOENT:
|
||||
error_logger.exception(
|
||||
"Got an exception while trying to open webasset file {}".format(
|
||||
filename
|
||||
)
|
||||
)
|
||||
return None
|
||||
try:
|
||||
result = f.read()
|
||||
finally:
|
||||
f.close()
|
||||
|
||||
unpickled = webassets.cache.safe_unpickle(result)
|
||||
if unpickled is None:
|
||||
warnings.warn("Ignoring corrupted cache file %s" % filename)
|
||||
return unpickled
|
||||
|
||||
cache.FilesystemCache.set = fixed_set
|
||||
cache.FilesystemCache.get = fixed_get
|
||||
|
||||
|
||||
def fix_webassets_filtertool():
|
||||
from webassets.merge import FilterTool, MemoryHunk, log
|
||||
|
||||
|
||||
@@ -37,11 +37,9 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
self._watched_folder = None
|
||||
|
||||
def initial_scan(self, folder):
|
||||
from os import scandir
|
||||
|
||||
def _recursive_scandir(path):
|
||||
"""Recursively yield DirEntry objects for given directory."""
|
||||
for entry in scandir(path):
|
||||
for entry in os.scandir(path):
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
yield from _recursive_scandir(entry.path)
|
||||
else:
|
||||
|
||||
@@ -167,6 +167,7 @@ default_settings = {
|
||||
"resendRatioThreshold": 10,
|
||||
"resendRatioStart": 100,
|
||||
"ignoreEmptyPorts": False,
|
||||
"encoding": "ascii",
|
||||
# command specific flags
|
||||
"triggerOkForM29": True,
|
||||
},
|
||||
@@ -244,7 +245,8 @@ default_settings = {
|
||||
"flipH": False,
|
||||
"flipV": False,
|
||||
"rotate90": False,
|
||||
"ffmpegCommandline": '{ffmpeg} -r {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b:v {bitrate} -f {containerformat} -y {filters} "{output}"',
|
||||
"ffmpegCommandline": '{ffmpeg} -framerate {fps} -i "{input}" -vcodec {videocodec} -threads {threads} -b:v {bitrate} -f {containerformat} -y {filters} "{output}"',
|
||||
"ffmpegThumbnailCommandline": '{ffmpeg} -sseof -1 -i "{input}" -update 1 -q:v 0.7 "{output}"',
|
||||
"timelapse": {
|
||||
"type": "off",
|
||||
"options": {},
|
||||
|
||||
@@ -1 +1 @@
|
||||
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .checkbox,.form-signin .form-signin-heading{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}
|
||||
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .checkbox,.form-signin .form-signin-heading{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}#noscript{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#fff;z-index:12310}#noscript .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#noscript .wrapper .outer{display:table;width:100%;height:100%}#noscript .wrapper .outer .inner{display:table-cell;vertical-align:middle}#noscript .wrapper .outer .inner .content{text-align:center}
|
||||
@@ -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
|
||||
@@ -0,0 +1,5 @@
|
||||
<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<circle cx="20" cy="20" r="20" fill="#A8A8A8" fill-opacity="0.6"/>
|
||||
<circle cx="20" cy="20" r="19.75" stroke="#A8A8A8" stroke-opacity="0.6" stroke-width="0.5"/>
|
||||
<path d="M31.25 20.9375L14.8437 30.4097L14.8437 11.4653L31.25 20.9375Z" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 350 B |
@@ -18,7 +18,6 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
self._lastProcessingTimesSize = 20;
|
||||
|
||||
self._safeModePopup = undefined;
|
||||
self._python2Popup = undefined;
|
||||
|
||||
self.increaseThrottle = function () {
|
||||
self.setThrottle(self._throttleFactor + 1);
|
||||
@@ -234,22 +233,6 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
});
|
||||
}
|
||||
|
||||
// process python version
|
||||
if (self._python2Popup) self._python2Popup.remove();
|
||||
if (PYTHON_VERSION && PYTHON_VERSION.startsWith("2.")) {
|
||||
self._python2Popup = new PNotify({
|
||||
title: gettext("You are still running Python 2"),
|
||||
text: _.sprintf(
|
||||
gettext(
|
||||
"<p>Python 2 is end-of-life as of January 1st 2020. While OctoPrint currently still supports running under Python 2, a future version will remove support and require Python 3. You should upgrade as soon as possible!</p><p>Please refer to the FAQ for recommended update workflows:</p>"
|
||||
) +
|
||||
"<p><a href='https://faq.octoprint.org/python3-update' target='_blank' rel='noopener noreferer'>How to migrate to Python 3</a></p>",
|
||||
{reason: _.escape(reason)}
|
||||
),
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
|
||||
// if the offline overlay is still showing, now's a good time to
|
||||
// hide it, plus reload the camera feed if it's currently displayed
|
||||
if ($("#offline_overlay").is(":visible")) {
|
||||
|
||||
@@ -43,7 +43,10 @@ $(function () {
|
||||
self.webcamHlsEnabled = ko.observable(false);
|
||||
self.webcamWebRTCEnabled = ko.observable(false);
|
||||
self.webcamError = ko.observable(false);
|
||||
self.webcamMuted = ko.observable(true);
|
||||
self.webRTCPeerConnection = null;
|
||||
self.webcamElementHls = null;
|
||||
self.webcamElementWebrtc = null;
|
||||
|
||||
self.keycontrolActive = ko.observable(false);
|
||||
self.keycontrolHelpActive = ko.observable(false);
|
||||
@@ -68,6 +71,15 @@ $(function () {
|
||||
}
|
||||
});
|
||||
|
||||
// Subscribe to rotation event to ensure we update calculations.
|
||||
// We need to wait for the CSS to be updated by KO, thus we use a timeout to
|
||||
// ensure our calculations run after the CSS was updated
|
||||
self.settings.webcam_rotate90.subscribe(function () {
|
||||
window.setTimeout(function () {
|
||||
self._updateVideoTagWebcamLayout();
|
||||
}, 1);
|
||||
});
|
||||
|
||||
self.settings.printerProfiles.currentProfileData.subscribe(function () {
|
||||
self._updateExtruderCount();
|
||||
self.settings.printerProfiles
|
||||
@@ -116,7 +128,8 @@ $(function () {
|
||||
};
|
||||
|
||||
self.onEventSettingsUpdated = function (payload) {
|
||||
// the webcam url might have changed, make sure we replace it now if the tab is focused
|
||||
// the webcam url might have changed, make sure we replace it now if the
|
||||
// tab is focused
|
||||
self._enableWebcam();
|
||||
self.requestData();
|
||||
};
|
||||
@@ -230,7 +243,7 @@ $(function () {
|
||||
element.slider.min
|
||||
);
|
||||
|
||||
// if default value is not within range of min and max, correct that
|
||||
// if default value is not w/i range of min and max, correct that
|
||||
if (
|
||||
!_.inRange(
|
||||
defaultValue,
|
||||
@@ -260,7 +273,8 @@ $(function () {
|
||||
if (control.hasOwnProperty("javascript")) {
|
||||
var js = control.javascript;
|
||||
|
||||
// if js is a function everything's fine already, but if it's a string we need to eval that first
|
||||
// if js is a function everything's fine already, but if it's a string
|
||||
// we need to eval that first
|
||||
if (!_.isFunction(js)) {
|
||||
control.javascript = function (data) {
|
||||
eval(js);
|
||||
@@ -271,7 +285,8 @@ $(function () {
|
||||
if (control.hasOwnProperty("enabled")) {
|
||||
var enabled = control.enabled;
|
||||
|
||||
// if js is a function everything's fine already, but if it's a string we need to eval that first
|
||||
// if js is a function everything's fine already, but if it's a string
|
||||
// we need to eval that first
|
||||
if (!_.isFunction(enabled)) {
|
||||
control.enabled = function (data) {
|
||||
return eval(enabled);
|
||||
@@ -318,6 +333,28 @@ $(function () {
|
||||
}
|
||||
};
|
||||
|
||||
self._getActiveWebcamVideoElement = function () {
|
||||
if (self.webcamWebRTCEnabled()) {
|
||||
return self.webcamElementWebrtc;
|
||||
} else {
|
||||
return self.webcamElementHls;
|
||||
}
|
||||
};
|
||||
|
||||
self.launchWebcamPictureInPicture = function () {
|
||||
self._getActiveWebcamVideoElement().requestPictureInPicture();
|
||||
};
|
||||
|
||||
self.launchWebcamFullscreen = function () {
|
||||
self._getActiveWebcamVideoElement().requestFullscreen();
|
||||
};
|
||||
|
||||
self.toggleWebcamMute = function () {
|
||||
self.webcamMuted(!self.webcamMuted());
|
||||
self.webcamElementWebrtc.muted = self.webcamMuted();
|
||||
self.webcamElementHls.muted = self.webcamMuted();
|
||||
};
|
||||
|
||||
self.sendJogCommand = function (axis, multiplier, distance) {
|
||||
if (typeof distance === "undefined") distance = self.distance();
|
||||
if (
|
||||
@@ -487,10 +524,12 @@ $(function () {
|
||||
};
|
||||
|
||||
self._disableWebcam = function () {
|
||||
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
|
||||
// more load by the constant connection creation than by the actual webcam stream
|
||||
// only disable webcam stream if tab is out of focus for more than 5s,
|
||||
// otherwise we might cause more load by the constant connection creation
|
||||
// than by the actual webcam stream
|
||||
|
||||
// safari bug doesn't release the mjpeg stream, so we just disable this for safari.
|
||||
// safari bug doesn't release the mjpeg stream, so we just disable this for
|
||||
// safari.
|
||||
if (OctoPrint.coreui.browser.safari) {
|
||||
return;
|
||||
}
|
||||
@@ -577,6 +616,11 @@ $(function () {
|
||||
self.extrusionAmount(self.settings.printer_defaultExtrusionLength());
|
||||
};
|
||||
|
||||
self.onStartup = function () {
|
||||
self.webcamElementHls = document.getElementById("webcam_hls");
|
||||
self.webcamElementWebrtc = document.getElementById("webcam_webrtc");
|
||||
};
|
||||
|
||||
self.onFocus = function (data, event) {
|
||||
if (!self.settings.feature_keyboardControl()) return;
|
||||
self.keycontrolActive(true);
|
||||
@@ -717,7 +761,14 @@ $(function () {
|
||||
};
|
||||
|
||||
self._switchToHlsWebcam = function () {
|
||||
var video = document.getElementById("webcam_hls");
|
||||
var video = self.webcamElementHls;
|
||||
video.onresize = self._updateVideoTagWebcamLayout;
|
||||
|
||||
// Ensure WebRTC is unloaded
|
||||
if (self.webRTCPeerConnection != null) {
|
||||
self.webRTCPeerConnection.close();
|
||||
self.webRTCPeerConnection = null;
|
||||
}
|
||||
|
||||
// Check for native playback options: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType
|
||||
if (
|
||||
@@ -727,9 +778,9 @@ $(function () {
|
||||
) {
|
||||
video.src = self.settings.webcam_streamUrl();
|
||||
} else if (Hls.isSupported()) {
|
||||
var hls = new Hls();
|
||||
hls.loadSource(self.settings.webcam_streamUrl());
|
||||
hls.attachMedia(video);
|
||||
self.hls = new Hls();
|
||||
self.hls.loadSource(self.settings.webcam_streamUrl());
|
||||
self.hls.attachMedia(video);
|
||||
}
|
||||
|
||||
self.webcamMjpgEnabled(false);
|
||||
@@ -741,7 +792,15 @@ $(function () {
|
||||
if (!isWebRTCAvailable()) {
|
||||
return;
|
||||
}
|
||||
var video = document.getElementById("webcam_webrtc");
|
||||
var video = self.webcamElementWebrtc;
|
||||
video.onresize = self._updateVideoTagWebcamLayout;
|
||||
|
||||
// Ensure HLS is unloaded
|
||||
if (self.hls != null) {
|
||||
self.webcamElementHls.src = null;
|
||||
self.hls.destroy();
|
||||
self.hls = null;
|
||||
}
|
||||
|
||||
// Close any existing, disconnected connection
|
||||
if (
|
||||
@@ -765,6 +824,57 @@ $(function () {
|
||||
self.webcamHlsEnabled(false);
|
||||
self.webcamWebRTCEnabled(true);
|
||||
};
|
||||
|
||||
self._updateVideoTagWebcamLayout = function () {
|
||||
// Get all elements we need
|
||||
var player = self._getActiveWebcamVideoElement();
|
||||
var rotationContainer = document.querySelector(
|
||||
"#webcam_video_container .webcam_rotated"
|
||||
);
|
||||
var rotationTarget = document.querySelector(
|
||||
"#webcam_video_container .webcam_rotated .rotation_target"
|
||||
);
|
||||
var unrotationContainer = document.querySelector(
|
||||
"#webcam_video_container .webcam_unrotated"
|
||||
);
|
||||
var unrotationTarget = document.querySelector(
|
||||
"#webcam_video_container .webcam_unrotated .rotation_target"
|
||||
);
|
||||
|
||||
// If we found the rotation container, the view is rotated 90 degrees. This
|
||||
// means we need to manually calculate the player dimensions and apply them
|
||||
// to the rotation target where height = width and width = height (to
|
||||
// accomodate the rotation). The target is centered in the container and
|
||||
// rotated around its center, so after we manually resized the container
|
||||
// everything will layout nicely.
|
||||
if (rotationContainer && player.videoWidth && player.videoHeight) {
|
||||
// Calculate the height the video will have in the UI, based on the
|
||||
// video width and the aspect ratio.
|
||||
var aspectRatio = player.videoWidth / player.videoHeight;
|
||||
var height = aspectRatio * rotationContainer.offsetWidth;
|
||||
|
||||
// Enforce the height on the rotation container and the rotation target.
|
||||
// Width of the container will be 100%, height will be calculated
|
||||
//
|
||||
// The size of the rotation target (the element that has the 90 deg
|
||||
// transform) is the inverse size of the container (so height -> width
|
||||
// and width -> height)
|
||||
rotationContainer.style.height = height + "px";
|
||||
rotationTarget.style.height = rotationContainer.offsetWidth + "px";
|
||||
rotationTarget.style.width = rotationContainer.offsetHeight + "px";
|
||||
|
||||
// Remove the padding we used to give the element an initial height.
|
||||
rotationContainer.style.paddingBottom = 0;
|
||||
}
|
||||
|
||||
// We are not rotated, clean up all changes we might have done before
|
||||
if (unrotationContainer) {
|
||||
unrotationContainer.style.height = null;
|
||||
unrotationContainer.style.paddingBottom = 0;
|
||||
unrotationTarget.style.height = null;
|
||||
unrotationTarget.style.width = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push({
|
||||
|
||||
@@ -1689,15 +1689,41 @@ $(function () {
|
||||
return extension.toLowerCase();
|
||||
}).sort();
|
||||
extensions = extensions.join(", ");
|
||||
var error =
|
||||
"<p>" +
|
||||
_.sprintf(
|
||||
gettext(
|
||||
"Could not upload the file. Make sure that it is a readable, valid file with one of these extensions: %(extensions)s"
|
||||
),
|
||||
{extensions: _.escape(extensions)}
|
||||
) +
|
||||
"</p>";
|
||||
|
||||
var error = "<p>";
|
||||
switch (data.jqXHR.status) {
|
||||
case 409:
|
||||
// already printing or otherwise busy
|
||||
if (e.target.id === "gcode_upload_sd") {
|
||||
error += gettext(
|
||||
"Could not upload the file to the printer's SD. Make sure the SD is initialized and the printer is not busy with a print already."
|
||||
);
|
||||
} else {
|
||||
error += gettext(
|
||||
"Could not upload the file, overwrite not possible. Make sure it is not already printing and that you have allowed overwriting."
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 415:
|
||||
// unknown file type
|
||||
error += _.sprintf(
|
||||
gettext(
|
||||
"Could not upload the file. Make sure that it is a readable, valid file with one of these extensions: %(extensions)s"
|
||||
),
|
||||
{extensions: _.escape(extensions)}
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
// any other kind of error
|
||||
error += gettext(
|
||||
"Could not upload the file. Please check octoprint.log for possible reasons."
|
||||
);
|
||||
break;
|
||||
}
|
||||
error += "</p>";
|
||||
|
||||
if (data.jqXHR.responseText) {
|
||||
error += pnotifyAdditionalInfo(
|
||||
"<pre>" + _.escape(data.jqXHR.responseText) + "</pre>"
|
||||
|
||||
@@ -90,3 +90,36 @@ body {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#noscript {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: #ffffff;
|
||||
z-index: 12310;
|
||||
|
||||
.wrapper {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
|
||||
.outer {
|
||||
display: table;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
.inner {
|
||||
display: table-cell;
|
||||
vertical-align: middle;
|
||||
|
||||
.content {
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -318,6 +318,7 @@ table {
|
||||
&.timelapse_files_checkbox,
|
||||
&.timelapse_unrendered_checkbox {
|
||||
text-align: center;
|
||||
vertical-align: middle;
|
||||
width: 10px;
|
||||
|
||||
input[type="checkbox"] {
|
||||
@@ -325,12 +326,65 @@ table {
|
||||
}
|
||||
}
|
||||
|
||||
&.timelapse_files_name,
|
||||
&.timelapse_unrendered_name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
&.timelapse_files_details {
|
||||
.name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
font-weight: 800;
|
||||
margin: 0 0 0 0;
|
||||
}
|
||||
.detail {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
margin: 0 0 0 0;
|
||||
font-size: 85%;
|
||||
color: #999;
|
||||
}
|
||||
}
|
||||
|
||||
&.timelapse_files_thumb {
|
||||
@thumb-size: 110px;
|
||||
@thumb-coner: 3px;
|
||||
width: @thumb-size;
|
||||
position: relative;
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
max-height: @thumb-size;
|
||||
border-radius: @thumb-coner;
|
||||
}
|
||||
|
||||
div {
|
||||
width: @thumb-size;
|
||||
height: calc(@thumb-size * 9 / 16);
|
||||
border-radius: @thumb-coner;
|
||||
background-color: rgb(238, 238, 238);
|
||||
}
|
||||
|
||||
a {
|
||||
background-image: url(/static/img/play.svg);
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: 32px 32px;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
opacity: 0.8;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
content: "";
|
||||
|
||||
&:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.timelapse_files_size {
|
||||
text-align: right;
|
||||
width: 55px;
|
||||
@@ -349,7 +403,14 @@ table {
|
||||
&.timelapse_files_action,
|
||||
&.timelapse_unrendered_action {
|
||||
width: 60px;
|
||||
position: relative;
|
||||
|
||||
.actioncol;
|
||||
.btn-group {
|
||||
position: absolute;
|
||||
bottom: 5px;
|
||||
right: 5px;
|
||||
}
|
||||
}
|
||||
|
||||
// user settings
|
||||
@@ -584,6 +645,57 @@ ul.dropdown-menu li a {
|
||||
}
|
||||
|
||||
/** Webcam */
|
||||
#webcam_video_container {
|
||||
width: 100%;
|
||||
position: relative;
|
||||
outline: none;
|
||||
|
||||
.video-controls {
|
||||
position: absolute;
|
||||
bottom: 0px;
|
||||
right: 8px;
|
||||
z-index: 10;
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
.video-controls {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
#webcam_hls,
|
||||
#webcam_rtsp {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.webcam_rotated {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
padding-bottom: 56.25%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
margin: auto;
|
||||
|
||||
.rotation_target {
|
||||
position: absolute;
|
||||
transform: rotate(-90deg);
|
||||
width: 100%;
|
||||
|
||||
div {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.webcam_unrotated {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
#webcam_container {
|
||||
width: 100%;
|
||||
|
||||
@@ -1 +1 @@
|
||||
{% filter externalize_links %}{% filter offset_html_headers(2) %}{% include "_data/AUTHORS.md.html" ignore missing %}{% endfilter %}{% endfilter %}
|
||||
{% filter externalize_links %}{% filter markdown %}{% filter offset_markdown_headers(2) %}{% include "_data/AUTHORS.md" ignore missing %}{% endfilter %}{% endfilter %}{% endfilter %}
|
||||
@@ -1 +1 @@
|
||||
{% filter externalize_links %}{% filter offset_html_headers(2) %}{% include "_data/SUPPORTERS.md.html" ignore missing %}{% endfilter %}{% endfilter %}
|
||||
{% filter externalize_links %}{% filter markdown %}{% filter offset_markdown_headers(2) %}{% include "_data/SUPPORTERS.md" ignore missing %}{% endfilter %}{% endfilter %}{% endfilter %}
|
||||
@@ -1 +1 @@
|
||||
{% filter externalize_links %}{% filter offset_html_headers(2) %}{% include "_data/THIRDPARTYLICENSES.md.html" ignore missing %}{% endfilter %}{% endfilter %}
|
||||
{% filter externalize_links %}{% filter markdown %}{% filter offset_markdown_headers(2) %}{% include "_data/THIRDPARTYLICENSES.md" ignore missing %}{% endfilter %}{% endfilter %}{% endfilter %}
|
||||
@@ -40,7 +40,28 @@
|
||||
<script src="{{ url_for("static", filename="js/login/login.js") }}"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<noscript>
|
||||
<style type="text/css">
|
||||
#login,
|
||||
#login-overlay {
|
||||
display:none;
|
||||
}
|
||||
</style>
|
||||
<div id="noscript">
|
||||
<div class="wrapper">
|
||||
<div class="outer">
|
||||
<div class="inner">
|
||||
<div class="content">
|
||||
<h1 class="text-error">{{ _('You don\'t seem to have JavaScript enabled') }}</h1>
|
||||
{{ _('OctoPrint\'s UI requires JavaScript to work. Please enable JavaScript and reload.') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</noscript>
|
||||
|
||||
<div id="login" class="container">
|
||||
<form class="form-signin">
|
||||
<h2 class="form-signin-heading" data-test-id="login-title">{{ _('Please log in') }}</h2>
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<form class="form-search" data-bind="submit: performSearch, visible: $root.loginState.hasPermissionKo($root.access.permissions.FILES_LIST)">
|
||||
<div class="search-query-with-clear" data-bind="css: {'active-clear': searchQuery}">
|
||||
<input type="search" class="input-block search-query" data-bind="value: searchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}">
|
||||
<input type="search" class="input-block search-query" data-bind="value: searchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}" spellcheck="false">
|
||||
<span class="search-clear" data-bind="click: clearSearchQuery"><i class="fas fa-times"></i></span>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -1,10 +1,26 @@
|
||||
{% if enableWebcam %}
|
||||
<!-- ko if: loginState.hasPermissionKo(access.permissions.WEBCAM) -->
|
||||
<div id="webcam_webrtc_container" tabindex="0" data-bind="visible: webcamWebRTCEnabled()">
|
||||
<video id="webcam_webrtc" muted autoplay playsinline controls style="width: 100%"></video>
|
||||
</div>
|
||||
<div id="webcam_hls_container" tabindex="0" data-bind="visible: webcamHlsEnabled()">
|
||||
<video id="webcam_hls" muted autoplay style="width: 100%"></video>
|
||||
<div id="webcam_video_container" tabindex="0" data-bind="visible: webcamWebRTCEnabled() || webcamHlsEnabled(), css: { webcam_rotated: settings.webcam_rotate90(), webcam_unrotated: !settings.webcam_rotate90() }">
|
||||
<div class="video-controls btn-group action-buttons">
|
||||
<div class="btn btn-mini" data-bind="click: function(data, event) { $root.launchWebcamFullscreen() }"><i class="fas fa-expand"></i></div>
|
||||
<div class="btn btn-mini" data-bind="visible: document.pictureInPictureEnabled, click: function(data, event) { $root.launchWebcamPictureInPicture() }"><i class="fas fa-images"></i></div>
|
||||
<div class="btn btn-mini" data-bind="click: function(data, event) { $root.toggleWebcamMute() }">
|
||||
<!-- ko if: webcamMuted() -->
|
||||
<i class="fas fa-volume-mute"></i>
|
||||
<!-- /ko -->
|
||||
<!-- ko ifnot: webcamMuted() -->
|
||||
<i class="fas fa-volume-up"></i>
|
||||
<!-- /ko -->
|
||||
</div>
|
||||
</div>
|
||||
<div data-bind="css: { webcam_rotated: settings.webcam_rotate90(), webcam_unrotated: !settings.webcam_rotate90() }">
|
||||
<div class="rotation_target">
|
||||
<div data-bind="css: { flipH: settings.webcam_flipH(), flipV: settings.webcam_flipV() }">
|
||||
<video id="webcam_webrtc" muted autoplay playsinline style="width: 100%" data-bind="visible: webcamWebRTCEnabled()"></video>
|
||||
<video id="webcam_hls" muted autoplay playsinline style="width: 100%" data-bind="visible: webcamHlsEnabled()"></video>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="webcam_container" tabindex="0" data-bind="event: { keydown: onKeyDown, mouseover: onMouseOver, mouseout: onMouseOut, focus: onFocus }, visible: webcamMjpgEnabled()">
|
||||
<div class="nowebcam" data-bind="visible: !webcamLoaded()">
|
||||
|
||||
@@ -133,21 +133,38 @@
|
||||
<button class="btn btn-small" data-bind="click: removeMarkedFiles, enable: markedForFileDeletion().length > 0">{{ _('Delete selected') }}</button>
|
||||
<a class="btn btn-small" data-bind="css: { disabled: !enableBulkDownload() }, attr: { href: bulkDownloadButtonUrl }">{{_('Download selected')}}</a>
|
||||
</div>
|
||||
<table class="table table-striped table-hover table-condensed table-hover" id="timelapse_files">
|
||||
<table class="table table-hover table-condensed table-hover" id="timelapse_files">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="timelapse_files_checkbox"></th>
|
||||
<th class="timelapse_files_name">{{ _('Name') }}</th>
|
||||
<th class="timelapse_files_size">{{ _('Size') }}</th>
|
||||
<th class="timelapse_files_thumb">{{ _('Preview') }}</th>
|
||||
<th class="timelapse_files_details">{{ _('Details') }}</th>
|
||||
<th class="timelapse_files_action">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: listHelper.paginatedItems">
|
||||
<tr data-bind="attr: {title: name}">
|
||||
<td class="timelapse_files_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForFileDeletion, invisible: !$root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_DELETE)()"></td>
|
||||
<td class="timelapse_files_name" data-bind="text: name"></td>
|
||||
<td class="timelapse_files_size" data-bind="text: size"></td>
|
||||
<td class="timelapse_files_action"><a href="javascript:void(0)" class="far fa-trash-alt" data-bind="click: function() { $parent.removeFile($data.name); }, css: {disabled: !$root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_DELETE)() }"></a> | <a href="javascript:void(0)" class="fas fa-download" data-bind="css: {disabled: !$root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_DOWNLOAD)()}, attr: { href: ($root.loginState.hasPermission($root.access.permissions.TIMELAPSE_DOWNLOAD)) ? $data.url : 'javascript:void(0)' }"></a> | <a href="javascript:void(0)" class="fas fa-camera" data-bind="css: {disabled: !$root.isTimelapseViewable($data)}, click: $root.showTimelapsePreview"></a></td>
|
||||
<td class="timelapse_files_thumb">
|
||||
<!-- ko if: $data.thumbnail -->
|
||||
<img data-bind="attr:{src: thumbnail}" loading="lazy" />
|
||||
<!-- /ko -->
|
||||
<!-- ko ifnot: $data.thumbnail -->
|
||||
<div></div>
|
||||
<!-- /ko -->
|
||||
<a href="javascript:void(0)" data-bind="css: {disabled: !$root.isTimelapseViewable($data)}, click: $root.showTimelapsePreview"></a>
|
||||
</td>
|
||||
<td class="timelapse_files_details">
|
||||
<p class="name" data-bind="text: name"></p>
|
||||
<p class="detail">{{ _('Recorded:') }} <span data-bind="text: formatTimeAgo(timestamp)"/></p>
|
||||
<p class="detail">{{ _('Size:') }} <span data-bind="text: size"/></p>
|
||||
</td>
|
||||
<td class="timelapse_files_action">
|
||||
<div class="btn-group action-buttons">
|
||||
<div href="javascript:void(0)" class="btn btn-mini" data-bind="click: function() { $parent.removeFile($data.name); }, css: {disabled: !$root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_DELETE)() }"><i class="far fa-trash-alt"></i></div>
|
||||
<a href="javascript:void(0)" class="btn btn-mini" data-bind="css: {disabled: !$root.loginState.hasPermissionKo($root.access.permissions.TIMELAPSE_DOWNLOAD)()}, attr: { href: ($root.loginState.hasPermission($root.access.permissions.TIMELAPSE_DOWNLOAD)) ? $data.url : 'javascript:void(0)' }"><i class="fas fa-download"></i></a>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -13,7 +13,6 @@ import shutil
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from os import scandir
|
||||
|
||||
import requests
|
||||
import sarge
|
||||
@@ -38,6 +37,11 @@ _capture_format = "{prefix}-%d.jpg"
|
||||
_capture_glob = "{prefix}-*.jpg"
|
||||
_output_format = "{prefix}{postfix}.{extension}"
|
||||
|
||||
# thumbnails
|
||||
_thumbnail_extension = ".thumb.jpg"
|
||||
_thumbnail_format = "{}.thumb.jpg"
|
||||
|
||||
|
||||
# ffmpeg progress regexes
|
||||
_ffmpeg_duration_regex = re.compile(r"Duration: (\d{2}):(\d{2}):(\d{2})\.\d{2}")
|
||||
_ffmpeg_current_regex = re.compile(r"time=(\d{2}):(\d{2}):(\d{2})\.\d{2}")
|
||||
@@ -62,6 +66,10 @@ _job_lock = threading.RLock()
|
||||
_extensions = None
|
||||
|
||||
|
||||
def create_thumbnail_path(movie_path):
|
||||
return _thumbnail_format.format(movie_path)
|
||||
|
||||
|
||||
def valid_timelapse(path):
|
||||
global _extensions
|
||||
|
||||
@@ -88,11 +96,20 @@ def valid_timelapse(path):
|
||||
return util.is_allowed_file(path, _extensions)
|
||||
|
||||
|
||||
def valid_timelapse_thumbnail(path):
|
||||
global _thumbnail_extensions
|
||||
# Thumbnail path is valid if it ends with thumbnail extension and path without extension is valid timelpase
|
||||
if path.endswith(_thumbnail_extension):
|
||||
return valid_timelapse(path[: -len(_thumbnail_extension)])
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def _extract_prefix(filename):
|
||||
"""
|
||||
>>> _extract_prefix("some_long_filename_without_hyphen.jpg")
|
||||
>>> _extract_prefix("-first_char_is_hyphen.jpg")
|
||||
>>> _extract_prefix("some_long_filename_with-stuff.jpg") # doctest: +ALLOW_UNICODE
|
||||
>>> _extract_prefix("some_long_filename_with-stuff.jpg")
|
||||
'some_long_filename_with'
|
||||
"""
|
||||
pos = filename.rfind("-")
|
||||
@@ -114,14 +131,23 @@ def last_modified_unrendered():
|
||||
def get_finished_timelapses():
|
||||
files = []
|
||||
basedir = settings().getBaseFolder("timelapse", check_writable=False)
|
||||
for entry in scandir(basedir):
|
||||
for entry in os.scandir(basedir):
|
||||
if util.is_hidden_path(entry.path) or not valid_timelapse(entry.path):
|
||||
continue
|
||||
|
||||
thumb = create_thumbnail_path(entry.path)
|
||||
if os.path.isfile(thumb) is True:
|
||||
thumb = os.path.basename(thumb)
|
||||
else:
|
||||
thumb = None
|
||||
|
||||
files.append(
|
||||
{
|
||||
"name": entry.name,
|
||||
"size": util.get_formatted_size(entry.stat().st_size),
|
||||
"bytes": entry.stat().st_size,
|
||||
"thumbnail": thumb,
|
||||
"timestamp": entry.stat().st_mtime,
|
||||
"date": util.get_formatted_datetime(
|
||||
datetime.datetime.fromtimestamp(entry.stat().st_mtime)
|
||||
),
|
||||
@@ -141,7 +167,7 @@ def get_unrendered_timelapses():
|
||||
lambda: {"count": 0, "size": None, "bytes": 0, "date": None, "timestamp": None}
|
||||
)
|
||||
|
||||
for entry in scandir(basedir):
|
||||
for entry in os.scandir(basedir):
|
||||
if not fnmatch.fnmatch(entry.name, "*.jpg"):
|
||||
continue
|
||||
|
||||
@@ -193,7 +219,7 @@ def delete_unrendered_timelapse(name):
|
||||
|
||||
basedir = settings().getBaseFolder("timelapse_tmp")
|
||||
with _cleanup_lock:
|
||||
for entry in scandir(basedir):
|
||||
for entry in os.scandir(basedir):
|
||||
try:
|
||||
if fnmatch.fnmatch(entry.name, pattern):
|
||||
os.remove(entry.path)
|
||||
@@ -239,7 +265,7 @@ def delete_old_unrendered_timelapses():
|
||||
prefixes_to_clean = []
|
||||
|
||||
with _cleanup_lock:
|
||||
for entry in scandir(basedir):
|
||||
for entry in os.scandir(basedir):
|
||||
try:
|
||||
prefix = _extract_prefix(entry.name)
|
||||
if prefix is None:
|
||||
@@ -1047,6 +1073,10 @@ class TimelapseRenderJob:
|
||||
|
||||
if returncode == 0:
|
||||
shutil.move(temporary, output)
|
||||
self._try_generate_thumbnail(
|
||||
ffmpeg=ffmpeg,
|
||||
movie_path=output,
|
||||
)
|
||||
self._notify_callback("success", output)
|
||||
else:
|
||||
self._logger.warning(
|
||||
@@ -1094,6 +1124,36 @@ class TimelapseRenderJob:
|
||||
if duration is not None:
|
||||
self._parsed_duration = self._convert_time(*duration.groups())
|
||||
|
||||
def _try_generate_thumbnail(self, ffmpeg, movie_path):
|
||||
try:
|
||||
thumb_path = create_thumbnail_path(movie_path)
|
||||
commandline = settings().get(["webcam", "ffmpegThumbnailCommandline"])
|
||||
thumb_command_str = self._create_ffmpeg_command_string(
|
||||
commandline=commandline,
|
||||
ffmpeg=ffmpeg,
|
||||
input=movie_path,
|
||||
output=thumb_path,
|
||||
fps=None,
|
||||
videocodec=None,
|
||||
threads=None,
|
||||
bitrate=None,
|
||||
)
|
||||
c = CommandlineCaller()
|
||||
returncode, stdout_text, stderr_text = c.call(
|
||||
thumb_command_str, delimiter=b"\r", buffer_size=512
|
||||
)
|
||||
if returncode != 0:
|
||||
self._logger.warning(
|
||||
"Failed to generate optional thumbnail %r: %s"
|
||||
% (returncode, stderr_text)
|
||||
)
|
||||
except Exception as ex:
|
||||
self._logger.warning(
|
||||
"Failed to generate thumbnail from {} to {} ({})".format(
|
||||
movie_path, thumb_path, ex
|
||||
)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _convert_time(hours, minutes, seconds):
|
||||
return (int(hours) * 60 + int(minutes)) * 60 + int(seconds)
|
||||
|
||||
+101
-78
@@ -11,10 +11,10 @@ import codecs
|
||||
import collections
|
||||
import contextlib
|
||||
import copy
|
||||
import glob
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import pickle # Python 3
|
||||
import pickle
|
||||
import queue
|
||||
import re
|
||||
import shutil
|
||||
@@ -24,8 +24,11 @@ import threading
|
||||
import time
|
||||
import traceback
|
||||
import warnings
|
||||
import zlib
|
||||
from collections.abc import Iterable, MutableMapping, Set
|
||||
from functools import wraps
|
||||
from glob import escape as glob_escape # noqa: F401
|
||||
from time import monotonic as monotonic_time # noqa: F401
|
||||
from typing import Union
|
||||
|
||||
from frozendict import frozendict
|
||||
@@ -48,14 +51,14 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
def to_bytes(
|
||||
s_or_u: Union[str, bytes], encoding: str = "utf-8", errors: str = "strict"
|
||||
) -> Union[bytes, None]:
|
||||
) -> bytes:
|
||||
"""
|
||||
Make sure ``s_or_u`` is a byte string.
|
||||
|
||||
Arguments:
|
||||
s_or_u (string or unicode): The value to convert
|
||||
encoding (string): encoding to use if necessary, see :meth:`python:str.encode`
|
||||
errors (string): error handling to use if necessary, see :meth:`python:str.encode`
|
||||
s_or_u (str or bytes): The value to convert
|
||||
encoding (str): encoding to use if necessary, see :meth:`python:str.encode`
|
||||
errors (str): error handling to use if necessary, see :meth:`python:str.encode`
|
||||
Returns:
|
||||
bytes: converted bytes.
|
||||
"""
|
||||
@@ -73,16 +76,16 @@ def to_bytes(
|
||||
|
||||
def to_unicode(
|
||||
s_or_u: Union[str, bytes], encoding: str = "utf-8", errors: str = "strict"
|
||||
) -> Union[str, None]:
|
||||
) -> str:
|
||||
"""
|
||||
Make sure ``s_or_u`` is a unicode string.
|
||||
Make sure ``s_or_u`` is a unicode string (str).
|
||||
|
||||
Arguments:
|
||||
s_or_u (string or unicode): The value to convert
|
||||
encoding (string): encoding to use if necessary, see :meth:`python:bytes.decode`
|
||||
errors (string): error handling to use if necessary, see :meth:`python:bytes.decode`
|
||||
s_or_u (str or bytes): The value to convert
|
||||
encoding (str): encoding to use if necessary, see :meth:`python:bytes.decode`
|
||||
errors (str): error handling to use if necessary, see :meth:`python:bytes.decode`
|
||||
Returns:
|
||||
string: converted string.
|
||||
str: converted string.
|
||||
"""
|
||||
if s_or_u is None:
|
||||
return s_or_u
|
||||
@@ -107,21 +110,21 @@ sv = sortable_value
|
||||
|
||||
def pp(value):
|
||||
"""
|
||||
>>> pp(dict()) # doctest: +ALLOW_UNICODE
|
||||
>>> pp(dict())
|
||||
'dict()'
|
||||
>>> pp(dict(a=1, b=2, c=3)) # doctest: +ALLOW_UNICODE
|
||||
>>> pp(dict(a=1, b=2, c=3))
|
||||
'dict(a=1, b=2, c=3)'
|
||||
>>> pp(set()) # doctest: +ALLOW_UNICODE
|
||||
>>> pp(set())
|
||||
'set()'
|
||||
>>> pp({"a", "b"}) # doctest: +ALLOW_UNICODE
|
||||
>>> pp({"a", "b"})
|
||||
"{'a', 'b'}"
|
||||
>>> pp(["a", "b", "d", "c"]) # doctest: +ALLOW_UNICODE
|
||||
>>> pp(["a", "b", "d", "c"])
|
||||
"['a', 'b', 'd', 'c']"
|
||||
>>> pp(("a", "b", "d", "c")) # doctest: +ALLOW_UNICODE
|
||||
>>> pp(("a", "b", "d", "c"))
|
||||
"('a', 'b', 'd', 'c')"
|
||||
>>> pp("foo") # doctest: +ALLOW_UNICODE
|
||||
>>> pp("foo")
|
||||
"'foo'"
|
||||
>>> pp([dict(a=1, b=2), {"a", "c", "b"}, (1, 2), None, 1, True, "foo"]) # doctest: +ALLOW_UNICODE
|
||||
>>> pp([dict(a=1, b=2), {"a", "c", "b"}, (1, 2), None, 1, True, "foo"])
|
||||
"[dict(a=1, b=2), {'a', 'b', 'c'}, (1, 2), None, 1, True, 'foo']"
|
||||
"""
|
||||
|
||||
@@ -312,10 +315,10 @@ Returns:
|
||||
value: The value of the variable with the deprecation warnings in place.
|
||||
"""
|
||||
|
||||
|
||||
# TODO rename to_unicode to to_str and deprecate to_unicode in 2.0.0
|
||||
to_str = deprecated(
|
||||
"to_str has been renamed to to_bytes",
|
||||
includedoc="to_str has been renamed to to_bytes",
|
||||
"to_str has been renamed to to_bytes and in a future version will become the new to_unicode",
|
||||
includedoc="to_str has been renamed to to_bytes and in a future version will become the new to_unicode",
|
||||
since="1.3.11",
|
||||
)(to_bytes)
|
||||
|
||||
@@ -326,6 +329,13 @@ to_native_str = deprecated(
|
||||
)(to_unicode)
|
||||
|
||||
|
||||
to_native_str = deprecated(
|
||||
"to_native_str is no longer needed, use to_unicode instead",
|
||||
includedoc="to_native_str is no longer needed, use to_unicode instead",
|
||||
since="1.8.0",
|
||||
)(to_unicode)
|
||||
|
||||
|
||||
def get_formatted_size(num):
|
||||
"""
|
||||
Formats the given byte count as a human readable rounded size expressed in the most pressing unit among B(ytes),
|
||||
@@ -400,13 +410,6 @@ def get_formatted_datetime(d):
|
||||
return d.strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
|
||||
monotonic_time = deprecated(
|
||||
"monotonic_time is natively available as time.monotonic in Python 3",
|
||||
includedoc="Replaced by :func:`time.monotonic`",
|
||||
since="2.0.0",
|
||||
)(time.monotonic)
|
||||
|
||||
|
||||
def get_class(name):
|
||||
"""
|
||||
Retrieves the class object for a given fully qualified class name.
|
||||
@@ -994,26 +997,27 @@ def atomic_write(
|
||||
|
||||
# Ensure we create the file in the target dir so our move is atomic. See #3719
|
||||
dir = os.path.dirname(filename)
|
||||
kwargs = {
|
||||
"mode": mode,
|
||||
"prefix": prefix,
|
||||
"suffix": suffix,
|
||||
"dir": dir,
|
||||
"delete": False,
|
||||
}
|
||||
if "b" not in mode:
|
||||
kwargs["encoding"] = encoding
|
||||
|
||||
temp_config = tempfile.NamedTemporaryFile(
|
||||
mode=mode,
|
||||
prefix=prefix,
|
||||
suffix=suffix,
|
||||
delete=False,
|
||||
dir=dir,
|
||||
encoding=encoding if "b" not in mode else None,
|
||||
)
|
||||
fd = tempfile.NamedTemporaryFile(**kwargs)
|
||||
try:
|
||||
try:
|
||||
yield temp_config
|
||||
yield fd
|
||||
finally:
|
||||
temp_config.close()
|
||||
fd.close()
|
||||
|
||||
os.chmod(temp_config.name, permissions)
|
||||
shutil.move(temp_config.name, filename)
|
||||
os.chmod(fd.name, permissions)
|
||||
shutil.move(fd.name, filename)
|
||||
finally:
|
||||
# just in case something went wrong and the temporary file is still there, nuke it now
|
||||
silent_remove(temp_config.name)
|
||||
silent_remove(fd.name)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
@@ -1044,35 +1048,10 @@ def temppath(prefix=None, suffix=""):
|
||||
os.remove(temp.name)
|
||||
|
||||
|
||||
if hasattr(tempfile, "TemporaryDirectory"):
|
||||
# Python 3
|
||||
TemporaryDirectory = tempfile.TemporaryDirectory
|
||||
else:
|
||||
# Python 2
|
||||
class TemporaryDirectory:
|
||||
def __init__(self, suffix="", prefix="tmp", dir=None):
|
||||
self._path = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self._path
|
||||
|
||||
def cleanup(self):
|
||||
try:
|
||||
os.remove(self._path)
|
||||
except Exception as exc:
|
||||
logging.getLogger(__name__).warning(
|
||||
f"Could not delete temporary directory {self.name}: {exc}"
|
||||
)
|
||||
|
||||
def __enter__(self):
|
||||
return self.name
|
||||
|
||||
def __exit__(self):
|
||||
self.cleanup()
|
||||
TemporaryDirectory = tempfile.TemporaryDirectory
|
||||
|
||||
|
||||
@deprecated("Please use io.open with '-sig' encoding instead", since="1.8.0")
|
||||
@deprecated("Please use open with '-sig' encoding instead", since="1.8.0")
|
||||
def bom_aware_open(filename, encoding="ascii", mode="r", **kwargs):
|
||||
# TODO Remove in 2.0.0
|
||||
import codecs
|
||||
@@ -1156,13 +1135,6 @@ def is_hidden_path(path):
|
||||
return False
|
||||
|
||||
|
||||
glob_escape = deprecated(
|
||||
"glob_escape is available natively under Python 3 as glob.escape",
|
||||
includedoc="Replaced by :func:`glob.escape`",
|
||||
since="2.0.0",
|
||||
)(glob.escape)
|
||||
|
||||
|
||||
def thaw_frozendict(obj):
|
||||
if not isinstance(obj, (dict, frozendict)):
|
||||
raise ValueError("obj must be a dict or frozendict instance")
|
||||
@@ -1741,3 +1713,54 @@ def generate_api_key():
|
||||
|
||||
def map_boolean(value, true_text, false_text):
|
||||
return true_text if value else false_text
|
||||
|
||||
|
||||
def serialize(filename, data, encoding="utf-8", compressed=True):
|
||||
"""
|
||||
Serializes data to a file
|
||||
|
||||
In the current implementation this uses json.dumps and - if compressed is True (the
|
||||
default) - zlib.compress. Only data that can be serialized by json.dumps in the stock
|
||||
configuration is supported.
|
||||
|
||||
This is not thread-safe, if concurrent access is required, the caller needs to ensure
|
||||
that only one thread is writing to the file at any given time.
|
||||
|
||||
Arguments:
|
||||
filename (str): The file to write to
|
||||
data (object): The data to serialize
|
||||
encoding (str): The encoding to use for the file
|
||||
compressed (bool): Whether to compress the data before writing it to the file
|
||||
"""
|
||||
serialized = json.dumps(data).encode(encoding)
|
||||
|
||||
if compressed:
|
||||
serialized = zlib.compress(serialized)
|
||||
|
||||
with open(filename, "wb") as f:
|
||||
f.write(serialized)
|
||||
|
||||
|
||||
def deserialize(filename, encoding="utf-8"):
|
||||
"""
|
||||
Deserializes data from a file
|
||||
|
||||
In the current implementation this uses json.loads and - if the file is found to be
|
||||
compressed - zlib.decompress.
|
||||
|
||||
Arguments:
|
||||
filename (str): The file to deserialize from
|
||||
encoding (str): The encoding to use for the file, defaults to utf-8
|
||||
|
||||
Returns:
|
||||
The deserialized data structure
|
||||
"""
|
||||
with open(filename, "rb") as f:
|
||||
serialized = f.read()
|
||||
|
||||
try:
|
||||
serialized = zlib.decompress(serialized)
|
||||
except zlib.error:
|
||||
pass
|
||||
|
||||
return json.loads(serialized.decode(encoding))
|
||||
+65
-46
@@ -109,15 +109,16 @@ Groups will be as follows:
|
||||
"""
|
||||
|
||||
regex_temp = re.compile(
|
||||
r"(?P<tool>B|C|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*\/?\s*(?P<target>%s))?"
|
||||
r"(?P<sensor>B|C|T(?P<toolnum>\d*)|([\w]+)):\s*(?P<actual>%s)(\s*\/?\s*(?P<target>%s))?"
|
||||
% (regex_float_pattern, regex_float_pattern)
|
||||
)
|
||||
"""Regex matching temperature entries in line.
|
||||
|
||||
Groups will be as follows:
|
||||
|
||||
* ``tool``: whole tool designator, incl. optional ``toolnum`` (str)
|
||||
* ``toolnum``: tool number, if provided (int)
|
||||
* ``sensor``: whole sensor designator, incl. optional ``toolnum``, e.g. "T1", "B",
|
||||
"C" or anything custom (str)
|
||||
* ``toolnum``: tool number, if provided, only for T0, T1, etc (int)
|
||||
* ``actual``: actual temperature (float)
|
||||
* ``target``: target temperature, if provided (float)
|
||||
"""
|
||||
@@ -766,6 +767,9 @@ class MachineCom:
|
||||
["serial", "abortHeatupOnCancel"]
|
||||
)
|
||||
|
||||
# serial encoding
|
||||
self._serial_encoding = settings().get(["serial", "encoding"])
|
||||
|
||||
# print job
|
||||
self._currentFile = None
|
||||
self._job_on_hold = CountedEvent()
|
||||
@@ -3706,23 +3710,30 @@ class MachineCom:
|
||||
if settings().getBoolean(["serial", "exclusive"]):
|
||||
serial_port_args["exclusive"] = True
|
||||
|
||||
serial_obj = serial.Serial(**serial_port_args)
|
||||
serial_obj.port = str(p)
|
||||
try:
|
||||
serial_obj = serial.Serial(**serial_port_args)
|
||||
serial_obj.port = str(p)
|
||||
|
||||
use_parity_workaround = settings().get(["serial", "useParityWorkaround"])
|
||||
needs_parity_workaround = get_os() == "linux" and os.path.exists(
|
||||
"/etc/debian_version"
|
||||
) # See #673
|
||||
use_parity_workaround = settings().get(["serial", "useParityWorkaround"])
|
||||
needs_parity_workaround = get_os() == "linux" and os.path.exists(
|
||||
"/etc/debian_version"
|
||||
) # See #673
|
||||
|
||||
if use_parity_workaround == "always" or (
|
||||
needs_parity_workaround and use_parity_workaround == "detect"
|
||||
):
|
||||
serial_obj.parity = serial.PARITY_ODD
|
||||
serial_obj.open()
|
||||
serial_obj.close()
|
||||
serial_obj.parity = serial.PARITY_NONE
|
||||
|
||||
if use_parity_workaround == "always" or (
|
||||
needs_parity_workaround and use_parity_workaround == "detect"
|
||||
):
|
||||
serial_obj.parity = serial.PARITY_ODD
|
||||
serial_obj.open()
|
||||
serial_obj.close()
|
||||
serial_obj.parity = serial.PARITY_NONE
|
||||
|
||||
serial_obj.open()
|
||||
except serial.SerialException:
|
||||
self._logger.info(
|
||||
f"Failed to connect: Port {p} is busy or does not exist"
|
||||
)
|
||||
return None
|
||||
|
||||
# Set close_exec flag on serial handle, see #3212
|
||||
if hasattr(serial_obj, "fd"):
|
||||
@@ -4208,7 +4219,7 @@ class MachineCom:
|
||||
# handled it.
|
||||
return False
|
||||
|
||||
cmd = self._lastLines[-self._resendDelta].decode("ascii")
|
||||
cmd = self._lastLines[-self._resendDelta].decode(self._serial_encoding)
|
||||
result = self._enqueue_for_sending(cmd, linenumber=lineNumber, resend=True)
|
||||
|
||||
self._resendDelta -= 1
|
||||
@@ -4445,7 +4456,9 @@ class MachineCom:
|
||||
# line number predetermined - this only happens for resends, so we'll use the number and
|
||||
# send directly without any processing (since that already took place on the first sending!)
|
||||
self._use_up_clear(gcode)
|
||||
self._do_send_with_checksum(command.encode("ascii"), linenumber)
|
||||
self._do_send_with_checksum(
|
||||
command.encode(self._serial_encoding), linenumber
|
||||
)
|
||||
|
||||
else:
|
||||
if not processed:
|
||||
@@ -4752,7 +4765,7 @@ class MachineCom:
|
||||
)
|
||||
|
||||
def _do_send(self, command, gcode=None):
|
||||
command_to_send = command.encode("ascii", errors="replace")
|
||||
command_to_send = command.encode(self._serial_encoding, errors="replace")
|
||||
if self._needs_checksum(gcode):
|
||||
self._do_increment_and_send_with_checksum(command_to_send)
|
||||
else:
|
||||
@@ -4766,11 +4779,15 @@ class MachineCom:
|
||||
self._do_send_with_checksum(cmd, linenumber)
|
||||
|
||||
def _do_send_with_checksum(self, command, linenumber):
|
||||
command_to_send = b"N" + str(linenumber).encode("ascii") + b" " + command
|
||||
command_to_send = (
|
||||
b"N" + str(linenumber).encode(self._serial_encoding) + b" " + command
|
||||
)
|
||||
checksum = 0
|
||||
for c in bytearray(command_to_send):
|
||||
checksum ^= c
|
||||
command_to_send = command_to_send + b"*" + str(checksum).encode("ascii")
|
||||
command_to_send = (
|
||||
command_to_send + b"*" + str(checksum).encode(self._serial_encoding)
|
||||
)
|
||||
self._do_send_without_checksum(command_to_send)
|
||||
|
||||
def _do_send_without_checksum(self, cmd, log=True):
|
||||
@@ -4778,7 +4795,7 @@ class MachineCom:
|
||||
return
|
||||
|
||||
if log:
|
||||
self._log("Send: " + cmd.decode("ascii"))
|
||||
self._log("Send: " + cmd.decode(self._serial_encoding))
|
||||
|
||||
cmd += b"\n"
|
||||
written = 0
|
||||
@@ -5245,7 +5262,9 @@ class MachineCom:
|
||||
for tool in range(
|
||||
self._printerProfileManager.get_current_or_default()["extruder"]["count"]
|
||||
):
|
||||
self._do_increment_and_send_with_checksum(f"M104 T{tool} S0".encode("ascii"))
|
||||
self._do_increment_and_send_with_checksum(
|
||||
f"M104 T{tool} S0".encode(self._serial_encoding)
|
||||
)
|
||||
if self._printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
self._do_increment_and_send_with_checksum(b"M140 S0")
|
||||
|
||||
@@ -6185,27 +6204,27 @@ def parse_temperature_line(line, current):
|
||||
"""
|
||||
|
||||
result = {}
|
||||
maxToolNum = 0
|
||||
max_tool_num = 0
|
||||
for match in re.finditer(regex_temp, line):
|
||||
values = match.groupdict()
|
||||
tool = values["tool"]
|
||||
sensor = values["sensor"]
|
||||
toolnum = values.get("toolnum", None)
|
||||
toolNumber = int(toolnum) if toolnum is not None and len(toolnum) else None
|
||||
if toolNumber and toolNumber > maxToolNum:
|
||||
maxToolNum = toolNumber
|
||||
tool_number = int(toolnum) if toolnum is not None and len(toolnum) else None
|
||||
if tool_number and tool_number > max_tool_num:
|
||||
max_tool_num = tool_number
|
||||
|
||||
try:
|
||||
actual = float(match.group(3))
|
||||
actual = float(values["actual"])
|
||||
target = None
|
||||
if match.group(4) and match.group(5):
|
||||
target = float(match.group(5))
|
||||
if values["target"]:
|
||||
target = float(values["target"])
|
||||
|
||||
result[tool] = (actual, target)
|
||||
result[sensor] = (actual, target)
|
||||
except ValueError:
|
||||
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
|
||||
pass
|
||||
|
||||
return max(maxToolNum, current), canonicalize_temperatures(result, current)
|
||||
return max(max_tool_num, current), canonicalize_temperatures(result, current)
|
||||
|
||||
|
||||
def parse_firmware_line(line):
|
||||
@@ -6404,31 +6423,31 @@ def _normalize_command_handler_result(
|
||||
be empty in which case the command is to be suppressed.
|
||||
|
||||
Examples:
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, None) # doctest: +ALLOW_UNICODE
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, None)
|
||||
[('M105', None, 'M105', None, None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, "M110") # doctest: +ALLOW_UNICODE
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, "M110")
|
||||
[('M110', None, 'M110', None, None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110"]) # doctest: +ALLOW_UNICODE
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110"])
|
||||
[('M110', None, 'M110', None, None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110", "M117 Foobar"])
|
||||
[('M110', None, 'M110', None, None), ('M117 Foobar', None, 'M117', None, None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), "M117 Foobar"]) # doctest: +ALLOW_UNICODE
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), "M117 Foobar"])
|
||||
[('M110', None, 'M110', None, None), ('M117 Foobar', None, 'M117', None, None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110", "lineno_reset"), "M117 Foobar"]) # doctest: +ALLOW_UNICODE
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110", "lineno_reset"), "M117 Foobar"])
|
||||
[('M110', 'lineno_reset', 'M110', None, None), ('M117 Foobar', None, 'M117', None, None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, []) # doctest: +ALLOW_UNICODE
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [])
|
||||
[]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110", None]) # doctest: +ALLOW_UNICODE
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110", None])
|
||||
[('M110', None, 'M110', None, None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), (None, "ignored")]) # doctest: +ALLOW_UNICODE
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), (None, "ignored")])
|
||||
[('M110', None, 'M110', None, None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of", "unexpected", "length"), ("M110", "lineno_reset")]) # doctest: +ALLOW_UNICODE
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of", "unexpected", "length"), ("M110", "lineno_reset")])
|
||||
[('M110', None, 'M110', None, None), ('M117 Foobar', 'display_message', 'M117', None, None), ('M110', 'lineno_reset', 'M110', None, None)]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", "M117 Foobar"])
|
||||
[('M110', None, 'M110', None, {'tag1', 'tag2'}), ('M117 Foobar', None, 'M117', None, {'tag1', 'tag2'})]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", "M105", "M117 Foobar"], tags_to_add={"tag3"}) # doctest: +ALLOW_UNICODE
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", "M105", "M117 Foobar"], tags_to_add={"tag3"})
|
||||
[('M110', None, 'M110', None, {'tag1', 'tag2', 'tag3'}), ('M105', None, 'M105', None, {'tag1', 'tag2'}), ('M117 Foobar', None, 'M117', None, {'tag1', 'tag2', 'tag3'})]
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", ("M105", "temperature_poll"), "M117 Foobar"], tags_to_add={"tag3"}) # doctest: +ALLOW_UNICODE
|
||||
>>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", ("M105", "temperature_poll"), "M117 Foobar"], tags_to_add={"tag3"})
|
||||
[('M110', None, 'M110', None, {'tag1', 'tag2', 'tag3'}), ('M105', 'temperature_poll', 'M105', None, {'tag1', 'tag2', 'tag3'}), ('M117 Foobar', None, 'M117', None, {'tag1', 'tag2', 'tag3'})]
|
||||
|
||||
Arguments:
|
||||
|
||||
@@ -7,46 +7,55 @@ import logging
|
||||
import queue
|
||||
import re
|
||||
import time
|
||||
import warnings
|
||||
from typing import Dict, List, Tuple, Union
|
||||
|
||||
import sarge
|
||||
|
||||
from octoprint.util import to_bytes, to_unicode
|
||||
from octoprint.util.platform import CLOSE_FDS
|
||||
|
||||
from . import to_unicode
|
||||
|
||||
# These regexes are based on the colorama package
|
||||
# Author: Jonathan Hartley
|
||||
# License: BSD-3 (https://github.com/tartley/colorama/blob/master/LICENSE.txt)
|
||||
# Website: https://github.com/tartley/colorama/
|
||||
_ANSI_CSI_PATTERN = (
|
||||
b"\001?\033\\[(\\??(?:\\d|;)*)([a-zA-Z])\002?" # Control Sequence Introducer
|
||||
"\001?\033\\[(\\??(?:\\d|;)*)([a-zA-Z])\002?" # Control Sequence Introducer
|
||||
)
|
||||
_ANSI_OSC_PATTERN = b"\001?\033\\]((?:.|;)*?)(\x07)\002?" # Operating System Command
|
||||
_ANSI_REGEX = re.compile(b"|".join([_ANSI_CSI_PATTERN, _ANSI_OSC_PATTERN]))
|
||||
_ANSI_OSC_PATTERN = "\001?\033\\]((?:.|;)*?)(\x07)\002?" # Operating System Command
|
||||
_ANSI_PATTERN = "|".join([_ANSI_CSI_PATTERN, _ANSI_OSC_PATTERN])
|
||||
|
||||
_ANSI_REGEX = re.compile(_ANSI_PATTERN)
|
||||
|
||||
|
||||
def clean_ansi(line):
|
||||
def clean_ansi(line: Union[str, bytes]) -> Union[str, bytes]:
|
||||
"""
|
||||
Removes ANSI control codes from ``line``.
|
||||
|
||||
Note: This function also still supports an input of ``bytes``, leading to an
|
||||
``output`` of ``bytes``. This if for reasons of backwards compatibility only,
|
||||
should no longer be used and considered to be deprecated and to be removed in
|
||||
a future version of OctoPrint. A warning will be logged.
|
||||
|
||||
Parameters:
|
||||
line (bytes or str): the line to process
|
||||
line (str or bytes): the line to process
|
||||
|
||||
Returns:
|
||||
(bytes or str) The line without any ANSI control codes
|
||||
(str or bytes) The line without any ANSI control codes
|
||||
|
||||
Example::
|
||||
.. changed:: 1.8.0
|
||||
|
||||
>>> text = b"Some text with some \x1b[31mred words\x1b[39m in it"
|
||||
>>> clean_ansi(text) # doctest: +ALLOW_BYTES
|
||||
'Some text with some red words in it'
|
||||
>>> text = b"We \x1b[?25lhide the cursor here and then \x1b[?25hshow it again here"
|
||||
>>> clean_ansi(text) # doctest: +ALLOW_BYTES
|
||||
'We hide the cursor here and then show it again here'
|
||||
Usage as ``clean_ansi(line: bytes) -> bytes`` is now deprecated and will be removed
|
||||
in a future version of OctoPrint.
|
||||
"""
|
||||
if isinstance(line, str):
|
||||
return _ANSI_REGEX.sub(b"", line.encode("latin1")).decode("latin1")
|
||||
return _ANSI_REGEX.sub(b"", line)
|
||||
# TODO: bytes support is deprecated, remove in 2.0.0
|
||||
if isinstance(line, bytes):
|
||||
warnings.warn(
|
||||
"Calling clean_ansi with bytes is deprecated, call with str instead",
|
||||
DeprecationWarning,
|
||||
)
|
||||
return to_bytes(_ANSI_REGEX.sub("", to_unicode(line)))
|
||||
return _ANSI_REGEX.sub("", line)
|
||||
|
||||
|
||||
class CommandlineError(Exception):
|
||||
@@ -123,7 +132,9 @@ class CommandlineCaller:
|
||||
self.on_log_stderr = lambda *args, **kwargs: None
|
||||
"""Callback for stderr output"""
|
||||
|
||||
def checked_call(self, command, **kwargs):
|
||||
def checked_call(
|
||||
self, command: Union[str, List[str], Tuple[str]], **kwargs
|
||||
) -> Tuple[int, List[str], List[str]]:
|
||||
"""
|
||||
Calls a command and raises an error if it doesn't return with return code 0
|
||||
|
||||
@@ -145,7 +156,9 @@ class CommandlineCaller:
|
||||
|
||||
return returncode, stdout, stderr
|
||||
|
||||
def call(self, command, **kwargs):
|
||||
def call(
|
||||
self, command: Union[str, List[str], Tuple[str]], **kwargs: Dict[str, str]
|
||||
) -> Tuple[int, List[str], List[str]]:
|
||||
"""
|
||||
Calls a command
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ This module provides a bunch of utility methods and helpers FOR DEVELOPMENT ONLY
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
|
||||
import contextlib
|
||||
import time
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
@@ -26,8 +27,6 @@ def duration_log(context=None, log=None):
|
||||
|
||||
log = logging.getLogger(__name__).debug
|
||||
|
||||
import time
|
||||
|
||||
start = time.monotonic()
|
||||
try:
|
||||
yield
|
||||
|
||||
+26
-28
@@ -28,19 +28,20 @@ def sanitize_filename(name, really_universal=False):
|
||||
"""
|
||||
Sanitizes the provided filename. Implementation differs between Python versions.
|
||||
|
||||
On Python 2, the name will be ASCII-fied, using ``octoprint.util.text.sanitize`` with
|
||||
safe chars ``-_.()[] `` and all spaces replaced by ``_``.
|
||||
|
||||
On Python 3, ``pathvalidate.sanitize_filename`` will be used instead, leaving the
|
||||
Under normal operation, ``pathvalidate.sanitize_filename`` will be used, leaving the
|
||||
name as intact as possible while still being a legal file name under all operating
|
||||
systems.
|
||||
|
||||
Behaviour can be changed by setting ``really_universal`` to ``True``. In this case,
|
||||
the name will be ASCII-fied, using ``octoprint.util.text.sanitize`` with
|
||||
safe chars ``-_.()[] `` and all spaces replaced by ``_``. This is the old behaviour.
|
||||
|
||||
In all cases, a single leading ``.`` will be removed (as it denotes hidden files
|
||||
on *nix).
|
||||
|
||||
Args:
|
||||
name: The file name to sanitize. Only the name, no path elements.
|
||||
really_universal: If ``True``, the Python 2 method of sanitization will always
|
||||
really_universal: If ``True``, the old method of sanitization will always
|
||||
be used. Defaults to ``False``.
|
||||
|
||||
Returns:
|
||||
@@ -56,10 +57,7 @@ def sanitize_filename(name, really_universal=False):
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
try:
|
||||
from pathvalidate import sanitize_filename as sfn
|
||||
except ImportError:
|
||||
sfn = _sfn_really_universal
|
||||
from pathvalidate import sanitize_filename as sfn
|
||||
|
||||
if really_universal:
|
||||
result = _sfn_really_universal(name)
|
||||
@@ -98,24 +96,24 @@ def get_dos_filename(
|
||||
|
||||
Examples:
|
||||
|
||||
>>> get_dos_filename("test1234.gco") # doctest: +ALLOW_UNICODE
|
||||
>>> get_dos_filename("test1234.gco")
|
||||
'test1234.gco'
|
||||
>>> get_dos_filename("test1234.gcode") # doctest: +ALLOW_UNICODE
|
||||
>>> get_dos_filename("test1234.gcode")
|
||||
'test1234.gco'
|
||||
>>> get_dos_filename("test12345.gco") # doctest: +ALLOW_UNICODE
|
||||
>>> get_dos_filename("test12345.gco")
|
||||
'test12~1.gco'
|
||||
>>> get_dos_filename("Wölfe 🐺.gcode") # doctest: +ALLOW_UNICODE
|
||||
>>> get_dos_filename("Wölfe 🐺.gcode")
|
||||
'wolfe_~1.gco'
|
||||
>>> get_dos_filename("💚.gcode") # doctest: +ALLOW_UNICODE
|
||||
>>> get_dos_filename("💚.gcode")
|
||||
'green_~1.gco'
|
||||
>>> get_dos_filename("test1234.fnord", extension="gco") # doctest: +ALLOW_UNICODE
|
||||
>>> get_dos_filename("test1234.fnord", extension="gco")
|
||||
'test1234.gco'
|
||||
>>> get_dos_filename("auto0.g", extension="gco") # doctest: +ALLOW_UNICODE
|
||||
>>> get_dos_filename("auto0.g", extension="gco")
|
||||
'auto0.gco'
|
||||
>>> get_dos_filename("auto0.g", extension="gco", whitelisted_extensions=["g"]) # doctest: +ALLOW_UNICODE
|
||||
>>> get_dos_filename("auto0.g", extension="gco", whitelisted_extensions=["g"])
|
||||
'auto0.g'
|
||||
>>> get_dos_filename(None)
|
||||
>>> get_dos_filename("foo") # doctest: +ALLOW_UNICODE
|
||||
>>> get_dos_filename("foo")
|
||||
'foo'
|
||||
"""
|
||||
|
||||
@@ -189,30 +187,30 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power=
|
||||
|
||||
Examples:
|
||||
|
||||
>>> find_collision_free_name("test1234", "gco", []) # doctest: +ALLOW_UNICODE
|
||||
>>> find_collision_free_name("test1234", "gco", [])
|
||||
'test1234.gco'
|
||||
>>> find_collision_free_name("test1234", "gcode", []) # doctest: +ALLOW_UNICODE
|
||||
>>> find_collision_free_name("test1234", "gcode", [])
|
||||
'test1234.gco'
|
||||
>>> find_collision_free_name("test12345", "gco", []) # doctest: +ALLOW_UNICODE
|
||||
>>> find_collision_free_name("test12345", "gco", [])
|
||||
'test12~1.gco'
|
||||
>>> find_collision_free_name("test 123", "gco", []) # doctest: +ALLOW_UNICODE
|
||||
>>> find_collision_free_name("test 123", "gco", [])
|
||||
'test_123.gco'
|
||||
>>> find_collision_free_name("test1234", "g o", []) # doctest: +ALLOW_UNICODE
|
||||
>>> find_collision_free_name("test1234", "g o", [])
|
||||
'test1234.g_o'
|
||||
>>> find_collision_free_name("test12345", "gco", ["/test12~1.gco"]) # doctest: +ALLOW_UNICODE
|
||||
>>> find_collision_free_name("test12345", "gco", ["/test12~1.gco"])
|
||||
'test12~2.gco'
|
||||
>>> many_files = ["/test12~{}.gco".format(x) for x in range(10)[1:]]
|
||||
>>> find_collision_free_name("test12345", "gco", many_files) # doctest: +ALLOW_UNICODE
|
||||
>>> find_collision_free_name("test12345", "gco", many_files)
|
||||
'test1~10.gco'
|
||||
>>> many_more_files = many_files + ["/test1~{}.gco".format(x) for x in range(10, 99)]
|
||||
>>> find_collision_free_name("test12345", "gco", many_more_files) # doctest: +ALLOW_UNICODE
|
||||
>>> find_collision_free_name("test12345", "gco", many_more_files)
|
||||
'test1~99.gco'
|
||||
>>> many_more_files_plus_one = many_more_files + ["/test1~99.gco"]
|
||||
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one) # doctest: +ALLOW_UNICODE
|
||||
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: Can't create a collision free filename
|
||||
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one, max_power=3) # doctest: +ALLOW_UNICODE
|
||||
>>> find_collision_free_name("test12345", "gco", many_more_files_plus_one, max_power=3)
|
||||
'test~100.gco'
|
||||
|
||||
"""
|
||||
|
||||
@@ -3,7 +3,6 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
|
||||
import logging
|
||||
import os
|
||||
from os import walk
|
||||
|
||||
from jinja2 import nodes
|
||||
from jinja2.ext import Extension
|
||||
@@ -149,7 +148,7 @@ class WarningLoader(BaseLoader):
|
||||
def get_all_template_paths(loader):
|
||||
def walk_folder(folder):
|
||||
files = []
|
||||
walk_dir = walk(folder, followlinks=True)
|
||||
walk_dir = os.walk(folder, followlinks=True)
|
||||
for dirpath, _, filenames in walk_dir:
|
||||
for filename in filenames:
|
||||
path = os.path.join(dirpath, filename)
|
||||
@@ -290,8 +289,8 @@ class MarkdownFilter:
|
||||
app.jinja_env.filters.setdefault("markdown", self)
|
||||
|
||||
def __call__(self, stream):
|
||||
from jinja2 import Markup
|
||||
from markdown import Markdown
|
||||
from markupsafe import Markup
|
||||
|
||||
# Markdown is not thread safe
|
||||
markdown = Markdown(**self._markdown_options)
|
||||
|
||||
+34
-16
@@ -4,6 +4,7 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
|
||||
import netaddr
|
||||
import netifaces
|
||||
@@ -39,8 +40,13 @@ if hasattr(socket, "IPPROTO_IPV6") and hasattr(socket, "IPV6_V6ONLY"):
|
||||
IPPROTO_IPV6 = socket.IPPROTO_IPV6
|
||||
IPV6_V6ONLY = socket.IPV6_V6ONLY
|
||||
else:
|
||||
# Whatever we are running on here, we don't want to use V6 on here due to lack of dual stack support
|
||||
HAS_V6 = False
|
||||
if sys.platform == "win32":
|
||||
# Python 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, we don't want to use V6 on here due to lack of dual stack support
|
||||
HAS_V6 = False
|
||||
|
||||
|
||||
def get_lan_ranges(additional_private=None):
|
||||
@@ -154,7 +160,7 @@ def unmap_v4_as_v6(address):
|
||||
return address
|
||||
|
||||
|
||||
def interface_addresses(family=None, interfaces=None):
|
||||
def interface_addresses(family=None, interfaces=None, ignored=None):
|
||||
"""
|
||||
Retrieves all of the host's network interface addresses.
|
||||
"""
|
||||
@@ -167,6 +173,9 @@ def interface_addresses(family=None, interfaces=None):
|
||||
if interfaces is None:
|
||||
interfaces = netifaces.interfaces()
|
||||
|
||||
if ignored is not None:
|
||||
interfaces = [i for i in interfaces if i not in ignored]
|
||||
|
||||
for interface in interfaces:
|
||||
try:
|
||||
ifaddresses = netifaces.ifaddresses(interface)
|
||||
@@ -179,13 +188,15 @@ def interface_addresses(family=None, interfaces=None):
|
||||
yield ifaddress["addr"]
|
||||
|
||||
|
||||
def address_for_client(host, port, timeout=3.05, addresses=None, interfaces=None):
|
||||
def address_for_client(
|
||||
host, port, timeout=3.05, addresses=None, interfaces=None, ignored=None
|
||||
):
|
||||
"""
|
||||
Determines the address of the network interface on this host needed to connect to the indicated client host and port.
|
||||
"""
|
||||
|
||||
if addresses is None:
|
||||
addresses = interface_addresses(interfaces=interfaces)
|
||||
addresses = interface_addresses(interfaces=interfaces, ignored=ignored)
|
||||
|
||||
for address in addresses:
|
||||
try:
|
||||
@@ -215,17 +226,24 @@ def server_reachable(host, port, timeout=3.05, proto="tcp", source=None):
|
||||
if proto not in ("tcp", "udp"):
|
||||
raise ValueError("proto must be either 'tcp' or 'udp'")
|
||||
|
||||
try:
|
||||
sock = socket.socket(
|
||||
socket.AF_INET, socket.SOCK_DGRAM if proto == "udp" else socket.SOCK_STREAM
|
||||
)
|
||||
sock.settimeout(timeout)
|
||||
if source is not None:
|
||||
sock.bind((source, 0))
|
||||
sock.connect((host, port))
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
if HAS_V6:
|
||||
families = [socket.AF_INET6, socket.AF_INET]
|
||||
else:
|
||||
families = [socket.AF_INET]
|
||||
|
||||
for family in families:
|
||||
try:
|
||||
sock = socket.socket(
|
||||
family, socket.SOCK_DGRAM if proto == "udp" else socket.SOCK_STREAM
|
||||
)
|
||||
sock.settimeout(timeout)
|
||||
if source is not None:
|
||||
sock.bind((source, 0))
|
||||
sock.connect((host, port))
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def resolve_host(host):
|
||||
|
||||
+124
-9
@@ -8,11 +8,11 @@ import os
|
||||
import site
|
||||
import sys
|
||||
import threading
|
||||
from typing import List
|
||||
|
||||
import pkg_resources
|
||||
import sarge
|
||||
|
||||
from octoprint.util import to_unicode
|
||||
from octoprint.util.platform import CLOSE_FDS
|
||||
|
||||
from .commandline import CommandlineCaller, clean_ansi
|
||||
@@ -21,6 +21,121 @@ _cache = {"version": {}, "setup": {}}
|
||||
_cache_mutex = threading.RLock()
|
||||
|
||||
|
||||
OUTPUT_SUCCESS = "Successfully installed"
|
||||
"""Start of successful result line"""
|
||||
|
||||
OUTPUT_FAILURE = "Could not install"
|
||||
"""Start of failure result line"""
|
||||
|
||||
OUTPUT_ALREADY_INSTALLED = "Requirement already satisfied"
|
||||
"""Start of a line indicating some package was already installed in this version"""
|
||||
|
||||
OUTPUT_PYTHON_MISMATCH = "requires a different Python:"
|
||||
"""Line segment indicating a mismatch of python_requires version"""
|
||||
|
||||
OUTPUT_PYTHON_SYNTAX = "SyntaxError: invalid syntax"
|
||||
"""Line segment indicating a syntax error, could be a python mismatch, e.g. f-strings"""
|
||||
|
||||
OUTPUT_POTENTIAL_EGG_PROBLEM_POSIX = "No such file or directory"
|
||||
"""Line indicating a potential egg problem on Posix"""
|
||||
|
||||
OUTPUT_POTENTIAL_EGG_PROBLEM_WINDOWS = "The system cannot find the file specified"
|
||||
"""Line indicating a potential egg problem on Windows"""
|
||||
|
||||
|
||||
def is_already_installed(lines):
|
||||
"""
|
||||
Returns whether the given output lines indicates the packages was already installed
|
||||
or not.
|
||||
|
||||
This is currently determined by an empty result line and any line starting with
|
||||
"Requirement already satisfied".
|
||||
|
||||
Args:
|
||||
lines (list of str): the output to parse, stdout or stderr
|
||||
|
||||
Returns:
|
||||
bool: True if detected, False otherwise
|
||||
"""
|
||||
result_line = get_result_line(lines) # neither success nor failure reported
|
||||
return not result_line and any(
|
||||
line.strip().startswith(OUTPUT_ALREADY_INSTALLED) for line in lines
|
||||
)
|
||||
|
||||
|
||||
def is_python_mismatch(lines):
|
||||
"""
|
||||
Returns whether the given output lines indicates a Python version mismatch.
|
||||
|
||||
This is currently determined by either a syntax error or an explicit "requires a
|
||||
different Python" line.
|
||||
|
||||
Args:
|
||||
lines (list of str): the output to parse, stdout or stderr
|
||||
|
||||
Returns:
|
||||
bool: True if detected, False otherwise
|
||||
"""
|
||||
return any(
|
||||
OUTPUT_PYTHON_MISMATCH in line or OUTPUT_PYTHON_SYNTAX in line for line in lines
|
||||
)
|
||||
|
||||
|
||||
def is_egg_problem(lines):
|
||||
"""
|
||||
Returns whether the given output lines indicates an occurence of the "egg-problem".
|
||||
|
||||
If something (target or dependency of target) was installed as an egg at an earlier
|
||||
date (e.g. thanks to just running python setup.py install), pip install will throw an
|
||||
error after updating that something to a newer (non-egg) version since it will still
|
||||
have the egg on its sys.path and expect to read data from it.
|
||||
|
||||
See commit 8ad0aadb52b9ef354cad1b33bd4882ae2fbdb8d6 for more details.
|
||||
|
||||
Args:
|
||||
lines (list of str): the output to parse, stdout or stderr
|
||||
|
||||
Returns:
|
||||
bool: True if detected, False otherwise
|
||||
"""
|
||||
return any(
|
||||
".egg" in line
|
||||
and (
|
||||
OUTPUT_POTENTIAL_EGG_PROBLEM_POSIX in line
|
||||
or OUTPUT_POTENTIAL_EGG_PROBLEM_WINDOWS in line
|
||||
)
|
||||
for line in lines
|
||||
)
|
||||
|
||||
|
||||
def get_result_line(lines):
|
||||
"""
|
||||
Returns the success or failure line contained in the output.
|
||||
|
||||
pip might generate more lines after the actual result line, which is why
|
||||
we can't just take the final line. So instead we look for the last line
|
||||
starting with either "Successfully installed" or "Could not installed".
|
||||
If neither can be found, an empty string will be returned, which should also
|
||||
be considered a failure to install.
|
||||
|
||||
Args:
|
||||
lines (list of str): the output to parse, stdout or stderr
|
||||
|
||||
Returns:
|
||||
str: the last result line, or an empty string if none was found, in which case
|
||||
failure should be resumed
|
||||
"""
|
||||
possible_results = list(
|
||||
filter(
|
||||
lambda x: x.startswith(OUTPUT_SUCCESS) or x.startswith(OUTPUT_FAILURE),
|
||||
lines,
|
||||
)
|
||||
)
|
||||
if not possible_results:
|
||||
return ""
|
||||
return possible_results[-1]
|
||||
|
||||
|
||||
class UnknownPip(Exception):
|
||||
pass
|
||||
|
||||
@@ -489,27 +604,27 @@ class PipCaller(CommandlineCaller):
|
||||
)
|
||||
return False, False, False, None
|
||||
|
||||
def _preprocess_lines(self, *lines):
|
||||
def _preprocess_lines(self, *lines: List[str]) -> List[str]:
|
||||
return list(map(self._preprocess, lines))
|
||||
|
||||
@staticmethod
|
||||
def _preprocess(text):
|
||||
def _preprocess(text: str) -> str:
|
||||
"""
|
||||
Strips ANSI and VT100 cursor control characters from line and makes sure it's a unicode.
|
||||
Strips ANSI and VT100 cursor control characters from line.
|
||||
|
||||
Parameters:
|
||||
text (str or unicode): The text to process
|
||||
text (str): The text to process
|
||||
|
||||
Returns:
|
||||
(unicode) The processed text as a unicode, stripped of ANSI and VT100 cursor show/hide codes
|
||||
(str) The processed text, stripped of ANSI and VT100 cursor show/hide codes
|
||||
|
||||
Example::
|
||||
|
||||
>>> text = b'some text with some\x1b[?25h ANSI codes for \x1b[31mred words\x1b[39m and\x1b[?25l also some cursor control codes'
|
||||
>>> PipCaller._preprocess(text) # doctest: +ALLOW_UNICODE
|
||||
>>> text = 'some text with some\x1b[?25h ANSI codes for \x1b[31mred words\x1b[39m and\x1b[?25l also some cursor control codes'
|
||||
>>> PipCaller._preprocess(text)
|
||||
'some text with some ANSI codes for red words and also some cursor control codes'
|
||||
"""
|
||||
return to_unicode(clean_ansi(text))
|
||||
return clean_ansi(text)
|
||||
|
||||
|
||||
class LocalPipCaller(PipCaller):
|
||||
|
||||
@@ -60,15 +60,9 @@ CLOSE_FDS = True
|
||||
Default setting for close_fds parameter to Popen/sarge.run.
|
||||
|
||||
Set ``close_fds`` on every sub process to this to ensure file handlers will be closed
|
||||
on child processes on platforms that support this (anything Python 3.7+ or anything
|
||||
but win32 in earlier Python versions).
|
||||
on child processes on platforms.
|
||||
"""
|
||||
|
||||
if sys.platform == "win32" and sys.version_info < (3, 7):
|
||||
# close_fds=True is only supported on win32 with enabled stdout/stderr
|
||||
# capturing starting with Python 3.7
|
||||
CLOSE_FDS = False
|
||||
|
||||
# current os
|
||||
|
||||
_OPERATING_SYSTEMS = {
|
||||
|
||||
@@ -24,15 +24,15 @@ def sanitize(text, safe_chars="-_.", demoji=True):
|
||||
|
||||
Examples:
|
||||
|
||||
>>> sanitize("Hello World!") # doctest: +ALLOW_UNICODE
|
||||
>>> sanitize("Hello World!")
|
||||
'Hello-World'
|
||||
>>> sanitize("Hello World!", safe_chars="-_. ") # doctest: +ALLOW_UNICODE
|
||||
>>> sanitize("Hello World!", safe_chars="-_. ")
|
||||
'Hello World'
|
||||
>>> sanitize("\u2764") # doctest: +ALLOW_UNICODE
|
||||
>>> sanitize("\u2764")
|
||||
'red_heart'
|
||||
>>> sanitize("\u2764\ufe00") # doctest: +ALLOW_UNICODE
|
||||
>>> sanitize("\u2764\ufe00")
|
||||
'red_heart'
|
||||
>>> sanitize("\u2764", demoji=False) # doctest: +ALLOW_UNICODE
|
||||
>>> sanitize("\u2764", demoji=False)
|
||||
''
|
||||
|
||||
Args:
|
||||
|
||||
@@ -219,8 +219,6 @@ def is_prerelease(version):
|
||||
|
||||
|
||||
def normalize_version(version):
|
||||
if "-" in version:
|
||||
version = version[: version.find("-")]
|
||||
|
||||
# Debian has the python version set to 2.7.15+ which is not PEP440 compliant (bug 914072)
|
||||
if version.endswith("+"):
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
def load_from_file(file=None, path=None):
|
||||
from typing import Any, Dict, Hashable, TextIO, Union
|
||||
|
||||
|
||||
def load_from_file(
|
||||
file: TextIO = None, path: str = None
|
||||
) -> Union[Dict[Hashable, Any], list, None]:
|
||||
"""
|
||||
Safely and performantly loads yaml data from the given source. Either a
|
||||
path or a file must be passed in.
|
||||
|
||||
:rtype: Union[dict[Hashable, Any], list, None]
|
||||
:type path: str | None
|
||||
:type file: typing.TextIO | None
|
||||
"""
|
||||
if path is not None:
|
||||
assert file is None
|
||||
|
||||
Vendored
+1
-1
@@ -241,7 +241,7 @@ def load_module(name, file, filename, details):
|
||||
elif type_ == PY_FROZEN:
|
||||
return init_frozen(name)
|
||||
else:
|
||||
msg = "Don't know how to import {} (type code {})".format(name, type_)
|
||||
msg = "Don't know how to import {} (type code {})".format(name, type_)
|
||||
raise ImportError(msg, name=name)
|
||||
|
||||
|
||||
|
||||
+2
-8
@@ -15,19 +15,13 @@ import logging
|
||||
from tornado.web import RequestHandler
|
||||
from tornado.gen import coroutine
|
||||
|
||||
try:
|
||||
# python 3
|
||||
# noinspection PyCompatibility
|
||||
from urllib.parse import urlparse
|
||||
except ImportError:
|
||||
# python 2
|
||||
# noinspection PyCompatibility
|
||||
from urlparse import urlparse
|
||||
from urllib.parse import urlparse
|
||||
|
||||
CACHE_TIME = 31536000
|
||||
|
||||
LOG = logging.getLogger("tornado.general")
|
||||
|
||||
|
||||
class BaseHandler(RequestHandler):
|
||||
"""Base request handler with set of helpers."""
|
||||
def initialize(self, server):
|
||||
|
||||
+1
-4
@@ -4,10 +4,7 @@ from __future__ import absolute_import, division, print_function, unicode_litera
|
||||
import tornado
|
||||
from tornado import escape, gen, websocket
|
||||
|
||||
try:
|
||||
from urllib.parse import urlparse # py3
|
||||
except ImportError:
|
||||
from urlparse import urlparse # py2
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
||||
class SockJSWebSocketHandler(websocket.WebSocketHandler):
|
||||
|
||||
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user