Merge branch 'devel' into dev/commRefactoringNG
This commit is contained in:
commit
741fac4396
123 files changed
+1733
-1741
No files matched your search
@@ -30,8 +30,8 @@ jobs:
|
||||
name: dist
|
||||
path: dist
|
||||
|
||||
lint-black:
|
||||
name: 🧹 black
|
||||
pre-commit:
|
||||
name: 🧹 Pre-commit
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
@@ -42,79 +42,15 @@ jobs:
|
||||
- name: 🏗 Set up dev dependencies
|
||||
run: |
|
||||
pip install -e .[develop]
|
||||
- name: 🚀 Run black
|
||||
- name: 🚀 Run pre-commit
|
||||
run: |
|
||||
pre-commit run --hook-stage manual black --all-files --show-diff-on-failure
|
||||
|
||||
lint-isort:
|
||||
name: 🧹 isort
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: 🏗 Set up Python 3.7
|
||||
uses: actions/setup-python@v1
|
||||
with:
|
||||
python-version: 3.7
|
||||
- name: 🏗 Set up dev dependencies
|
||||
run: |
|
||||
pip install -e .[develop]
|
||||
- name: 🚀 Run isort
|
||||
run: |
|
||||
pre-commit run --hook-stage manual isort --all-files --show-diff-on-failure
|
||||
|
||||
lint-flake8:
|
||||
name: 🧹 Flake8
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: 🏗 Set up Python 3.7
|
||||
uses: actions/setup-python@v1
|
||||
with:
|
||||
python-version: 3.7
|
||||
- name: 🏗 Set up dev dependencies
|
||||
run: |
|
||||
pip install -e .[develop]
|
||||
- name: 🚀 Run flake8
|
||||
run: |
|
||||
pre-commit run --hook-stage manual flake8 --all-files
|
||||
|
||||
lint-prettier:
|
||||
name: 🧹 prettier
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: 🏗 Set up Python 3.7
|
||||
uses: actions/setup-python@v1
|
||||
with:
|
||||
python-version: 3.7
|
||||
- name: 🏗 Set up dev dependencies
|
||||
run: |
|
||||
pip install -e .[develop]
|
||||
- name: 🚀 Run prettier
|
||||
run: |
|
||||
pre-commit run --hook-stage manual prettier --all-files --show-diff-on-failure
|
||||
|
||||
lint-eslint:
|
||||
name: 🧹 eslint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: 🏗 Set up Python 3.7
|
||||
uses: actions/setup-python@v1
|
||||
with:
|
||||
python-version: 3.7
|
||||
- name: 🏗 Set up dev dependencies
|
||||
run: |
|
||||
pip install -e .[develop]
|
||||
- name: 🚀 Run eslint
|
||||
run: |
|
||||
pre-commit run --hook-stage manual eslint --all-files
|
||||
pre-commit run --all-files --show-diff-on-failure
|
||||
|
||||
test-unit:
|
||||
name: 🧪 Unit tests
|
||||
strategy:
|
||||
matrix:
|
||||
python: ["3.7", "3.8"]
|
||||
python: ["3.7", "3.8", "3.9"]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
@@ -134,7 +70,7 @@ jobs:
|
||||
needs: build
|
||||
strategy:
|
||||
matrix:
|
||||
python: ["3.7", "3.8"]
|
||||
python: ["3.7", "3.8", "3.9"]
|
||||
installable: ["wheel", "sdist"]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -207,11 +143,7 @@ jobs:
|
||||
name: 📦 Publish on TestPyPI
|
||||
if: github.event_name == 'release'
|
||||
needs:
|
||||
- lint-black
|
||||
- lint-isort
|
||||
- lint-flake8
|
||||
- lint-prettier
|
||||
- lint-eslint
|
||||
- pre-commit
|
||||
- test-unit
|
||||
- test-install
|
||||
- test-e2e
|
||||
|
||||
@@ -14,7 +14,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
os: ["ubuntu-latest"]
|
||||
python: ["3.7", "3.8"]
|
||||
python: ["3.7", "3.8", "3.9"]
|
||||
branch: ["master"]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
@@ -49,7 +49,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
os: ["ubuntu-latest"]
|
||||
python: ["3.7", "3.8"]
|
||||
python: ["3.7", "3.8", "3.9"]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: 👀 Determine latest release
|
||||
|
||||
+5
-18
@@ -12,35 +12,22 @@ repos:
|
||||
- id: check-merge-conflict
|
||||
- id: fix-encoding-pragma
|
||||
args: ["--remove"]
|
||||
- repo: https://github.com/asottile/pyupgrade
|
||||
rev: v2.10.0
|
||||
hooks:
|
||||
- id: pyupgrade
|
||||
args: ["--py37-plus"]
|
||||
- repo: https://github.com/OctoPrint/codemods
|
||||
rev: 0.4.0
|
||||
hooks:
|
||||
- id: codemod_detect_past_builtins_imports
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- id: codemod_dict_comprehension_to_literal
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- id: codemod_dict_to_literal
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- id: codemod_not_in
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- id: codemod_oserror_merge
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- id: codemod_py3_class_inheritance
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- id: codemod_py3_super
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- id: codemod_remove_builtins_imports
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- id: codemod_remove_float_conversion
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- id: codemod_remove_future_imports
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- id: codemod_set_to_literal
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- id: codemod_string_encoding
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- id: codemod_yield_from_generator
|
||||
args: ["--ignore", "src/octoprint/vendor"]
|
||||
- repo: https://github.com/pre-commit/mirrors-isort
|
||||
rev: v5.5.4
|
||||
hooks:
|
||||
|
||||
@@ -138,6 +138,9 @@ date of first contribution):
|
||||
* [Nils Hofmann](https://github.com/Master92)
|
||||
* [Miroslav Šedivý](https://github.com/eumiro)
|
||||
* [Costas Basdekis](https://github.com/costas-basdekis)
|
||||
* [Joe Martella](https://github.com/martellaj)
|
||||
* [Scott Lahteine](https://github.com/thinkyhead)
|
||||
* [Karthikeyan Singaravelan](https://github.com/tirkarthi)
|
||||
|
||||
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
|
||||
|
||||
+2
-1
@@ -51,7 +51,7 @@ into one ticket: One ticket per bug, request, brainstorming thread please.
|
||||
## How to file a bug report
|
||||
|
||||
If you encounter an issue with OctoPrint, you are welcome to
|
||||
[submit a bug report](https://github.com/foosel/OctoPrint/issues/new).
|
||||
[submit a bug report](https://github.com/OctoPrint/OctoPrint/issues/new?template=bug_report.yml).
|
||||
|
||||
Before you do that for the first time though please take a moment to read the
|
||||
following section *completely* and also follow the instructions in the
|
||||
@@ -287,6 +287,7 @@ See [the corresponding chapter in the documentation](https://docs.octoprint.org/
|
||||
* 2020-09-23: Move branch & versioning into development docs
|
||||
* 2020-10-07: Introduce `pre-commit`
|
||||
* 2021-02-04: Issue forms! \o/
|
||||
* 2020-03-04: Correct issue forms link
|
||||
|
||||
## Footnotes
|
||||
* [1] - If you are wondering why, the problem is that anything that you add
|
||||
|
||||
+6
-2
@@ -14,7 +14,8 @@ Retrieve all files
|
||||
.. http:get:: /api/files
|
||||
|
||||
Retrieve information regarding all files currently available and regarding the disk space still available
|
||||
locally in the system.
|
||||
locally in the system. The results are cached for performance reasons. If you
|
||||
want to override the cache, supply the query parameter ``force`` and set it to ``true``.
|
||||
|
||||
By default only returns the files and folders in the root directory. If the query parameter ``recursive``
|
||||
is provided and set to ``true``, returns all files and folders.
|
||||
@@ -234,6 +235,7 @@ Retrieve all files
|
||||
"free": "3.2GB"
|
||||
}
|
||||
|
||||
:param force: If set to ``true``, forces a refresh, overriding the cache.
|
||||
:param recursive: If set to ``true``, return all files and folders recursively. Otherwise only return items on same level.
|
||||
:statuscode 200: No error
|
||||
|
||||
@@ -245,7 +247,8 @@ Retrieve files from specific location
|
||||
.. http:get:: /api/files/(string:location)
|
||||
|
||||
Retrieve information regarding the files currently available on the selected `location` and -- if targeting
|
||||
the ``local`` location -- regarding the disk space still available locally in the system.
|
||||
the ``local`` location -- regarding the disk space still available locally in the system. The results are cached for performance reasons. If you
|
||||
want to override the cache, supply the query parameter ``force`` and set it to ``true``.
|
||||
|
||||
By default only returns the files and folders in the root directory. If the query parameter ``recursive``
|
||||
is provided and set to ``true``, returns all files and folders.
|
||||
@@ -305,6 +308,7 @@ Retrieve files from specific location
|
||||
:param location: The origin location from which to retrieve the files. Currently only ``local`` and ``sdcard`` are
|
||||
supported, with ``local`` referring to files stored in OctoPrint's ``uploads`` folder and ``sdcard``
|
||||
referring to files stored on the printer's SD card (if available).
|
||||
:param force: If set to ``true``, forces a refresh, overriding the cache.
|
||||
:param recursive: If set to ``true``, return all files and folders recursively. Otherwise only return items on same level.
|
||||
:statuscode 200: No error
|
||||
:statuscode 404: If `location` is neither ``local`` nor ``sdcard``
|
||||
|
||||
@@ -1132,9 +1132,9 @@ Use `Javascript regular expressions <https://developer.mozilla.org/en/docs/Web/J
|
||||
# A list of filters to display in the terminal tab. Defaults to the filters shown below
|
||||
terminalFilters:
|
||||
- name: Suppress temperature messages
|
||||
regex: '(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?.*(B|T\d*):\d+)'
|
||||
regex: '(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+([PBN]\d+\s+)*)?([BCLPR]|T\d*):-?\d+)'
|
||||
- name: Suppress SD status messages
|
||||
regex: '(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)'
|
||||
regex: '(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)|(Recv: Not SD printing)'
|
||||
- name: Suppress wait responses
|
||||
regex: 'Recv: wait'
|
||||
- name: Suppress processing responses
|
||||
|
||||
@@ -71,7 +71,7 @@ If you also want to be able to build the documentation that resides in the ``doc
|
||||
the *Python 3* environment and install the docs dependencies as well:
|
||||
|
||||
* ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
|
||||
* ``pip install -e .[develop,plugins,docs]``
|
||||
* ``pip install -e '.[develop,plugins,docs]'``
|
||||
|
||||
Go to the directory `docs` and you can then build the documentation:
|
||||
|
||||
@@ -112,7 +112,7 @@ Then:
|
||||
virtualenv --python=python3 venv
|
||||
source ./venv/bin/activate
|
||||
pip install --upgrade pip
|
||||
pip install -e .[develop,plugins,docs]
|
||||
pip install -e '.[develop,plugins,docs]'
|
||||
pre-commit install
|
||||
git config blame.ignoreRevsFile .git-blame-ignore-revs
|
||||
|
||||
@@ -153,7 +153,7 @@ Open the Git Bash you just installed and in that:
|
||||
virtualenv --python=C:\Python38\python.exe venv
|
||||
source ./venv/Scripts/activate
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install -e .[develop,plugins,docs]
|
||||
python -m pip install -e '.[develop,plugins,docs]'
|
||||
pre-commit install
|
||||
git config blame.ignoreRevsFile .git-blame-ignore-revs
|
||||
|
||||
@@ -229,7 +229,7 @@ You'll need a user account with administrator privileges.
|
||||
virtualenv venv
|
||||
source venv/bin/activate
|
||||
pip install --upgrade pip
|
||||
pip install -e .[develop,plugins]
|
||||
pip install -e '.[develop,plugins]'
|
||||
pre-commit install
|
||||
git config blame.ignoreRevsFile .git-blame-ignore-revs
|
||||
|
||||
@@ -277,7 +277,7 @@ PyCharm
|
||||
|
||||
* Name: Update OctoPrint dependencies
|
||||
* Program: ``$ModuleSdkPath$``
|
||||
* Parameters: ``-m pip install -e .[develop,plugins]``
|
||||
* Parameters: ``-m pip install -e '.[develop,plugins]'``
|
||||
* Working directory: ``$ProjectFileDir$``
|
||||
|
||||
Note that sadly that seems to cause some hiccups on current PyCharm versions due to ``$PyInterpreterDirectory$``
|
||||
@@ -306,7 +306,7 @@ PyCharm
|
||||
the documentation, see above on how to set this up.
|
||||
|
||||
Note that this requires you to also have installed the additional ``docs`` dependencies into the Python 3 venv as
|
||||
described above via ``pip install -e .[develop,plugins,docs]``.
|
||||
described above via ``pip install -e '.[develop,plugins,docs]'``.
|
||||
|
||||
- Settings > Tools > File Watchers (you might have to enable this, it's a bundled plugin), add new:
|
||||
|
||||
|
||||
@@ -54,6 +54,27 @@ resumed
|
||||
disconnect
|
||||
When this command is received from the printer, OctoPrint will immediately disconnect from it.
|
||||
|
||||
sd_inserted
|
||||
When this command is received from the printer, OctoPrint will assume an SD card is present in the printer,
|
||||
set the corresponding internal state flags and send a file list request. This command is only recognized
|
||||
if SD support is enabled in OctoPrint.
|
||||
|
||||
.. versionadded:: 1.6.0
|
||||
|
||||
sd_ejected
|
||||
When this command is received from the printer, OctoPrint will assume the SD card has been removed from
|
||||
the printer and clear the corresponding internal state flags. This command is only recognized
|
||||
if SD support is enabled in OctoPrint.
|
||||
|
||||
.. versionadded:: 1.6.0
|
||||
|
||||
sd_updated
|
||||
When this command is received from the printer, OctoPrint will assume something on the SD card in the
|
||||
printer has changed and trigger a file list request. This command is only recognized
|
||||
if SD support is enabled in OctoPrint.
|
||||
|
||||
.. versionadded:: 1.6.0
|
||||
|
||||
If the bundled :ref:`Action Command Prompt Support Plugin <sec-bundledplugins-action_command_prompt>` is enabled (which
|
||||
should be the case by default), OctoPrint will also interactive dialog creation through its :ref:`supported commands <sec-bundledplugins-action_command_prompt-action_commands>`.
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ INSTALL_REQUIRES = [
|
||||
"websocket-client>=0.57,<1",
|
||||
"wrapt>=1.12.1,<2",
|
||||
"emoji>=0.5.4,<1",
|
||||
"frozendict>=1.2,<2",
|
||||
"immutabledict>=1.2.0,<2",
|
||||
"sentry-sdk>=0.15.1,<1",
|
||||
"filetype>=1.0.7,<2",
|
||||
"zeroconf>=0.24,<0.25",
|
||||
@@ -134,7 +134,7 @@ def md_to_html_build_py_factory(files, baseclass):
|
||||
source = entry
|
||||
dest = os.path.join(target_dir, source + ".html")
|
||||
|
||||
print("Rendering markdown from {} to {}".format(source, dest))
|
||||
print(f"Rendering markdown from {source} to {dest}")
|
||||
|
||||
from markdown import markdownFromFile
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
import io
|
||||
import logging as log
|
||||
import os
|
||||
import sys
|
||||
@@ -373,7 +372,7 @@ def init_logging(
|
||||
if os.path.exists(logging_file) and os.path.isfile(logging_file):
|
||||
import yaml
|
||||
|
||||
with io.open(logging_file, "rt", encoding="utf-8") as f:
|
||||
with open(logging_file, encoding="utf-8") as f:
|
||||
config_from_file = yaml.safe_load(f)
|
||||
|
||||
# we merge that with the default config
|
||||
@@ -403,7 +402,7 @@ def octoprint_plugin_inject_factory(settings, components):
|
||||
def wrapper(*args, **kwargs):
|
||||
tags = kwargs.get("tags", set()) | {
|
||||
"source:plugin",
|
||||
"plugin:{}".format(name),
|
||||
f"plugin:{name}",
|
||||
}
|
||||
kwargs["tags"] = tags
|
||||
return f(*args, **kwargs)
|
||||
@@ -528,7 +527,7 @@ def init_custom_events(plugin_manager):
|
||||
if isinstance(result, (list, tuple)):
|
||||
for event in result:
|
||||
constant, value = octoprint.events.Events.register_event(
|
||||
event, prefix="plugin_{}_".format(name)
|
||||
event, prefix=f"plugin_{name}_"
|
||||
)
|
||||
logger.debug(
|
||||
'Registered event {} of plugin {} as Events.{} = "{}"'.format(
|
||||
@@ -537,7 +536,7 @@ def init_custom_events(plugin_manager):
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Error while retrieving custom event list from plugin {}".format(name),
|
||||
f"Error while retrieving custom event list from plugin {name}",
|
||||
extra={"plugin": name},
|
||||
)
|
||||
|
||||
@@ -664,7 +663,7 @@ def init_pluginsystem(
|
||||
disabled_from_overlays[name] = (disabled_plugins, order)
|
||||
|
||||
settings_overlays[name] = overlay
|
||||
logger.debug("Found settings overlay on plugin {}".format(name))
|
||||
logger.debug(f"Found settings overlay on plugin {name}")
|
||||
|
||||
def handle_plugins_loaded(
|
||||
startup=False, initialize_implementations=True, force_reload=None
|
||||
@@ -706,7 +705,7 @@ def init_pluginsystem(
|
||||
def handle_plugin_enabled(name, plugin):
|
||||
if name in settings_overlays:
|
||||
settings.add_overlay(settings_overlays[name])
|
||||
logger.info("Added settings overlay from plugin {}".format(name))
|
||||
logger.info(f"Added settings overlay from plugin {name}")
|
||||
|
||||
pm.on_plugin_loaded = handle_plugin_loaded
|
||||
pm.on_plugins_loaded = handle_plugins_loaded
|
||||
@@ -735,7 +734,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
format_entry = (
|
||||
lambda x: "{} ({})".format(x[0], x[1])
|
||||
if isinstance(x, (list, tuple)) and len(x) == 2
|
||||
else "{} (any)".format(x)
|
||||
else f"{x} (any)"
|
||||
)
|
||||
return ", ".join(map(format_entry, entries))
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
"""Git implementation of _version.py."""
|
||||
|
||||
import errno
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
@@ -97,7 +96,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
|
||||
return None
|
||||
else:
|
||||
if verbose:
|
||||
print("unable to find command, tried %s" % (commands,))
|
||||
print(f"unable to find command, tried {commands}")
|
||||
return None
|
||||
stdout = p.communicate()[0].strip()
|
||||
if sys.version_info[0] >= 3:
|
||||
@@ -140,7 +139,7 @@ def git_get_keywords(versionfile_abs):
|
||||
# _version.py.
|
||||
keywords = {}
|
||||
try:
|
||||
f = io.open(versionfile_abs, "rt", encoding="utf-8")
|
||||
f = open(versionfile_abs, encoding="utf-8")
|
||||
for line in f.readlines():
|
||||
if line.strip().startswith("git_refnames ="):
|
||||
mo = re.search(r'=\s*"(.*)"', line)
|
||||
@@ -299,7 +298,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
|
||||
if verbose:
|
||||
fmt = "tag '%s' doesn't start with prefix '%s'"
|
||||
print(fmt % (full_tag, tag_prefix))
|
||||
pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
|
||||
pieces["error"] = "tag '{}' doesn't start with prefix '{}'".format(
|
||||
full_tag,
|
||||
tag_prefix,
|
||||
)
|
||||
@@ -334,7 +333,7 @@ def git_parse_lookup_file(path):
|
||||
import re
|
||||
|
||||
lookup = []
|
||||
with io.open(path, "rt", encoding="utf-8") as f:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
if "#" in line:
|
||||
line = line[: line.index("#")]
|
||||
|
||||
@@ -2,7 +2,6 @@ __author__ = "Marc Hannappel <salandora@gmail.com>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
from functools import partial
|
||||
@@ -183,13 +182,13 @@ class GroupManager:
|
||||
return None
|
||||
|
||||
def _notify_listeners(self, action, group, *args, **kwargs):
|
||||
method = "on_group_{}".format(action)
|
||||
method = f"on_group_{action}"
|
||||
for listener in self._group_change_listeners:
|
||||
try:
|
||||
getattr(listener, method)(group, *args, **kwargs)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error notifying listener {!r} via {}".format(listener, method)
|
||||
f"Error notifying listener {listener!r} via {method}"
|
||||
)
|
||||
|
||||
|
||||
@@ -227,7 +226,7 @@ class FilebasedGroupManager(GroupManager):
|
||||
def _load(self):
|
||||
if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile):
|
||||
try:
|
||||
with io.open(self._groupfile, "rt", encoding="utf-8") as f:
|
||||
with open(self._groupfile, encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
|
||||
if "groups" not in data:
|
||||
@@ -316,7 +315,7 @@ class FilebasedGroupManager(GroupManager):
|
||||
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while loading groups from file {}".format(self._groupfile)
|
||||
f"Error while loading groups from file {self._groupfile}"
|
||||
)
|
||||
|
||||
def _save(self, force=False):
|
||||
|
||||
@@ -2,7 +2,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
@@ -83,11 +82,11 @@ class UserManager(GroupChangeListener):
|
||||
listener.on_user_logged_in(user)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error in on_user_logged_in on {!r}".format(listener),
|
||||
f"Error in on_user_logged_in on {listener!r}",
|
||||
extra={"callback": fqcn(listener)},
|
||||
)
|
||||
|
||||
self._logger.info("Logged in user: {}".format(user.get_id()))
|
||||
self._logger.info(f"Logged in user: {user.get_id()}")
|
||||
|
||||
return user
|
||||
|
||||
@@ -121,11 +120,11 @@ class UserManager(GroupChangeListener):
|
||||
listener.on_user_logged_out(user, stale=stale)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error in on_user_logged_out on {!r}".format(listener),
|
||||
f"Error in on_user_logged_out on {listener!r}",
|
||||
extra={"callback": fqcn(listener)},
|
||||
)
|
||||
|
||||
self._logger.info("Logged out user: {}".format(user.get_id()))
|
||||
self._logger.info(f"Logged out user: {user.get_id()}")
|
||||
|
||||
def _cleanup_sessions(self):
|
||||
for session, user in list(self._session_users_by_session.items()):
|
||||
@@ -269,9 +268,7 @@ class UserManager(GroupChangeListener):
|
||||
return False
|
||||
|
||||
def on_group_removed(self, group):
|
||||
self._logger.debug(
|
||||
"Group {} got removed, removing from all users".format(group.key)
|
||||
)
|
||||
self._logger.debug(f"Group {group.key} got removed, removing from all users")
|
||||
self.remove_groups_from_users([group])
|
||||
|
||||
def on_group_permissions_changed(self, group, added=None, removed=None):
|
||||
@@ -282,7 +279,7 @@ class UserManager(GroupChangeListener):
|
||||
listener.on_user_modified(user)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error in on_user_modified on {!r}".format(listener),
|
||||
f"Error in on_user_modified on {listener!r}",
|
||||
extra={"callback": fqcn(listener)},
|
||||
)
|
||||
|
||||
@@ -295,7 +292,7 @@ class UserManager(GroupChangeListener):
|
||||
listener.on_user_modified(user)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error in on_user_modified on {!r}".format(listener),
|
||||
f"Error in on_user_modified on {listener!r}",
|
||||
extra={"callback": fqcn(listener)},
|
||||
)
|
||||
|
||||
@@ -327,7 +324,7 @@ class UserManager(GroupChangeListener):
|
||||
listener.on_user_modified(user)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error in on_user_modified on {!r}".format(listener),
|
||||
f"Error in on_user_modified on {listener!r}",
|
||||
extra={"callback": fqcn(listener)},
|
||||
)
|
||||
|
||||
@@ -337,7 +334,7 @@ class UserManager(GroupChangeListener):
|
||||
listener.on_user_removed(username)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error in on_user_removed on {!r}".format(listener),
|
||||
f"Error in on_user_removed on {listener!r}",
|
||||
extra={"callback": fqcn(listener)},
|
||||
)
|
||||
|
||||
@@ -516,7 +513,7 @@ class FilebasedUserManager(UserManager):
|
||||
def _load(self):
|
||||
if os.path.exists(self._userfile) and os.path.isfile(self._userfile):
|
||||
# noinspection PyBroadException
|
||||
with io.open(self._userfile, "rt", encoding="utf-8") as f:
|
||||
with open(self._userfile, encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
|
||||
if not data or not isinstance(data, dict):
|
||||
|
||||
@@ -66,6 +66,7 @@ def util():
|
||||
@click.option("--offset", "offset", type=(float, float), multiple=True)
|
||||
@click.option("--max-t", "maxt", type=int, default=10)
|
||||
@click.option("--g90-extruder", "g90_extruder", is_flag=True)
|
||||
@click.option("--bed-z", "bedz", type=float, default=0)
|
||||
@click.option("--progress", "progress", is_flag=True)
|
||||
@click.argument("path", type=click.Path())
|
||||
def gcode_command(
|
||||
@@ -78,6 +79,7 @@ def gcode_command(
|
||||
throttle,
|
||||
throttle_lines,
|
||||
g90_extruder,
|
||||
bedz,
|
||||
progress,
|
||||
):
|
||||
"""Runs a GCODE file analysis."""
|
||||
@@ -111,7 +113,7 @@ def gcode_command(
|
||||
if progress:
|
||||
|
||||
def progress_callback(percentage):
|
||||
click.echo("PROGRESS:{}".format(percentage))
|
||||
click.echo(f"PROGRESS:{percentage}")
|
||||
|
||||
interpreter = gcode(progress_callback=progress_callback)
|
||||
|
||||
@@ -123,6 +125,7 @@ def gcode_command(
|
||||
throttle=throttle_callback,
|
||||
max_extruders=maxt,
|
||||
g90_extruder=g90_extruder,
|
||||
bed_z=bedz,
|
||||
)
|
||||
|
||||
click.echo("DONE:{}s".format(time.monotonic() - start_time))
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
|
||||
@@ -45,11 +44,11 @@ def create_client(
|
||||
if not apikey:
|
||||
cli_key_file = os.path.join(settings.getBaseFolder("generated"), "cli.key")
|
||||
try:
|
||||
with io.open(cli_key_file, "r", encoding="utf8") as f:
|
||||
with open(cli_key_file, encoding="utf8") as f:
|
||||
apikey = f.readline()
|
||||
except Exception:
|
||||
raise FatalStartupError(
|
||||
"Can not authenticate with server at {}:{}, no key".format(host, port)
|
||||
f"Can not authenticate with server at {host}:{port}, no key"
|
||||
)
|
||||
|
||||
baseurl = octoprint_client.build_base_url(
|
||||
@@ -115,10 +114,10 @@ def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
|
||||
|
||||
def log_response(response, status_code=True, body=True, headers=False):
|
||||
if status_code:
|
||||
click.echo("Status Code: {}".format(response.status_code))
|
||||
click.echo(f"Status Code: {response.status_code}")
|
||||
if headers:
|
||||
for header, value in response.headers.items():
|
||||
click.echo("{}: {}".format(header, value))
|
||||
click.echo(f"{header}: {value}")
|
||||
click.echo()
|
||||
if body:
|
||||
click.echo(response.text)
|
||||
@@ -169,17 +168,17 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
|
||||
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
|
||||
if json_flag or yaml_flag:
|
||||
if json_flag:
|
||||
with io.open(file_path, "rt") as fp:
|
||||
with open(file_path) as fp:
|
||||
data = json.load(fp)
|
||||
else:
|
||||
import yaml
|
||||
|
||||
with io.open(file_path, "rt") as fp:
|
||||
with open(file_path) as fp:
|
||||
data = yaml.safe_load(fp)
|
||||
|
||||
r = ctx.obj.client.post_json(path, data, timeout=timeout)
|
||||
else:
|
||||
with io.open(file_path, "rb") as fp:
|
||||
with open(file_path, "rb") as fp:
|
||||
data = fp.read()
|
||||
|
||||
r = ctx.obj.client.post(path, data, timeout=timeout)
|
||||
@@ -285,7 +284,7 @@ def listen(ctx):
|
||||
click.echo("--- Connection closed!")
|
||||
|
||||
def on_error(ws, error):
|
||||
click.echo("!!! Error: {}".format(error))
|
||||
click.echo(f"!!! Error: {error}")
|
||||
|
||||
def on_sent(ws, data):
|
||||
click.echo(">>> {}".format(json.dumps(data)))
|
||||
|
||||
@@ -33,9 +33,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
|
||||
return log
|
||||
|
||||
self.command_caller = CommandlineCaller()
|
||||
self.command_caller.on_log_call = log_util(
|
||||
lambda x: click.echo(">> {}".format(x))
|
||||
)
|
||||
self.command_caller.on_log_call = log_util(lambda x: click.echo(f">> {x}"))
|
||||
self.command_caller.on_log_stdout = log_util(click.echo)
|
||||
self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True))
|
||||
|
||||
@@ -53,7 +51,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
|
||||
def _get_commands(self):
|
||||
result = {}
|
||||
for group in self.groups:
|
||||
for command in self._get_commands_from_prefix_methods("{}_".format(group)):
|
||||
for command in self._get_commands_from_prefix_methods(f"{group}_"):
|
||||
result[group + self.sep + command.name] = command
|
||||
return result
|
||||
|
||||
|
||||
@@ -131,7 +131,7 @@ class OctoPrintPluginCommands(click.MultiCommand):
|
||||
result[name + self.sep + command.name] = command
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while retrieving cli commands for plugin {}".format(name),
|
||||
f"Error while retrieving cli commands for plugin {name}",
|
||||
extra={"plugin": name},
|
||||
)
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ def run_server(
|
||||
PluginTimingsLogHandler.arm_rollover(logger)
|
||||
|
||||
logger.info(get_divider_line("*"))
|
||||
logger.info("Starting OctoPrint {}".format(__display_version__))
|
||||
logger.info(f"Starting OctoPrint {__display_version__}")
|
||||
if safe_mode:
|
||||
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
|
||||
if safe_mode == "flag":
|
||||
@@ -55,7 +55,7 @@ def run_server(
|
||||
reason = "problem during last startup"
|
||||
else:
|
||||
reason = "unknown"
|
||||
logger.info("Reason for safe mode: {}".format(reason))
|
||||
logger.info(f"Reason for safe mode: {reason}")
|
||||
|
||||
if recorder and len(recorder):
|
||||
logger.info(get_divider_line("-", "Logged during platform initialization:"))
|
||||
@@ -98,7 +98,7 @@ def run_server(
|
||||
log_to_handler(logger, handler, level, message)
|
||||
|
||||
_log(get_divider_line("-", "Log roll over detected"))
|
||||
_log("OctoPrint {}".format(__display_version__))
|
||||
_log(f"OctoPrint {__display_version__}")
|
||||
if safe_mode:
|
||||
_log("SAFE MODE is active. Third party plugins are disabled!")
|
||||
plugin_manager.log_all_plugins(only_to_handler=handler)
|
||||
|
||||
@@ -135,7 +135,7 @@ def systeminfo_command(ctx, path, **kwargs):
|
||||
if path:
|
||||
# create zip at path
|
||||
zipfilename = os.path.join(path, get_systeminfo_bundle_name())
|
||||
click.echo("Writing systeminfo bundle to {}...".format(zipfilename))
|
||||
click.echo(f"Writing systeminfo bundle to {zipfilename}...")
|
||||
|
||||
z = get_systeminfo_bundle(systeminfo, settings.getBaseFolder("logs"))
|
||||
try:
|
||||
@@ -144,9 +144,7 @@ def systeminfo_command(ctx, path, **kwargs):
|
||||
f.write(data)
|
||||
except Exception as e:
|
||||
click.echo(str(e), err=True)
|
||||
click.echo(
|
||||
"There was an error writing to {}.".format(zipfilename), err=True
|
||||
)
|
||||
click.echo(f"There was an error writing to {zipfilename}.", err=True)
|
||||
ctx.exit(-1)
|
||||
|
||||
click.echo("Done!")
|
||||
|
||||
@@ -130,9 +130,7 @@ def add_user_command(ctx, username, password, groups, permissions, is_admin):
|
||||
click.echo("User created:")
|
||||
click.echo("\t{}".format(_user_to_line(user.as_dict())))
|
||||
except UserAlreadyExists:
|
||||
click.echo(
|
||||
"A user with the name {} does already exist!".format(username), err=True
|
||||
)
|
||||
click.echo(f"A user with the name {username} does already exist!", err=True)
|
||||
|
||||
|
||||
@user.command(name="remove")
|
||||
@@ -147,9 +145,9 @@ def remove_user_command(ctx, username):
|
||||
|
||||
if confirm.lower() == "yes":
|
||||
ctx.obj.user_manager.remove_user(username)
|
||||
click.echo("User {} removed.".format(username))
|
||||
click.echo(f"User {username} removed.")
|
||||
else:
|
||||
click.echo("User {} not removed.".format(username))
|
||||
click.echo(f"User {username} not removed.")
|
||||
|
||||
|
||||
@user.command(name="password")
|
||||
@@ -160,9 +158,9 @@ def change_password_command(ctx, username, password):
|
||||
"""Change an existing user's password."""
|
||||
try:
|
||||
ctx.obj.user_manager.change_user_password(username, password)
|
||||
click.echo("Password changed for user {}.".format(username))
|
||||
click.echo(f"Password changed for user {username}.")
|
||||
except UnknownUser:
|
||||
click.echo("User {} does not exist!".format(username), err=True)
|
||||
click.echo(f"User {username} does not exist!", err=True)
|
||||
|
||||
|
||||
@user.command(name="activate")
|
||||
@@ -172,14 +170,14 @@ def activate_command(ctx, username):
|
||||
"""Activate a user account."""
|
||||
try:
|
||||
ctx.obj.user_manager.change_user_activation(username, True)
|
||||
click.echo("User {} activated.".format(username))
|
||||
click.echo(f"User {username} activated.")
|
||||
|
||||
user = ctx.obj.user_manager.find_user(username)
|
||||
if user:
|
||||
click.echo("User created:")
|
||||
click.echo("\t{}".format(_user_to_line(user.asDict())))
|
||||
except UnknownUser:
|
||||
click.echo("User {} does not exist!".format(username), err=True)
|
||||
click.echo(f"User {username} does not exist!", err=True)
|
||||
|
||||
|
||||
@user.command(name="deactivate")
|
||||
@@ -189,14 +187,14 @@ def deactivate_command(ctx, username):
|
||||
"""Activate a user account."""
|
||||
try:
|
||||
ctx.obj.user_manager.change_user_activation(username, False)
|
||||
click.echo("User {} activated.".format(username))
|
||||
click.echo(f"User {username} activated.")
|
||||
|
||||
user = ctx.obj.user_manager.find_user(username)
|
||||
if user:
|
||||
click.echo("User created:")
|
||||
click.echo("\t{}".format(_user_to_line(user.asDict())))
|
||||
except UnknownUser:
|
||||
click.echo("User {} does not exist!".format(username), err=True)
|
||||
click.echo(f"User {username} does not exist!", err=True)
|
||||
|
||||
|
||||
def _print_list(users):
|
||||
|
||||
@@ -4,7 +4,6 @@ Generic linux daemon base class
|
||||
Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35
|
||||
"""
|
||||
|
||||
import io
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
@@ -63,9 +62,9 @@ class Daemon:
|
||||
# redirect standard file descriptors
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
si = io.open(os.devnull, "rt", encoding="utf-8")
|
||||
so = io.open(os.devnull, "at+", encoding="utf-8")
|
||||
se = io.open(os.devnull, "at+", encoding="utf-8")
|
||||
si = open(os.devnull, encoding="utf-8")
|
||||
so = open(os.devnull, "at+", encoding="utf-8")
|
||||
se = open(os.devnull, "at+", encoding="utf-8")
|
||||
|
||||
os.dup2(si.fileno(), sys.stdin.fileno())
|
||||
os.dup2(so.fileno(), sys.stdout.fileno())
|
||||
@@ -153,7 +152,7 @@ class Daemon:
|
||||
def get_pid(self):
|
||||
"""Get the pid from the pidfile."""
|
||||
try:
|
||||
with io.open(self.pidfile, "rt", encoding="utf-8") as pf:
|
||||
with open(self.pidfile, encoding="utf-8") as pf:
|
||||
pid = int(pf.read().strip())
|
||||
except (OSError, ValueError):
|
||||
pid = None
|
||||
@@ -161,7 +160,7 @@ class Daemon:
|
||||
|
||||
def set_pid(self, pid):
|
||||
"""Write the pid to the pidfile."""
|
||||
with io.open(self.pidfile, "wt+", encoding="utf-8") as f:
|
||||
with open(self.pidfile, "wt+", encoding="utf-8") as f:
|
||||
f.write(str(pid) + "\n")
|
||||
|
||||
def remove_pidfile(self):
|
||||
|
||||
@@ -169,7 +169,7 @@ class EnvironmentDetector:
|
||||
environment, default_flow_style=False, indent=2, allow_unicode=True
|
||||
).strip()
|
||||
environment_lines = "\n".join(
|
||||
map(lambda l: "| {}".format(l), dumped_environment.split("\n"))
|
||||
map(lambda l: f"| {l}", dumped_environment.split("\n"))
|
||||
)
|
||||
return "Detected environment is Python {} under {} ({}). Details:\n{}".format(
|
||||
environment["python"]["version"],
|
||||
|
||||
+7
-11
@@ -160,7 +160,7 @@ class EventManager:
|
||||
def __init__(self):
|
||||
self._registeredListeners = collections.defaultdict(list)
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._logger_fire = logging.getLogger("{}.fire".format(__name__))
|
||||
self._logger_fire = logging.getLogger(f"{__name__}.fire")
|
||||
|
||||
self._startup_signaled = False
|
||||
self._shutdown_signaled = False
|
||||
@@ -184,12 +184,10 @@ class EventManager:
|
||||
self._shutdown_signaled = True
|
||||
|
||||
eventListeners = self._registeredListeners[event]
|
||||
self._logger_fire.debug(
|
||||
"Firing event: {} (Payload: {!r})".format(event, payload)
|
||||
)
|
||||
self._logger_fire.debug(f"Firing event: {event} (Payload: {payload!r})")
|
||||
|
||||
for listener in eventListeners:
|
||||
self._logger.debug("Sending action to {!r}".format(listener))
|
||||
self._logger.debug(f"Sending action to {listener!r}")
|
||||
try:
|
||||
listener(event, payload)
|
||||
except Exception:
|
||||
@@ -256,9 +254,7 @@ class EventManager:
|
||||
return
|
||||
|
||||
self._registeredListeners[event].append(callback)
|
||||
self._logger.debug(
|
||||
"Subscribed listener {!r} for event {}".format(callback, event)
|
||||
)
|
||||
self._logger.debug(f"Subscribed listener {callback!r} for event {event}")
|
||||
|
||||
def unsubscribe(self, event, callback):
|
||||
"""
|
||||
@@ -317,7 +313,7 @@ class DebugEventListener(GenericEventListener):
|
||||
|
||||
def eventCallback(self, event, payload):
|
||||
GenericEventListener.eventCallback(self, event, payload)
|
||||
self._logger.debug("Received event: %s (Payload: %r)" % (event, payload))
|
||||
self._logger.debug(f"Received event: {event} (Payload: {payload!r})")
|
||||
|
||||
|
||||
class CommandTrigger(GenericEventListener):
|
||||
@@ -364,7 +360,7 @@ class CommandTrigger(GenericEventListener):
|
||||
continue
|
||||
|
||||
if "enabled" in subscription and not subscription["enabled"]:
|
||||
self._logger.info("Disabled command trigger: {!r}".format(subscription))
|
||||
self._logger.info(f"Disabled command trigger: {subscription!r}")
|
||||
continue
|
||||
|
||||
events = subscription["event"]
|
||||
@@ -423,7 +419,7 @@ class CommandTrigger(GenericEventListener):
|
||||
def _executeSystemCommand(self, command, debug=False):
|
||||
def commandExecutioner(cmd):
|
||||
if debug:
|
||||
self._logger.info("Executing system command: {}".format(cmd))
|
||||
self._logger.info(f"Executing system command: {cmd}")
|
||||
else:
|
||||
self._logger.info("Executing a system command")
|
||||
# we run this with shell=True since we have to trust whatever
|
||||
|
||||
@@ -445,8 +445,6 @@ class FileManager:
|
||||
source_meta = self.get_metadata(source_location, source_path)
|
||||
hash = source_meta.get("hash", "n/a")
|
||||
|
||||
import io
|
||||
|
||||
links = [("model", {"name": source_path})]
|
||||
_, stl_name = self.split_path(source_location, source_path)
|
||||
file_obj = StreamWrapper(
|
||||
@@ -960,7 +958,7 @@ class FileManager:
|
||||
)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Could not write recovery data to file {}".format(self._recovery_file)
|
||||
f"Could not write recovery data to file {self._recovery_file}"
|
||||
)
|
||||
|
||||
def delete_recovery_data(self):
|
||||
@@ -971,7 +969,7 @@ class FileManager:
|
||||
os.remove(self._recovery_file)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error deleting recovery data file {}".format(self._recovery_file)
|
||||
f"Error deleting recovery data file {self._recovery_file}"
|
||||
)
|
||||
|
||||
def get_recovery_data(self):
|
||||
@@ -981,7 +979,7 @@ class FileManager:
|
||||
import yaml
|
||||
|
||||
try:
|
||||
with io.open(self._recovery_file, "rt", encoding="utf-8") as f:
|
||||
with open(self._recovery_file, encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
if not isinstance(data, dict) or not all(
|
||||
map(lambda x: x in data, ("origin", "path", "pos", "date"))
|
||||
@@ -990,7 +988,7 @@ class FileManager:
|
||||
return data
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Could not read recovery data from file {}".format(self._recovery_file)
|
||||
f"Could not read recovery data from file {self._recovery_file}"
|
||||
)
|
||||
self.delete_recovery_data()
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ class QueueEntry(
|
||||
"""
|
||||
|
||||
def __str__(self):
|
||||
return "{location}:{path}".format(location=self.location, path=self.path)
|
||||
return f"{self.location}:{self.path}"
|
||||
|
||||
|
||||
class AnalysisAborted(Exception):
|
||||
@@ -114,7 +114,7 @@ class AnalysisQueue:
|
||||
callback(entry, result)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while pushing analysis data to callback {}".format(callback),
|
||||
f"Error while pushing analysis data to callback {callback}",
|
||||
extra={"callback": fqcn(callback)},
|
||||
)
|
||||
eventManager().fire(
|
||||
@@ -185,9 +185,7 @@ class AbstractAnalysisQueue:
|
||||
"""
|
||||
|
||||
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
|
||||
self._logger.debug(
|
||||
"Ignoring entry {entry} for analysis queue".format(entry=entry)
|
||||
)
|
||||
self._logger.debug(f"Ignoring entry {entry} for analysis queue")
|
||||
return
|
||||
elif high_priority:
|
||||
self._logger.debug(
|
||||
@@ -254,7 +252,7 @@ class AbstractAnalysisQueue:
|
||||
while True:
|
||||
(priority, entry, high_priority) = self._queue.get()
|
||||
self._logger.debug(
|
||||
"Processing entry {} from queue (priority {})".format(entry, priority)
|
||||
f"Processing entry {entry} from queue (priority {priority})"
|
||||
)
|
||||
self._active.wait()
|
||||
|
||||
@@ -273,7 +271,7 @@ class AbstractAnalysisQueue:
|
||||
high_priority,
|
||||
)
|
||||
)
|
||||
self._logger.debug("Running analysis of entry {} aborted".format(entry))
|
||||
self._logger.debug(f"Running analysis of entry {entry} aborted")
|
||||
self._queue.task_done()
|
||||
self._done.set()
|
||||
else:
|
||||
@@ -290,7 +288,7 @@ class AbstractAnalysisQueue:
|
||||
|
||||
try:
|
||||
start_time = time.monotonic()
|
||||
self._logger.info("Starting analysis of {}".format(entry))
|
||||
self._logger.info(f"Starting analysis of {entry}")
|
||||
eventManager().fire(
|
||||
Events.METADATA_ANALYSIS_STARTED,
|
||||
{
|
||||
@@ -311,9 +309,7 @@ class AbstractAnalysisQueue:
|
||||
)
|
||||
self._finished_callback(self._current, result)
|
||||
except RuntimeError as exc:
|
||||
self._logger.error(
|
||||
"Analysis for {} ran into error: {}".format(self._current, exc)
|
||||
)
|
||||
self._logger.error(f"Analysis for {self._current} ran into error: {exc}")
|
||||
finally:
|
||||
self._current = None
|
||||
self._current_progress = None
|
||||
@@ -410,6 +406,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
|
||||
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
|
||||
g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
|
||||
bed_z = settings().getFloat(["gcodeAnalysis", "bedZ"])
|
||||
speedx = self._current.printer_profile["axes"]["x"]["speed"]
|
||||
speedy = self._current.printer_profile["axes"]["y"]["speed"]
|
||||
offsets = self._current.printer_profile["extruder"]["offsets"]
|
||||
@@ -420,11 +417,12 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
"octoprint",
|
||||
"analysis",
|
||||
"gcode",
|
||||
"--speed-x={}".format(speedx),
|
||||
"--speed-y={}".format(speedy),
|
||||
"--max-t={}".format(max_extruders),
|
||||
"--throttle={}".format(throttle),
|
||||
"--throttle-lines={}".format(throttle_lines),
|
||||
f"--speed-x={speedx}",
|
||||
f"--speed-y={speedy}",
|
||||
f"--max-t={max_extruders}",
|
||||
f"--throttle={throttle}",
|
||||
f"--throttle-lines={throttle_lines}",
|
||||
f"--bed-z={bed_z}",
|
||||
]
|
||||
for offset in offsets[1:]:
|
||||
command += ["--offset", str(offset[0]), str(offset[1])]
|
||||
@@ -470,7 +468,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
p.close()
|
||||
|
||||
output = p.stdout.text
|
||||
self._logger.debug("Got output: {!r}".format(output))
|
||||
self._logger.debug(f"Got output: {output!r}")
|
||||
|
||||
if "ERROR:" in output:
|
||||
_, error = output.split("ERROR:")
|
||||
|
||||
@@ -3,7 +3,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import copy
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
@@ -63,9 +62,7 @@ class LocalFileStorage(Storage):
|
||||
self._initialize_metadata()
|
||||
|
||||
def _initialize_metadata(self):
|
||||
self._logger.info(
|
||||
"Initializing the file metadata for {}...".format(self.basefolder)
|
||||
)
|
||||
self._logger.info(f"Initializing the file metadata for {self.basefolder}...")
|
||||
|
||||
old_metadata_path = os.path.join(self.basefolder, "metadata.yaml")
|
||||
backup_path = os.path.join(self.basefolder, "metadata.yaml.backup")
|
||||
@@ -73,7 +70,7 @@ class LocalFileStorage(Storage):
|
||||
if os.path.exists(old_metadata_path):
|
||||
# load the old metadata file
|
||||
try:
|
||||
with io.open(old_metadata_path, "rt", encoding="utf-8") as f:
|
||||
with open(old_metadata_path, encoding="utf-8") as f:
|
||||
import yaml
|
||||
|
||||
self._old_metadata = yaml.safe_load(f)
|
||||
@@ -97,7 +94,7 @@ class LocalFileStorage(Storage):
|
||||
self._list_folder(self.basefolder)
|
||||
|
||||
self._logger.info(
|
||||
"... file metadata for {} initialized successfully.".format(self.basefolder)
|
||||
f"... file metadata for {self.basefolder} initialized successfully."
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -290,7 +287,7 @@ class LocalFileStorage(Storage):
|
||||
|
||||
if not os.path.exists(source_fullpath):
|
||||
raise StorageError(
|
||||
"{} in {} does not exist".format(source_name, source_path),
|
||||
f"{source_name} in {source_path} does not exist",
|
||||
code=StorageError.INVALID_SOURCE,
|
||||
)
|
||||
|
||||
@@ -306,7 +303,7 @@ class LocalFileStorage(Storage):
|
||||
and source_fullpath != destination_fullpath
|
||||
):
|
||||
raise StorageError(
|
||||
"{} does already exist in {}".format(destination_name, destination_path),
|
||||
f"{destination_name} does already exist in {destination_path}",
|
||||
code=StorageError.INVALID_DESTINATION,
|
||||
)
|
||||
|
||||
@@ -795,16 +792,14 @@ class LocalFileStorage(Storage):
|
||||
while os.path.exists(sanitized_path):
|
||||
counter += 1
|
||||
sanitized = self.sanitize_name(
|
||||
"{}_({}){}".format(sanitized_name, counter, sanitized_ext)
|
||||
f"{sanitized_name}_({counter}){sanitized_ext}"
|
||||
)
|
||||
sanitized_path = os.path.join(path, sanitized)
|
||||
|
||||
try:
|
||||
shutil.move(entry_path, sanitized_path)
|
||||
|
||||
self._logger.info(
|
||||
'Sanitized "{}" to "{}"'.format(entry_path, sanitized_path)
|
||||
)
|
||||
self._logger.info(f'Sanitized "{entry_path}" to "{sanitized_path}"')
|
||||
return sanitized, sanitized_path
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
@@ -1084,6 +1079,7 @@ class LocalFileStorage(Storage):
|
||||
logtarget=__name__ + ".timings",
|
||||
message="{func}({func_args},{func_kwargs}) took {timing:.2f}ms",
|
||||
incl_func_args=True,
|
||||
log_enter=True,
|
||||
)
|
||||
def _list_folder(self, path, base="", force_refresh=False, **kwargs):
|
||||
def get_size(nodes):
|
||||
@@ -1111,11 +1107,8 @@ class LocalFileStorage(Storage):
|
||||
try:
|
||||
with self._filelist_cache_mutex:
|
||||
cache = self._filelist_cache.get(path)
|
||||
if (
|
||||
not force_refresh
|
||||
and cache
|
||||
and cache[0] >= self.last_modified(path, recursive=True)
|
||||
):
|
||||
lm = self.last_modified(path, recursive=True)
|
||||
if not force_refresh and cache and cache[0] >= lm:
|
||||
return enrich_folders(cache[1])
|
||||
|
||||
metadata = self._get_metadata(path)
|
||||
@@ -1251,12 +1244,12 @@ class LocalFileStorage(Storage):
|
||||
except Exception:
|
||||
# So something went wrong somewhere while processing this file entry - log that and continue
|
||||
self._logger.exception(
|
||||
"Error while processing entry {}".format(entry_path)
|
||||
f"Error while processing entry {entry_path}"
|
||||
)
|
||||
continue
|
||||
|
||||
self._filelist_cache[path] = (
|
||||
self.last_modified(path, recursive=True),
|
||||
lm,
|
||||
result,
|
||||
)
|
||||
return enrich_folders(result)
|
||||
@@ -1321,7 +1314,7 @@ class LocalFileStorage(Storage):
|
||||
|
||||
blocksize = 65536
|
||||
hash = hashlib.sha1()
|
||||
with io.open(path, "rb") as f:
|
||||
with open(path, "rb") as f:
|
||||
buffer = f.read(blocksize)
|
||||
while len(buffer) > 0:
|
||||
hash.update(buffer)
|
||||
@@ -1402,7 +1395,7 @@ class LocalFileStorage(Storage):
|
||||
metadata = None
|
||||
with self._get_persisted_metadata_lock(path):
|
||||
if os.path.exists(metadata_path):
|
||||
with io.open(metadata_path, "rt", encoding="utf-8") as f:
|
||||
with open(metadata_path, encoding="utf-8") as f:
|
||||
try:
|
||||
metadata = json.load(f)
|
||||
except Exception:
|
||||
@@ -1509,7 +1502,7 @@ class LocalFileStorage(Storage):
|
||||
)
|
||||
return
|
||||
|
||||
with io.open(metadata_path_yaml, "rt", encoding="utf-8") as f:
|
||||
with open(metadata_path_yaml, encoding="utf-8") as f:
|
||||
try:
|
||||
metadata = yaml.safe_load(f)
|
||||
except Exception:
|
||||
|
||||
@@ -72,7 +72,7 @@ class DiskFileWrapper(AbstractFileWrapper):
|
||||
os.chmod(path, permissions)
|
||||
|
||||
def stream(self):
|
||||
return io.open(self.path, "rb")
|
||||
return open(self.path, "rb")
|
||||
|
||||
|
||||
class StreamWrapper(AbstractFileWrapper):
|
||||
|
||||
@@ -20,7 +20,7 @@ class TornadoAccessFilter(logging.Filter):
|
||||
record.levelname = logging.getLevelName(record.levelno)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception(
|
||||
"Error while filtering log record {!r}".format(record)
|
||||
f"Error while filtering log record {record!r}"
|
||||
)
|
||||
|
||||
return logging.Filter.filter(self, record)
|
||||
@@ -186,7 +186,7 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
|
||||
get_preprocessors, set_preprocessors = instance.get_settings_preprocessors()
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception(
|
||||
"Error while retrieving preprocessors for plugin {}".format(plugin_key)
|
||||
f"Error while retrieving preprocessors for plugin {plugin_key}"
|
||||
)
|
||||
return None
|
||||
|
||||
@@ -263,7 +263,7 @@ def call_plugin(
|
||||
continue
|
||||
|
||||
if hasattr(plugin, method):
|
||||
logger.debug("Calling {} on {}".format(method, plugin._identifier))
|
||||
logger.debug(f"Calling {method} on {plugin._identifier}")
|
||||
try:
|
||||
result = getattr(plugin, method)(*args, **kwargs)
|
||||
if callback:
|
||||
|
||||
@@ -24,7 +24,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import fnmatch
|
||||
import inspect
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
from collections import OrderedDict, defaultdict, namedtuple
|
||||
@@ -306,7 +305,7 @@ class PluginInfo:
|
||||
|
||||
def __str__(self):
|
||||
if self.version:
|
||||
return "{name} ({version})".format(name=self.name, version=self.version)
|
||||
return f"{self.name} ({self.version})"
|
||||
else:
|
||||
return to_unicode(self.name)
|
||||
|
||||
@@ -684,14 +683,12 @@ class PluginInfo:
|
||||
# we only support parsing plain text source files
|
||||
return result
|
||||
|
||||
self._logger.debug(
|
||||
"Parsing plugin metadata for {} from AST of {}".format(self.key, path)
|
||||
)
|
||||
self._logger.debug(f"Parsing plugin metadata for {self.key} from AST of {path}")
|
||||
|
||||
try:
|
||||
import ast
|
||||
|
||||
with io.open(path, "rb") as f:
|
||||
with open(path, "rb") as f:
|
||||
root = ast.parse(f.read(), filename=path)
|
||||
|
||||
assignments = list(
|
||||
@@ -765,13 +762,11 @@ class PluginInfo:
|
||||
break
|
||||
|
||||
except SyntaxError:
|
||||
self._logger.exception(
|
||||
"Invalid syntax in {} for plugin {}".format(path, self.key)
|
||||
)
|
||||
self._logger.exception(f"Invalid syntax in {path} for plugin {self.key}")
|
||||
self.invalid_syntax = True
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while parsing AST from {} for plugin {}".format(path, self.key)
|
||||
f"Error while parsing AST from {path} for plugin {self.key}"
|
||||
)
|
||||
|
||||
return result
|
||||
@@ -1001,7 +996,7 @@ class PluginManager:
|
||||
|
||||
module_name = None
|
||||
if package:
|
||||
module_name = "{}.{}".format(package, key)
|
||||
module_name = f"{package}.{key}"
|
||||
|
||||
plugin = self._import_plugin_from_module(
|
||||
key, module_name=module_name, folder=folder, bundled=bundled
|
||||
@@ -1025,7 +1020,7 @@ class PluginManager:
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
self.logger.exception("Error processing folder {}".format(folder))
|
||||
self.logger.exception(f"Error processing folder {folder}")
|
||||
|
||||
return added, found
|
||||
|
||||
@@ -1163,7 +1158,7 @@ class PluginManager:
|
||||
else:
|
||||
return None
|
||||
except Exception:
|
||||
self.logger.exception("Could not locate plugin {key}".format(key=key))
|
||||
self.logger.exception(f"Could not locate plugin {key}")
|
||||
return None
|
||||
|
||||
# Create a simple dummy entry first ...
|
||||
@@ -1181,14 +1176,14 @@ class PluginManager:
|
||||
plugin.bundled = bundled
|
||||
|
||||
if self._is_plugin_disabled(key):
|
||||
self.logger.info("Plugin {} is disabled.".format(plugin))
|
||||
self.logger.info(f"Plugin {plugin} is disabled.")
|
||||
plugin.forced_disabled = True
|
||||
|
||||
if self._is_plugin_blacklisted(key) or (
|
||||
plugin.version is not None
|
||||
and self._is_plugin_version_blacklisted(key, plugin.version)
|
||||
):
|
||||
self.logger.warning("Plugin {} is blacklisted.".format(plugin))
|
||||
self.logger.warning(f"Plugin {plugin} is blacklisted.")
|
||||
plugin.blacklisted = True
|
||||
|
||||
python_version = get_python_version_string()
|
||||
@@ -1264,7 +1259,7 @@ class PluginManager:
|
||||
|
||||
plugin.bundled = bundled
|
||||
except Exception:
|
||||
self.logger.exception("Error loading plugin {key}".format(key=key))
|
||||
self.logger.exception(f"Error loading plugin {key}")
|
||||
return None
|
||||
|
||||
if plugin.check():
|
||||
@@ -1386,7 +1381,7 @@ class PluginManager:
|
||||
):
|
||||
if plugin.blacklisted:
|
||||
self.logger.warning(
|
||||
"Plugin {} is blacklisted. Not enabling it.".format(plugin)
|
||||
f"Plugin {plugin} is blacklisted. Not enabling it."
|
||||
)
|
||||
continue
|
||||
self.enable_plugin(
|
||||
@@ -2272,11 +2267,11 @@ def is_sub_path_of(path, parent):
|
||||
|
||||
|
||||
def is_editable_install(install_dir, package, module, location):
|
||||
package_link = os.path.join(install_dir, "{}.egg-link".format(package))
|
||||
package_link = os.path.join(install_dir, f"{package}.egg-link")
|
||||
if os.path.isfile(package_link):
|
||||
expected_target = os.path.normcase(os.path.realpath(location))
|
||||
try:
|
||||
with io.open(package_link, "rt", encoding="utf-8") as f:
|
||||
with open(package_link, encoding="utf-8") as f:
|
||||
contents = f.readlines()
|
||||
for line in contents:
|
||||
target = os.path.normcase(
|
||||
|
||||
@@ -1276,7 +1276,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
|
||||
|
||||
If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content``
|
||||
for you. You may also return regular responses as you would return from any Flask view here though, e.g.
|
||||
``return flask.jsonify(result="some json result")`` or ``return flask.make_response("Not found", 404)``.
|
||||
``return flask.jsonify(result="some json result")`` or ``flask.abort(404)``.
|
||||
|
||||
:param string command: the command with which the resource was called
|
||||
:param dict data: the full request body of the POST request parsed from JSON into a Python dictionary
|
||||
@@ -1294,7 +1294,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
|
||||
|
||||
If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content``
|
||||
for you. You may also return regular responses as you would return from any Flask view here though, e.g.
|
||||
``return flask.jsonify(result="some json result")`` or ``return flask.make_response("Not found", 404)``.
|
||||
``return flask.jsonify(result="some json result")`` or ``flask.abort(404)``.
|
||||
|
||||
:param request: the Flask request object
|
||||
:return: ``None`` in which case OctoPrint will generate a ``204 No content`` response with empty body, or optionally
|
||||
@@ -1324,7 +1324,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
@octoprint.plugin.BlueprintPlugin.route("/echo", methods=["GET"])
|
||||
def myEcho(self):
|
||||
if not "text" in flask.request.values:
|
||||
return flask.make_response("Expected a text to echo back.", 400)
|
||||
abort(400, description="Expected a text to echo back.")
|
||||
return flask.request.values["text"]
|
||||
|
||||
__plugin_implementation__ = MyBlueprintPlugin()
|
||||
@@ -1474,9 +1474,22 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
If you want your blueprint's endpoints to have specific permissions, return ``False`` for this and do your
|
||||
permissions checks explicitly.
|
||||
"""
|
||||
|
||||
return True
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_blueprint_api_prefixes(self):
|
||||
"""
|
||||
Return all prefixes of your endpoint that are an API that should be containing JSON only.
|
||||
|
||||
Anything that matches this will generate JSON error messages in case of flask.abort
|
||||
calls, instead of the default HTML ones.
|
||||
|
||||
Defaults to all endpoints under the blueprint. Limit this further as needed. E.g.,
|
||||
if you only want your endpoints /foo, /foo/1 and /bar to be declared as API,
|
||||
return ``["/foo", "/bar"]``. A match will be determined via startswith.
|
||||
"""
|
||||
return [""]
|
||||
|
||||
|
||||
class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
|
||||
@@ -66,7 +66,7 @@ class ActionCommandNotificationPlugin(
|
||||
|
||||
def on_api_get(self, request):
|
||||
if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW.can():
|
||||
return flask.abort(403, "Insufficient permissions")
|
||||
return flask.abort(403)
|
||||
return flask.jsonify(
|
||||
notifications=[
|
||||
{"timestamp": notification[0], "message": notification[1]}
|
||||
@@ -123,7 +123,7 @@ class ActionCommandNotificationPlugin(
|
||||
self._notifications.append((time.time(), message))
|
||||
self._plugin_manager.send_plugin_message(self._identifier, {"message": message})
|
||||
|
||||
self._logger.info("Got a notification: {}".format(message))
|
||||
self._logger.info(f"Got a notification: {message}")
|
||||
|
||||
def _clear_notifications(self):
|
||||
self._notifications = []
|
||||
|
||||
+1
-1
@@ -85,7 +85,7 @@ $(function () {
|
||||
}
|
||||
};
|
||||
|
||||
var optionsLocalStorageKey = "core.gcodeviewer.options";
|
||||
var optionsLocalStorageKey = "plugin.action_command_notification.options";
|
||||
self._toLocalStorage = function () {
|
||||
saveToLocalStorage(optionsLocalStorageKey, {sortDesc: self.sortDesc()});
|
||||
};
|
||||
|
||||
@@ -90,7 +90,7 @@ class ActionCommandPromptPlugin(
|
||||
and self._enable == "always"
|
||||
and self._enable_signal_support
|
||||
):
|
||||
self._printer.commands(["{command} P1".format(command=self._command)])
|
||||
self._printer.commands([f"{self._command} P1"])
|
||||
elif event == Events.DISCONNECTED:
|
||||
self._close_prompt()
|
||||
|
||||
@@ -123,22 +123,20 @@ class ActionCommandPromptPlugin(
|
||||
def on_api_command(self, command, data):
|
||||
if command == "select":
|
||||
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
|
||||
return flask.abort(403, "Insufficient permissions")
|
||||
return flask.abort(403)
|
||||
|
||||
if self._prompt is None:
|
||||
return flask.abort(409, "No active prompt")
|
||||
return flask.abort(409, description="No active prompt")
|
||||
|
||||
choice = data["choice"]
|
||||
if not isinstance(choice, int) or not self._prompt.validate_choice(choice):
|
||||
return flask.abort(
|
||||
400, "{!r} is not a valid value for choice".format(choice)
|
||||
)
|
||||
return flask.abort(400, f"{choice!r} is not a valid value for choice")
|
||||
|
||||
self._answer_prompt(choice)
|
||||
|
||||
def on_api_get(self, request):
|
||||
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
|
||||
return flask.abort(403, "Insufficient permissions")
|
||||
return flask.abort(403)
|
||||
if self._prompt is None:
|
||||
return flask.jsonify()
|
||||
else:
|
||||
@@ -208,7 +206,7 @@ class ActionCommandPromptPlugin(
|
||||
subcode=None,
|
||||
tags=None,
|
||||
*args,
|
||||
**kwargs
|
||||
**kwargs,
|
||||
):
|
||||
if gcode != self._command:
|
||||
return
|
||||
@@ -226,7 +224,7 @@ class ActionCommandPromptPlugin(
|
||||
|
||||
# noinspection PyProtectedMember
|
||||
return comm_instance._emergency_force_send(
|
||||
cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode
|
||||
cmd, f"Force-sending {self._command} to the printer", gcode=gcode
|
||||
)
|
||||
|
||||
# ~ capability reporting
|
||||
@@ -237,7 +235,7 @@ class ActionCommandPromptPlugin(
|
||||
if capability == self.CAP_PROMPT_SUPPORT and enabled:
|
||||
self._cap_prompt_support = True
|
||||
if self._enable == "detected" and self._enable_signal_support:
|
||||
self._printer.commands(["{command} P1".format(command=self._command)])
|
||||
self._printer.commands([f"{self._command} P1"])
|
||||
|
||||
# ~ prompt handling
|
||||
|
||||
@@ -277,7 +275,7 @@ class ActionCommandPromptPlugin(
|
||||
self._printer.commands([self._command.format(choice=choice)], force=True)
|
||||
else:
|
||||
self._printer.commands(
|
||||
["{command} S{choice}".format(command=self._command, choice=choice)],
|
||||
[f"{self._command} S{choice}"],
|
||||
force=True,
|
||||
)
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms
|
||||
|
||||
|
||||
import calendar
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
@@ -286,7 +285,7 @@ class AnnouncementPlugin(
|
||||
|
||||
elif command == "toggle":
|
||||
if not Permissions.PLUGIN_ANNOUNCEMENTS_MANAGE.can():
|
||||
return flask.make_response("Insufficient rights", 403)
|
||||
flask.abort(403)
|
||||
self._toggle(channel)
|
||||
|
||||
return NO_CONTENT
|
||||
@@ -434,9 +433,7 @@ class AnnouncementPlugin(
|
||||
now = time.time()
|
||||
if os.stat(channel_path).st_mtime + ttl > now:
|
||||
d = feedparser.parse(channel_path)
|
||||
self._logger.debug(
|
||||
"Loaded channel {} from cache at {}".format(key, channel_path)
|
||||
)
|
||||
self._logger.debug(f"Loaded channel {key} from cache at {channel_path}")
|
||||
return d
|
||||
|
||||
return None
|
||||
@@ -464,7 +461,7 @@ class AnnouncementPlugin(
|
||||
|
||||
response = r.text
|
||||
channel_path = self._get_channel_cache_path(key)
|
||||
with io.open(channel_path, mode="wt", encoding="utf-8") as f:
|
||||
with open(channel_path, mode="wt", encoding="utf-8") as f:
|
||||
f.write(response)
|
||||
return feedparser.parse(response)
|
||||
|
||||
@@ -518,7 +515,7 @@ class AnnouncementPlugin(
|
||||
"""Retrieve cache path for channel key."""
|
||||
|
||||
safe_key = sanitize(key)
|
||||
return os.path.join(self.get_plugin_data_folder(), "{}.cache".format(safe_key))
|
||||
return os.path.join(self.get_plugin_data_folder(), f"{safe_key}.cache")
|
||||
|
||||
|
||||
_image_tag_re = re.compile(r"<img.*?/?>")
|
||||
@@ -577,7 +574,7 @@ def _lazy_images(text, placeholder=None):
|
||||
quote = match.group("quote")
|
||||
quoted_src = quote + src + quote
|
||||
img_tag = img_tag.replace(
|
||||
match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src)
|
||||
match.group(0), f'src="{placeholder}" data-src={quoted_src}'
|
||||
)
|
||||
return img_tag
|
||||
|
||||
@@ -602,10 +599,10 @@ def _strip_tags(text):
|
||||
self._fed.append(data)
|
||||
|
||||
def handle_entityref(self, ref):
|
||||
self._fed.append("&{};".format(ref))
|
||||
self._fed.append(f"&{ref};")
|
||||
|
||||
def handle_charref(self, ref):
|
||||
self._fed.append("&#{};".format(ref))
|
||||
self._fed.append(f"&#{ref};")
|
||||
|
||||
def get_data(self):
|
||||
return "".join(self._fed)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import io
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
@@ -155,10 +154,10 @@ class AppKeysPlugin(
|
||||
def handle_request(self):
|
||||
data = flask.request.json
|
||||
if data is None:
|
||||
return flask.make_response("Missing key request", 400)
|
||||
flask.abort(400, description="Missing key request")
|
||||
|
||||
if "app" not in data:
|
||||
return flask.make_response("No app name provided", 400)
|
||||
flask.abort(400, description="No app name provided")
|
||||
|
||||
app_name = data["app"]
|
||||
user_id = None
|
||||
@@ -206,7 +205,7 @@ class AppKeysPlugin(
|
||||
def handle_decision(self, user_token):
|
||||
data = flask.request.json
|
||||
if "decision" not in data:
|
||||
return flask.make_response("No decision provided", 400)
|
||||
flask.abort(400, description="No decision provided")
|
||||
decision = data["decision"] in valid_boolean_trues
|
||||
user_id = current_user.get_name()
|
||||
|
||||
@@ -439,13 +438,11 @@ class AppKeysPlugin(
|
||||
return
|
||||
|
||||
try:
|
||||
with io.open(
|
||||
self._key_path, "rt", encoding="utf-8", errors="strict"
|
||||
) as f:
|
||||
with open(self._key_path, encoding="utf-8", errors="strict") as f:
|
||||
persisted = yaml.safe_load(f)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Could not load application keys from {}".format(self._key_path)
|
||||
f"Could not load application keys from {self._key_path}"
|
||||
)
|
||||
return
|
||||
|
||||
@@ -470,7 +467,7 @@ class AppKeysPlugin(
|
||||
yaml.safe_dump(to_persist, f, allow_unicode=True)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Could not write application keys to {}".format(self._key_path)
|
||||
f"Could not write application keys to {self._key_path}"
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -26,7 +26,6 @@ except ImportError:
|
||||
zlib = None
|
||||
|
||||
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -197,12 +196,13 @@ class BackupPlugin(
|
||||
if not Permissions.PLUGIN_BACKUP_ACCESS.can() and not self._settings.global_get(
|
||||
["server", "firstRun"]
|
||||
):
|
||||
return flask.abort(403)
|
||||
flask.abort(403)
|
||||
|
||||
if not self._restore_supported(self._settings):
|
||||
return flask.make_response(
|
||||
"Invalid request, the restores are not supported on the underlying operating system",
|
||||
flask.abort(
|
||||
400,
|
||||
description="Invalid request, the restores are not "
|
||||
"supported on the underlying operating system",
|
||||
)
|
||||
|
||||
input_name = "file"
|
||||
@@ -230,9 +230,10 @@ class BackupPlugin(
|
||||
return flask.abort(404)
|
||||
|
||||
else:
|
||||
return flask.make_response(
|
||||
"Invalid request, neither a file nor a path of a file to restore provided",
|
||||
flask.abort(
|
||||
400,
|
||||
description="Invalid request, neither a file nor a path of a file to "
|
||||
"restore provided",
|
||||
)
|
||||
|
||||
def on_install_plugins(plugins):
|
||||
@@ -504,7 +505,7 @@ class BackupPlugin(
|
||||
if not os.path.isdir(datafolder):
|
||||
os.makedirs(datafolder)
|
||||
|
||||
click.echo("Creating backup at {}, please wait...".format(filename))
|
||||
click.echo(f"Creating backup at {filename}, please wait...")
|
||||
self._create_backup(
|
||||
filename,
|
||||
exclude=exclude,
|
||||
@@ -548,7 +549,7 @@ class BackupPlugin(
|
||||
path = os.path.join(datafolder, path)
|
||||
|
||||
if not os.path.exists(path):
|
||||
click.echo("Backup {} does not exist".format(path), err=True)
|
||||
click.echo(f"Backup {path} does not exist", err=True)
|
||||
sys.exit(-1)
|
||||
|
||||
archive = tempfile.NamedTemporaryFile(delete=False)
|
||||
@@ -566,7 +567,7 @@ class BackupPlugin(
|
||||
pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"])
|
||||
|
||||
def log(line):
|
||||
click.echo("\t{}".format(line))
|
||||
click.echo(f"\t{line}")
|
||||
|
||||
for plugin in plugins:
|
||||
octoprint_compatible = is_octoprint_compatible(
|
||||
@@ -642,9 +643,9 @@ class BackupPlugin(
|
||||
on_log_error=on_log_error,
|
||||
on_invalid_backup=on_log_error,
|
||||
):
|
||||
click.echo("Restored from {}".format(path))
|
||||
click.echo(f"Restored from {path}")
|
||||
else:
|
||||
click.echo("Restoring from {} failed".format(path), err=True)
|
||||
click.echo(f"Restoring from {path} failed", err=True)
|
||||
|
||||
return [backup_command, restore_command]
|
||||
|
||||
@@ -723,7 +724,7 @@ class BackupPlugin(
|
||||
try:
|
||||
os.remove(full_path)
|
||||
except Exception:
|
||||
self._logger.exception("Could not delete {}".format(filename))
|
||||
self._logger.exception(f"Could not delete {filename}")
|
||||
raise
|
||||
|
||||
def _get_backups(self):
|
||||
@@ -752,7 +753,7 @@ class BackupPlugin(
|
||||
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
|
||||
if os.path.exists(data_file):
|
||||
try:
|
||||
with io.open(data_file, mode="rt", encoding="utf-8") as f:
|
||||
with open(data_file, mode="rt", encoding="utf-8") as f:
|
||||
unknown_plugins = json.load(f)
|
||||
|
||||
assert isinstance(unknown_plugins, list)
|
||||
@@ -850,7 +851,7 @@ class BackupPlugin(
|
||||
r.raise_for_status()
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Error while fetching the plugin repository data from {}".format(url)
|
||||
f"Error while fetching the plugin repository data from {url}"
|
||||
)
|
||||
return {}
|
||||
|
||||
@@ -871,7 +872,7 @@ class BackupPlugin(
|
||||
# prepare pip caller
|
||||
def log(prefix, *lines):
|
||||
for line in lines:
|
||||
on_log("{} {}".format(prefix, line.rstrip()))
|
||||
on_log(f"{prefix} {line.rstrip()}")
|
||||
|
||||
def log_call(*lines):
|
||||
log(">", *lines)
|
||||
@@ -965,7 +966,7 @@ class BackupPlugin(
|
||||
configfile = settings._configfile
|
||||
basedir = settings._basedir
|
||||
|
||||
temporary_path = os.path.join(datafolder, ".{}".format(name))
|
||||
temporary_path = os.path.join(datafolder, f".{name}")
|
||||
final_path = os.path.join(datafolder, name)
|
||||
|
||||
own_folder = datafolder
|
||||
@@ -1160,7 +1161,7 @@ class BackupPlugin(
|
||||
temp = tempfile.mkdtemp()
|
||||
try:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress("Unpacking backup to {}...".format(temp))
|
||||
on_log_progress(f"Unpacking backup to {temp}...")
|
||||
|
||||
abstemp = os.path.abspath(temp)
|
||||
dirs = {}
|
||||
@@ -1191,7 +1192,7 @@ class BackupPlugin(
|
||||
|
||||
import yaml
|
||||
|
||||
with io.open(configfile, "rt", encoding="utf-8") as f:
|
||||
with open(configfile, encoding="utf-8") as f:
|
||||
configdata = yaml.safe_load(f)
|
||||
|
||||
userfile = os.path.join(temp, "basedir", "users.yaml")
|
||||
@@ -1209,7 +1210,7 @@ class BackupPlugin(
|
||||
plugins = []
|
||||
plugin_list_file = os.path.join(temp, "plugin_list.json")
|
||||
if os.path.exists(plugin_list_file):
|
||||
with io.open(os.path.join(temp, "plugin_list.json"), "rb") as f:
|
||||
with open(os.path.join(temp, "plugin_list.json"), "rb") as f:
|
||||
plugins = json.load(f)
|
||||
|
||||
known_plugins = []
|
||||
@@ -1259,16 +1260,12 @@ class BackupPlugin(
|
||||
basedir_extracted = os.path.join(temp, "basedir")
|
||||
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(
|
||||
"Renaming {} to {}...".format(basedir, basedir_backup)
|
||||
)
|
||||
on_log_progress(f"Renaming {basedir} to {basedir_backup}...")
|
||||
shutil.move(basedir, basedir_backup)
|
||||
|
||||
try:
|
||||
if callable(on_log_progress):
|
||||
on_log_progress(
|
||||
"Moving {} to {}...".format(basedir_extracted, basedir)
|
||||
)
|
||||
on_log_progress(f"Moving {basedir_extracted} to {basedir}...")
|
||||
shutil.move(basedir_extracted, basedir)
|
||||
except Exception:
|
||||
if callable(on_log_error):
|
||||
@@ -1295,7 +1292,7 @@ class BackupPlugin(
|
||||
datafolder, UNKNOWN_PLUGINS_FILE
|
||||
)
|
||||
try:
|
||||
with io.open(unknown_plugins_path, mode="wb") as f:
|
||||
with open(unknown_plugins_path, mode="wb") as f:
|
||||
f.write(to_bytes(json.dumps(unknown_plugins)))
|
||||
except Exception:
|
||||
if callable(on_log_error):
|
||||
@@ -1349,7 +1346,7 @@ class BackupPlugin(
|
||||
except Exception:
|
||||
if callable(on_log_error):
|
||||
on_log_error(
|
||||
"Error while restarting via command {}".format(restart_command),
|
||||
f"Error while restarting via command {restart_command}",
|
||||
exc_info=sys.exc_info(),
|
||||
)
|
||||
on_log_error("Please restart OctoPrint manually")
|
||||
|
||||
@@ -54,9 +54,9 @@ class CoreWizardPlugin(
|
||||
config = {
|
||||
"type": "wizard",
|
||||
"name": name,
|
||||
"template": "corewizard_{}_wizard.jinja2".format(key),
|
||||
"div": "wizard_plugin_corewizard_{}".format(key),
|
||||
"suffix": "_{}".format(key),
|
||||
"template": f"corewizard_{key}_wizard.jinja2",
|
||||
"div": f"wizard_plugin_corewizard_{key}",
|
||||
"suffix": f"_{key}",
|
||||
}
|
||||
if key in additional:
|
||||
additional_result = additional[key]()
|
||||
|
||||
@@ -228,15 +228,15 @@ class DiscoveryPlugin(
|
||||
name,
|
||||
addresses=addresses,
|
||||
port=port,
|
||||
server="{}.local.".format(socket.gethostname()),
|
||||
server=f"{socket.gethostname()}.local.",
|
||||
properties=txt_record,
|
||||
)
|
||||
self._zeroconf.register_service(info, allow_name_change=True)
|
||||
self._zeroconf_registrations[key].append(info)
|
||||
self._logger.info("Registered '{}' for {}".format(name, reg_type))
|
||||
self._logger.info(f"Registered '{name}' for {reg_type}")
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Could not register {} for {} on port {}".format(name, reg_type, port)
|
||||
f"Could not register {name} for {reg_type} on port {port}"
|
||||
)
|
||||
|
||||
def zeroconf_unregister(self, reg_type, port=None):
|
||||
@@ -260,10 +260,10 @@ class DiscoveryPlugin(
|
||||
try:
|
||||
for info in infos:
|
||||
self._zeroconf.unregister_service(info)
|
||||
self._logger.debug("Unregistered {} on port {}".format(reg_type, port))
|
||||
self._logger.debug(f"Unregistered {reg_type} on port {port}")
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Could not (fully) unregister {} on port {}".format(reg_type, port)
|
||||
f"Could not (fully) unregister {reg_type} on port {port}"
|
||||
)
|
||||
|
||||
def zeroconf_browse(
|
||||
@@ -349,9 +349,7 @@ class DiscoveryPlugin(
|
||||
for address in map(lambda x: socket.inet_ntoa(x), info.addresses):
|
||||
result.append(to_result(info, address))
|
||||
|
||||
self._logger.debug(
|
||||
"Browsing Zeroconf for {service_type}".format(service_type=service_type)
|
||||
)
|
||||
self._logger.debug(f"Browsing Zeroconf for {service_type}")
|
||||
|
||||
def browse():
|
||||
listener = ZeroconfListener(self._logger)
|
||||
@@ -706,7 +704,7 @@ class DiscoveryPlugin(
|
||||
+ socket.inet_aton("0.0.0.0"),
|
||||
)
|
||||
|
||||
self._logger.info("Registered {} for SSDP".format(self.get_instance_name()))
|
||||
self._logger.info(f"Registered {self.get_instance_name()} for SSDP")
|
||||
|
||||
self._ssdp_notify(alive=True)
|
||||
|
||||
@@ -728,7 +726,7 @@ class DiscoveryPlugin(
|
||||
interface_address = octoprint.util.address_for_client(
|
||||
*address,
|
||||
addresses=self._settings.get(["addresses"]),
|
||||
interfaces=self._settings.get(["interfaces"])
|
||||
interfaces=self._settings.get(["interfaces"]),
|
||||
)
|
||||
if not interface_address:
|
||||
continue
|
||||
@@ -772,9 +770,9 @@ class DiscoveryPlugin(
|
||||
def get_instance_name(self):
|
||||
name = self._settings.global_get(["appearance", "name"])
|
||||
if name:
|
||||
return 'OctoPrint instance "{}"'.format(name)
|
||||
return f'OctoPrint instance "{name}"'
|
||||
else:
|
||||
return "OctoPrint instance on {}".format(socket.gethostname())
|
||||
return f"OctoPrint instance on {socket.gethostname()}"
|
||||
|
||||
def get_interface_addresses(self):
|
||||
addresses = self._settings.get(["addresses"])
|
||||
|
||||
@@ -365,7 +365,8 @@ $(function () {
|
||||
onLayerSelected: self._onLayerSelected,
|
||||
bed: self._retrieveBedDimensions(),
|
||||
toolOffsets: self._retrieveToolOffsets(),
|
||||
invertAxes: self._retrieveAxesConfiguration()
|
||||
invertAxes: self._retrieveAxesConfiguration(),
|
||||
bedZ: self.settings.settings.gcodeAnalysis.bedZ()
|
||||
});
|
||||
|
||||
if (!initResult) {
|
||||
|
||||
@@ -39,7 +39,8 @@ GCODE.gCodeReader = (function () {
|
||||
centeredOrigin: undefined
|
||||
},
|
||||
ignoreOutsideBed: false,
|
||||
g90InfluencesExtruder: false
|
||||
g90InfluencesExtruder: false,
|
||||
bedZ: 0
|
||||
};
|
||||
|
||||
var percentageTree = undefined;
|
||||
@@ -166,7 +167,8 @@ GCODE.gCodeReader = (function () {
|
||||
toolOffsets: gCodeOptions["toolOffsets"],
|
||||
bed: gCodeOptions["bed"],
|
||||
ignoreOutsideBed: gCodeOptions["ignoreOutsideBed"],
|
||||
g90InfluencesExtruder: gCodeOptions["g90InfluencesExtruder"]
|
||||
g90InfluencesExtruder: gCodeOptions["g90InfluencesExtruder"],
|
||||
bedZ: gCodeOptions["bedZ"]
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -174,11 +176,11 @@ GCODE.gCodeReader = (function () {
|
||||
|
||||
setOption: function (options) {
|
||||
var dirty = false;
|
||||
for (var opt in options) {
|
||||
if (options[opt] === undefined) continue;
|
||||
dirty = dirty || gCodeOptions[opt] != options[opt];
|
||||
gCodeOptions[opt] = options[opt];
|
||||
}
|
||||
_.forOwn(options, function (value, key) {
|
||||
if (value === undefined) return;
|
||||
dirty = dirty || gCodeOptions[key] !== value;
|
||||
gCodeOptions[key] = value;
|
||||
});
|
||||
if (dirty) {
|
||||
if (model && model.length > 0) this.passDataToRenderer();
|
||||
}
|
||||
|
||||
@@ -156,7 +156,8 @@ GCODE.ui = (function () {
|
||||
});
|
||||
GCODE.gCodeReader.setOption({
|
||||
toolOffsets: options.toolOffsets,
|
||||
bed: options.bed
|
||||
bed: options.bed,
|
||||
bedZ: options.bedZ
|
||||
});
|
||||
GCODE.renderer.render(0, 0);
|
||||
|
||||
|
||||
@@ -715,6 +715,7 @@ var parseGCode = function (message) {
|
||||
bed = message.options.bed;
|
||||
ignoreOutsideBed = message.options.ignoreOutsideBed;
|
||||
g90InfluencesExtruder = message.options.g90InfluencesExtruder;
|
||||
boundingBox.minZ = min.z = message.options.bedZ;
|
||||
|
||||
doParse();
|
||||
gcode = [];
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<form class="form-horizontal" onsubmit="return false;">
|
||||
<div class="control-group" title="{{ _('Maximum size for which the GCode Viewer autoloads the file for preview')|edq }}">
|
||||
<label class="control-label" for="settings-featureSizeThreshold">{{ _('GCode Viewer file size threshold') }}</label>
|
||||
<label class="control-label" for="settings-gcodeviewer-featureSizeThreshold">{{ _('GCode Viewer file size threshold') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="text" class="input-mini text-right" data-bind="value: sizeThresholdStr" id="settings-featureSizeThreshold">
|
||||
<input type="text" class="input-mini text-right" data-bind="value: sizeThresholdStr" id="settings-gcodeviewer-featureSizeThreshold">
|
||||
</div>
|
||||
<span class="help-inline">{{ _('on desktop')}}</span>
|
||||
</div>
|
||||
@@ -19,12 +19,10 @@
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Skip/Hide gcode until this string')}}">
|
||||
<label class="control-label" for="settings-skipUntilThis">{{ _('Skip to this') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: settings.settings.plugins.gcodeviewer.skipUntilThis" id="settings-skipUntilThis" placeholder="; layer 1">
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Skip/hide gcode until this string')}}">
|
||||
<label class="control-label" for="settings-gcodeviewer-skipUntilThis">{{ _('Skip to this') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: settings.settings.plugins.gcodeviewer.skipUntilThis" id="settings-gcodeviewer-skipUntilThis" placeholder="; layer 1">
|
||||
<span class="help-inline">
|
||||
{% trans %}If provided, the GCode Viewer will search for a line beginning with this string. If found, all GCode up to that point will be skipped. This can be used to skip "purge/nozzle wipe" GCode in the viewer. Note the search is case sensitive. Example: <code>; layer 1</code>{% endtrans %}
|
||||
</span>
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import os
|
||||
from os import scandir
|
||||
|
||||
import yaml
|
||||
from flask import jsonify, make_response, request, url_for
|
||||
from flask import abort, jsonify, request, url_for
|
||||
from flask_babel import gettext
|
||||
from werkzeug.exceptions import BadRequest
|
||||
from werkzeug.utils import secure_filename
|
||||
@@ -17,6 +16,7 @@ from octoprint.access.permissions import Permissions
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.server.util.flask import no_firstrun_access, redirect_to_tornado
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import is_hidden_path
|
||||
|
||||
|
||||
class LoggingPlugin(
|
||||
@@ -81,8 +81,12 @@ class LoggingPlugin(
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def delete_log(self, filename):
|
||||
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
|
||||
if not os.path.exists(secure):
|
||||
return make_response("File not found: %s" % filename, 404)
|
||||
if (
|
||||
not os.path.exists(secure)
|
||||
or is_hidden_path(secure)
|
||||
or not filename.endswith(".log")
|
||||
):
|
||||
abort(404)
|
||||
|
||||
os.remove(secure)
|
||||
|
||||
@@ -107,15 +111,15 @@ class LoggingPlugin(
|
||||
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
|
||||
def set_logging_levels_api(self):
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
abort(400, description="Expected content-type JSON")
|
||||
|
||||
try:
|
||||
json_data = request.json
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
abort(400, description="Malformed JSON body in request")
|
||||
|
||||
if not isinstance(json_data, dict):
|
||||
return make_response("Invalid log level configuration", 400)
|
||||
abort(400, description="Invalid log level configuration")
|
||||
|
||||
# TODO validate further
|
||||
|
||||
@@ -135,6 +139,12 @@ class LoggingPlugin(
|
||||
files = []
|
||||
basedir = settings().getBaseFolder("logs", check_writable=False)
|
||||
for entry in scandir(basedir):
|
||||
if is_hidden_path(entry.path) or not entry.name.endswith(".log"):
|
||||
continue
|
||||
|
||||
if not entry.is_file():
|
||||
continue
|
||||
|
||||
files.append(
|
||||
{
|
||||
"name": entry.name,
|
||||
@@ -172,7 +182,7 @@ class LoggingPlugin(
|
||||
if os.path.exists(logging_file) and os.path.isfile(logging_file):
|
||||
import yaml
|
||||
|
||||
with io.open(logging_file, "rt", encoding="utf-8") as f:
|
||||
with open(logging_file, encoding="utf-8") as f:
|
||||
config_from_file = yaml.safe_load(f)
|
||||
return config_from_file
|
||||
|
||||
@@ -231,7 +241,7 @@ class LoggingPlugin(
|
||||
for logger, level in new_levels.items():
|
||||
level = logging.getLevelName(level)
|
||||
|
||||
self._logger.info("Setting logger {} level to {}".format(logger, level))
|
||||
self._logger.info(f"Setting logger {logger} level to {level}")
|
||||
self._logger.manager.loggerDict[logger].setLevel(level)
|
||||
|
||||
def _is_managed_logger(self, logger):
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
this.setupUrl = this.baseUrl + "setup";
|
||||
};
|
||||
|
||||
var bulkDownloadUrl = "downloads/logs";
|
||||
|
||||
OctoPrintLoggingClient.prototype.get = function (opts) {
|
||||
return this.base.get(this.baseUrl, opts);
|
||||
};
|
||||
@@ -31,6 +33,10 @@
|
||||
return this.base.download(fileUrl, opts);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.bulkDownloadUrl = function (filenames) {
|
||||
return this.base.bulkDownloadUrl(bulkDownloadUrl, filenames);
|
||||
};
|
||||
|
||||
OctoPrintLoggingClient.prototype.updateLevels = function (config, opts) {
|
||||
return this.base.putJson(this.setupUrl + "/levels", config, opts);
|
||||
};
|
||||
|
||||
@@ -273,6 +273,27 @@ $(function () {
|
||||
);
|
||||
};
|
||||
|
||||
self.enableBulkDownload = ko.pureComputed(function () {
|
||||
return self.markedForDeletion().length && !self.bulkDownloadUrlTooLong();
|
||||
});
|
||||
|
||||
self.bulkDownloadUrlTooLong = ko.pureComputed(function () {
|
||||
return BASEURL.length + self.bulkDownloadUrl().length >= 2000;
|
||||
});
|
||||
|
||||
self.bulkDownloadButtonUrl = ko.pureComputed(function () {
|
||||
var files = self.markedForDeletion();
|
||||
if (!files.length || self.bulkDownloadUrlTooLong()) {
|
||||
return "javascript:void(0)";
|
||||
}
|
||||
return self.bulkDownloadUrl();
|
||||
});
|
||||
|
||||
self.bulkDownloadUrl = function () {
|
||||
var files = self.markedForDeletion();
|
||||
return OctoPrint.plugins.logging.bulkDownloadUrl(files);
|
||||
};
|
||||
|
||||
self.onServerReconnect = self.onUserLoggedIn = self.onEventSettingsUpdated = self.onSettingsShown = function () {
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
</ul>
|
||||
</div>
|
||||
<button class="btn btn-small" data-bind="click: removeMarkedFiles, enable: markedForDeletion().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="log_files">
|
||||
<thead>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import os
|
||||
|
||||
import flask
|
||||
@@ -95,7 +94,7 @@ class ThrottleState:
|
||||
self._past_throttled = False
|
||||
|
||||
for key, value in kwargs.items():
|
||||
local_key = "_{}".format(key)
|
||||
local_key = f"_{key}"
|
||||
if hasattr(self, local_key) and isinstance(value, bool):
|
||||
setattr(self, local_key, value)
|
||||
|
||||
@@ -141,7 +140,7 @@ class ThrottleState:
|
||||
|
||||
@property
|
||||
def raw_value_hex(self):
|
||||
return "0x{:X}".format(self._raw_value)
|
||||
return f"0x{self._raw_value:X}"
|
||||
|
||||
def __eq__(self, other):
|
||||
if not isinstance(other, ThrottleState):
|
||||
@@ -176,7 +175,7 @@ def get_proc_dt_model():
|
||||
global _proc_dt_model
|
||||
|
||||
if _proc_dt_model is None:
|
||||
with io.open(_PROC_DT_MODEL_PATH, "rt", encoding="utf-8") as f:
|
||||
with open(_PROC_DT_MODEL_PATH, encoding="utf-8") as f:
|
||||
_proc_dt_model = f.readline().strip(" \t\r\n\0")
|
||||
|
||||
return _proc_dt_model
|
||||
@@ -189,7 +188,7 @@ def get_vcgencmd_throttled_state(command):
|
||||
output = sarge.get_stdout(command, close_fds=CLOSE_FDS)
|
||||
|
||||
if "throttled=0x" not in output:
|
||||
raise ValueError('cannot parse "{}" output: {}'.format(command, output))
|
||||
raise ValueError(f'cannot parse "{command}" output: {output}')
|
||||
|
||||
value = output[len("throttled=") :].strip(" \t\r\n\0")
|
||||
value = int(value, 0)
|
||||
@@ -207,7 +206,7 @@ def get_octopi_version():
|
||||
global _octopi_version
|
||||
|
||||
if _octopi_version is None:
|
||||
with io.open(_OCTOPI_VERSION_PATH, "rt", encoding="utf-8") as f:
|
||||
with open(_OCTOPI_VERSION_PATH, encoding="utf-8") as f:
|
||||
_octopi_version = f.readline().strip(" \t\r\n\0")
|
||||
|
||||
return _octopi_version
|
||||
@@ -362,7 +361,7 @@ class PiSupportPlugin(
|
||||
def _check_throttled_state(self):
|
||||
command = self._settings.get(["vcgencmd_throttle_check_command"])
|
||||
|
||||
self._logger.debug('Retrieving throttle state via "{}"'.format(command))
|
||||
self._logger.debug(f'Retrieving throttle state via "{command}"')
|
||||
try:
|
||||
state = get_vcgencmd_throttled_state(command)
|
||||
except ValueError:
|
||||
|
||||
@@ -3,7 +3,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import copy
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
@@ -19,7 +18,7 @@ import filetype
|
||||
import pkg_resources
|
||||
import requests
|
||||
import sarge
|
||||
from flask import jsonify, make_response
|
||||
from flask import Response, abort, jsonify, request
|
||||
from flask_babel import gettext
|
||||
|
||||
import octoprint.plugin
|
||||
@@ -27,13 +26,14 @@ import octoprint.plugin.core
|
||||
from octoprint.access import ADMIN_GROUP
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.events import Events
|
||||
from octoprint.server import safe_mode
|
||||
from octoprint.server.util.flask import (
|
||||
check_etag,
|
||||
no_firstrun_access,
|
||||
with_revalidation_checking,
|
||||
)
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.util import TemporaryDirectory, to_bytes
|
||||
from octoprint.util import TemporaryDirectory, deprecated, to_bytes
|
||||
from octoprint.util.net import download_file
|
||||
from octoprint.util.pip import create_pip_caller
|
||||
from octoprint.util.platform import get_os, is_os_compatible
|
||||
@@ -358,7 +358,7 @@ class PluginManagerPlugin(
|
||||
input_upload_path not in flask.request.values
|
||||
or input_upload_name not in flask.request.values
|
||||
):
|
||||
return flask.make_response("No file included", 400)
|
||||
abort(400, description="No file included")
|
||||
upload_path = flask.request.values[input_upload_path]
|
||||
upload_name = flask.request.values[input_upload_name]
|
||||
|
||||
@@ -369,9 +369,9 @@ class PluginManagerPlugin(
|
||||
)
|
||||
)
|
||||
if not len(exts):
|
||||
return flask.make_response(
|
||||
"File doesn't have a valid extension for a plugin archive or a single file plugin",
|
||||
abort(
|
||||
400,
|
||||
description="File doesn't have a valid extension for a plugin archive or a single file plugin",
|
||||
)
|
||||
|
||||
ext = exts[0]
|
||||
@@ -398,7 +398,7 @@ class PluginManagerPlugin(
|
||||
|
||||
with self._install_lock:
|
||||
if self._install_task is not None:
|
||||
return make_response("There's already a plugin being installed", 409)
|
||||
abort(409, description="There's already a plugin being installed")
|
||||
|
||||
self._install_task = threading.Thread(
|
||||
target=perform_install,
|
||||
@@ -419,16 +419,159 @@ class PluginManagerPlugin(
|
||||
def export_plugin_list(self):
|
||||
import json
|
||||
|
||||
import flask
|
||||
|
||||
plugins = self.generate_plugins_json(self._settings, self._plugin_manager)
|
||||
|
||||
return flask.Response(
|
||||
return Response(
|
||||
json.dumps(plugins),
|
||||
mimetype="text/plain",
|
||||
headers={"Content-Disposition": 'attachment; filename="plugin_list.json"'},
|
||||
)
|
||||
|
||||
def _plugin_response(self):
|
||||
return {
|
||||
"plugins": self._get_plugins(),
|
||||
"os": get_os(),
|
||||
"octoprint": get_octoprint_version_string(),
|
||||
"pip": {
|
||||
"available": self._pip_caller.available,
|
||||
"version": self._pip_caller.version_string,
|
||||
"install_dir": self._pip_caller.install_dir,
|
||||
"use_user": self._pip_caller.use_user,
|
||||
"virtual_env": self._pip_caller.virtual_env,
|
||||
"additional_args": self._settings.get(["pip_args"]),
|
||||
"python": sys.executable,
|
||||
},
|
||||
"safe_mode": safe_mode,
|
||||
"online": self._connectivity_checker.online,
|
||||
}
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/plugins")
|
||||
@Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403)
|
||||
def retrieve_plugins(self):
|
||||
refresh = request.values.get("refresh", "false") in valid_boolean_trues
|
||||
if refresh or not self._is_notices_cache_valid():
|
||||
self._notices_available = self._refresh_notices()
|
||||
|
||||
def view():
|
||||
return jsonify(**self._plugin_response())
|
||||
|
||||
def etag():
|
||||
import hashlib
|
||||
|
||||
hash = hashlib.sha1()
|
||||
|
||||
def hash_update(value):
|
||||
value = value.encode("utf-8")
|
||||
hash.update(value)
|
||||
|
||||
hash_update(repr(self._get_plugins()))
|
||||
hash_update(str(self._notices_available))
|
||||
hash_update(repr(self._notices))
|
||||
hash_update(repr(safe_mode))
|
||||
hash_update(repr(self._connectivity_checker.online))
|
||||
hash_update(repr(_DATA_FORMAT_VERSION))
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
return check_etag(etag())
|
||||
|
||||
return with_revalidation_checking(
|
||||
etag_factory=lambda *args, **kwargs: etag(),
|
||||
condition=lambda *args, **kwargs: condition(),
|
||||
unless=lambda: refresh,
|
||||
)(view)()
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/plugins/<string:key>")
|
||||
@Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403)
|
||||
def retrieve_specific_plugin(self, key):
|
||||
plugin = self._plugin_manager.get_plugin_info(key, require_enabled=False)
|
||||
if plugin is None:
|
||||
return abort(404)
|
||||
|
||||
return jsonify(plugin=self._to_external_plugin(plugin))
|
||||
|
||||
def _orphan_response(self):
|
||||
return {"orphan_data": self._get_orphans()}
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/orphans")
|
||||
@Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403)
|
||||
def retrieve_plugin_orphans(self):
|
||||
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
|
||||
abort(403)
|
||||
|
||||
refresh = request.values.get("refresh", "false") in valid_boolean_trues
|
||||
if refresh:
|
||||
self._get_orphans(refresh=True)
|
||||
|
||||
def view():
|
||||
return jsonify(**self._orphan_response())
|
||||
|
||||
def etag():
|
||||
import hashlib
|
||||
|
||||
hash = hashlib.sha1()
|
||||
|
||||
def hash_update(value):
|
||||
value = value.encode("utf-8")
|
||||
hash.update(value)
|
||||
|
||||
hash_update(repr(self._get_orphans()))
|
||||
hash_update(repr(_DATA_FORMAT_VERSION))
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
return check_etag(etag())
|
||||
|
||||
return with_revalidation_checking(
|
||||
etag_factory=lambda *args, **kwargs: etag(),
|
||||
condition=lambda *args, **kwargs: condition(),
|
||||
unless=lambda: refresh,
|
||||
)(view)()
|
||||
|
||||
def _repository_response(self):
|
||||
return {
|
||||
"repository": {
|
||||
"available": self._repository_available,
|
||||
"plugins": self._repository_plugins,
|
||||
}
|
||||
}
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/repository")
|
||||
@Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403)
|
||||
def retrieve_plugin_repository(self):
|
||||
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
|
||||
abort(403)
|
||||
|
||||
refresh = request.values.get("refresh", "false") in valid_boolean_trues
|
||||
if refresh or not self._is_repository_cache_valid():
|
||||
self._repository_available = self._refresh_repository()
|
||||
|
||||
def view():
|
||||
return jsonify(**self._repository_response())
|
||||
|
||||
def etag():
|
||||
import hashlib
|
||||
|
||||
hash = hashlib.sha1()
|
||||
|
||||
def hash_update(value):
|
||||
value = value.encode("utf-8")
|
||||
hash.update(value)
|
||||
|
||||
hash_update(str(self._repository_available))
|
||||
hash_update(repr(self._repository_plugins))
|
||||
hash_update(repr(_DATA_FORMAT_VERSION))
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
return check_etag(etag())
|
||||
|
||||
return with_revalidation_checking(
|
||||
etag_factory=lambda *args, **kwargs: etag(),
|
||||
condition=lambda *args, **kwargs: condition(),
|
||||
unless=lambda: refresh,
|
||||
)(view)()
|
||||
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
@@ -458,97 +601,23 @@ class PluginManagerPlugin(
|
||||
"refresh_repository": [],
|
||||
}
|
||||
|
||||
def on_api_get(self, request):
|
||||
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
|
||||
return make_response("Insufficient rights", 403)
|
||||
|
||||
from octoprint.server import safe_mode
|
||||
|
||||
refresh_repository = (
|
||||
request.values.get("refresh_repository", "false") in valid_boolean_trues
|
||||
)
|
||||
if refresh_repository or not self._is_repository_cache_valid():
|
||||
self._repository_available = self._refresh_repository()
|
||||
|
||||
refresh_notices = (
|
||||
request.values.get("refresh_notices", "false") in valid_boolean_trues
|
||||
)
|
||||
if refresh_notices or not self._is_notices_cache_valid():
|
||||
self._notices_available = self._refresh_notices()
|
||||
|
||||
refresh_orphan = (
|
||||
request.values.get("refresh_orphans", "false") in valid_boolean_trues
|
||||
)
|
||||
|
||||
def view():
|
||||
return jsonify(
|
||||
plugins=self._get_plugins(),
|
||||
repository={
|
||||
"available": self._repository_available,
|
||||
"plugins": self._repository_plugins,
|
||||
},
|
||||
orphan_data=self._get_orphans(refresh=refresh_orphan),
|
||||
os=get_os(),
|
||||
octoprint=get_octoprint_version_string(),
|
||||
pip={
|
||||
"available": self._pip_caller.available,
|
||||
"version": self._pip_caller.version_string,
|
||||
"install_dir": self._pip_caller.install_dir,
|
||||
"use_user": self._pip_caller.use_user,
|
||||
"virtual_env": self._pip_caller.virtual_env,
|
||||
"additional_args": self._settings.get(["pip_args"]),
|
||||
"python": sys.executable,
|
||||
},
|
||||
safe_mode=safe_mode,
|
||||
online=self._connectivity_checker.online,
|
||||
)
|
||||
|
||||
def etag():
|
||||
import hashlib
|
||||
|
||||
hash = hashlib.sha1()
|
||||
|
||||
def hash_update(value):
|
||||
value = value.encode("utf-8")
|
||||
hash.update(value)
|
||||
|
||||
hash_update(repr(self._get_plugins()))
|
||||
hash_update(str(self._repository_available))
|
||||
hash_update(repr(self._repository_plugins))
|
||||
hash_update(str(self._notices_available))
|
||||
hash_update(repr(self._notices))
|
||||
hash_update(repr(self._get_orphans()))
|
||||
hash_update(repr(safe_mode))
|
||||
hash_update(repr(self._connectivity_checker.online))
|
||||
hash_update(repr(_DATA_FORMAT_VERSION))
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
return check_etag(etag())
|
||||
|
||||
return with_revalidation_checking(
|
||||
etag_factory=lambda *args, **kwargs: etag(),
|
||||
condition=lambda *args, **kwargs: condition(),
|
||||
unless=lambda: refresh_repository or refresh_notices or refresh_orphan,
|
||||
)(view)()
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
|
||||
return make_response("Insufficient rights", 403)
|
||||
abort(403)
|
||||
|
||||
if self._printer.is_printing() or self._printer.is_paused():
|
||||
# do not update while a print job is running
|
||||
return make_response("Printer is currently printing or paused", 409)
|
||||
abort(409, description="Printer is currently printing or paused")
|
||||
|
||||
if command == "install":
|
||||
if not Permissions.PLUGIN_PLUGINMANAGER_INSTALL.can():
|
||||
return make_response("Insufficient rights", 403)
|
||||
abort(403)
|
||||
url = data["url"]
|
||||
plugin_name = data["plugin"] if "plugin" in data else None
|
||||
|
||||
with self._install_lock:
|
||||
if self._install_task is not None:
|
||||
return make_response("There's already a plugin being installed", 409)
|
||||
abort(409, description="There's already a plugin being installed")
|
||||
|
||||
self._install_task = threading.Thread(
|
||||
target=self.command_install,
|
||||
@@ -568,7 +637,7 @@ class PluginManagerPlugin(
|
||||
elif command == "uninstall":
|
||||
plugin_name = data["plugin"]
|
||||
if plugin_name not in self._plugin_manager.plugins:
|
||||
return make_response("Unknown plugin: %s" % plugin_name, 404)
|
||||
abort(404, description="Unknown plugin")
|
||||
|
||||
plugin = self._plugin_manager.plugins[plugin_name]
|
||||
return self.command_uninstall(plugin, cleanup=data.get("cleanup", False))
|
||||
@@ -589,11 +658,44 @@ class PluginManagerPlugin(
|
||||
elif command == "enable" or command == "disable":
|
||||
plugin_name = data["plugin"]
|
||||
if plugin_name not in self._plugin_manager.plugins:
|
||||
return make_response("Unknown plugin: %s" % plugin_name, 404)
|
||||
abort(404, description="Unknown plugin")
|
||||
|
||||
plugin = self._plugin_manager.plugins[plugin_name]
|
||||
return self.command_toggle(plugin, command)
|
||||
|
||||
@deprecated(
|
||||
"Deprecated API endpoint api/plugin/pluginmanager used. "
|
||||
"Please switch clients to plugin/pluginmanager/*",
|
||||
since="1.6.0",
|
||||
)
|
||||
def on_api_get(self, r):
|
||||
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
|
||||
abort(403)
|
||||
|
||||
refresh_repository = (
|
||||
request.values.get("refresh_repository", "false") in valid_boolean_trues
|
||||
)
|
||||
if refresh_repository or not self._is_repository_cache_valid():
|
||||
self._repository_available = self._refresh_repository()
|
||||
|
||||
refresh_notices = (
|
||||
request.values.get("refresh_notices", "false") in valid_boolean_trues
|
||||
)
|
||||
if refresh_notices or not self._is_notices_cache_valid():
|
||||
self._notices_available = self._refresh_notices()
|
||||
|
||||
refresh_orphan = (
|
||||
request.values.get("refresh_orphans", "false") in valid_boolean_trues
|
||||
)
|
||||
if refresh_orphan:
|
||||
self._get_orphans(refresh=True)
|
||||
|
||||
result = {}
|
||||
result.update(**self._plugin_response())
|
||||
result.update(**self._orphan_response())
|
||||
result.update(**self._repository_response())
|
||||
return jsonify(**result)
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def _is_archive(self, path):
|
||||
_, ext = os.path.splitext(path)
|
||||
@@ -602,7 +704,7 @@ class PluginManagerPlugin(
|
||||
|
||||
kind = filetype.guess(path)
|
||||
if kind:
|
||||
return ".{}".format(kind.extension) in PluginManagerPlugin.ARCHIVE_EXTENSIONS
|
||||
return f".{kind.extension}" in PluginManagerPlugin.ARCHIVE_EXTENSIONS
|
||||
return False
|
||||
|
||||
def _is_pythonfile(self, path):
|
||||
@@ -611,13 +713,11 @@ class PluginManagerPlugin(
|
||||
import ast
|
||||
|
||||
try:
|
||||
with io.open(path, "rb") as f:
|
||||
with open(path, "rb") as f:
|
||||
ast.parse(f.read(), filename=path)
|
||||
return True
|
||||
except Exception as exc:
|
||||
self._logger.exception(
|
||||
"Could not parse {} as python file: {}".format(path, exc)
|
||||
)
|
||||
self._logger.exception(f"Could not parse {path} as python file: {exc}")
|
||||
|
||||
return False
|
||||
|
||||
@@ -664,12 +764,12 @@ class PluginManagerPlugin(
|
||||
raise exceptions.InvalidPackageFormat()
|
||||
|
||||
except requests.exceptions.HTTPError as e:
|
||||
self._logger.error("Could not fetch plugin from server, got {}".format(e))
|
||||
self._logger.error(f"Could not fetch plugin from server, got {e}")
|
||||
result = {
|
||||
"result": False,
|
||||
"source": source,
|
||||
"source_type": source_type,
|
||||
"reason": "Could not fetch plugin from server, got {}".format(e),
|
||||
"reason": f"Could not fetch plugin from server, got {e}",
|
||||
}
|
||||
self._send_result_notification("install", result)
|
||||
|
||||
@@ -760,7 +860,7 @@ class PluginManagerPlugin(
|
||||
lambda line: path_url in line.lower()
|
||||
) # lower case in case of windows
|
||||
|
||||
self._logger.info("Installing plugin from {}".format(source))
|
||||
self._logger.info(f"Installing plugin from {source}")
|
||||
pip_args = [
|
||||
"--disable-pip-version-check",
|
||||
"install",
|
||||
@@ -806,7 +906,7 @@ class PluginManagerPlugin(
|
||||
)
|
||||
force = True
|
||||
except Exception as e:
|
||||
self._logger.exception("Could not install plugin from {}".format(source))
|
||||
self._logger.exception(f"Could not install plugin from {source}")
|
||||
self._logger.exception("Reason: {}".format(repr(e)))
|
||||
result = {
|
||||
"result": False,
|
||||
@@ -827,9 +927,7 @@ class PluginManagerPlugin(
|
||||
try:
|
||||
returncode, stdout, stderr = self._call_pip(pip_args)
|
||||
except Exception as e:
|
||||
self._logger.exception(
|
||||
"Could not install plugin from {}".format(source)
|
||||
)
|
||||
self._logger.exception(f"Could not install plugin from {source}")
|
||||
self._logger.exception("Reason: {}".format(repr(e)))
|
||||
result = {
|
||||
"result": False,
|
||||
@@ -989,7 +1087,7 @@ class PluginManagerPlugin(
|
||||
if name is None:
|
||||
name = os.path.basename(path)
|
||||
|
||||
self._logger.info("Installing single file plugin {} from {}".format(name, source))
|
||||
self._logger.info(f"Installing single file plugin {name} from {source}")
|
||||
|
||||
all_plugins_before = self._plugin_manager.find_plugins(existing={})
|
||||
|
||||
@@ -997,10 +1095,10 @@ class PluginManagerPlugin(
|
||||
plugin_id, _ = os.path.splitext(name)
|
||||
|
||||
try:
|
||||
self._log_call("cp {} {}".format(path, destination))
|
||||
self._log_call(f"cp {path} {destination}")
|
||||
shutil.copy(path, destination)
|
||||
except Exception:
|
||||
self._logger.exception("Installing plugin from {} failed".format(source))
|
||||
self._logger.exception(f"Installing plugin from {source} failed")
|
||||
result = {
|
||||
"result": False,
|
||||
"source": source,
|
||||
@@ -1076,15 +1174,15 @@ class PluginManagerPlugin(
|
||||
|
||||
def command_uninstall(self, plugin, cleanup=False):
|
||||
if plugin.key == "pluginmanager":
|
||||
return make_response("Can't uninstall Plugin Manager", 403)
|
||||
abort(403, description="Can't uninstall Plugin Manager")
|
||||
|
||||
if not plugin.managable:
|
||||
return make_response(
|
||||
"Plugin is not managable and hence cannot be uninstalled", 403
|
||||
abort(
|
||||
403, description="Plugin is not managable and hence cannot be uninstalled"
|
||||
)
|
||||
|
||||
if plugin.bundled:
|
||||
return make_response("Bundled plugins cannot be uninstalled", 403)
|
||||
abort(403, description="Bundled plugins cannot be uninstalled")
|
||||
|
||||
if plugin.origin is None:
|
||||
self._logger.warning(
|
||||
@@ -1092,7 +1190,7 @@ class PluginManagerPlugin(
|
||||
**locals()
|
||||
)
|
||||
)
|
||||
return make_response("Could not uninstall plugin, its origin is unknown")
|
||||
abort(500, description="Could not uninstall plugin, its origin is unknown")
|
||||
|
||||
if plugin.origin.type == "entry_point":
|
||||
# plugin is installed through entry point, need to use pip to uninstall it
|
||||
@@ -1105,9 +1203,9 @@ class PluginManagerPlugin(
|
||||
self._call_pip(pip_args)
|
||||
except Exception:
|
||||
self._logger.exception("Could not uninstall plugin via pip")
|
||||
return make_response(
|
||||
"Could not uninstall plugin via pip, see the log for more details",
|
||||
abort(
|
||||
500,
|
||||
description="Could not uninstall plugin via pip, see the log for more details",
|
||||
)
|
||||
|
||||
elif plugin.origin.type == "folder":
|
||||
@@ -1118,22 +1216,16 @@ class PluginManagerPlugin(
|
||||
|
||||
if os.path.isdir(full_path):
|
||||
# plugin is installed via a plugin folder, need to use rmtree to get rid of it
|
||||
self._log_stdout(
|
||||
"Deleting plugin from {folder}".format(folder=plugin.location)
|
||||
)
|
||||
self._log_stdout(f"Deleting plugin from {plugin.location}")
|
||||
shutil.rmtree(full_path)
|
||||
elif os.path.isfile(full_path):
|
||||
self._log_stdout(
|
||||
"Deleting plugin from {file}".format(file=plugin.location)
|
||||
)
|
||||
self._log_stdout(f"Deleting plugin from {plugin.location}")
|
||||
os.remove(full_path)
|
||||
|
||||
if full_path.endswith(".py"):
|
||||
pyc_file = "{full_path}c".format(**locals())
|
||||
if os.path.isfile(pyc_file):
|
||||
self._log_stdout(
|
||||
"Deleting plugin from {file}".format(file=pyc_file)
|
||||
)
|
||||
self._log_stdout(f"Deleting plugin from {pyc_file}")
|
||||
os.remove(pyc_file)
|
||||
|
||||
else:
|
||||
@@ -1142,7 +1234,7 @@ class PluginManagerPlugin(
|
||||
**locals()
|
||||
)
|
||||
)
|
||||
return make_response("Could not uninstall plugin, its origin is unknown")
|
||||
abort(500, description="Could not uninstall plugin, its origin is unknown")
|
||||
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) or cleanup
|
||||
needs_refresh = plugin.implementation and isinstance(
|
||||
@@ -1167,9 +1259,7 @@ class PluginManagerPlugin(
|
||||
if plugin.enabled:
|
||||
self._plugin_manager.disable_plugin(plugin.key, plugin=plugin)
|
||||
except octoprint.plugin.core.PluginLifecycleException as e:
|
||||
self._logger.exception(
|
||||
"Problem disabling plugin {name}".format(name=plugin.key)
|
||||
)
|
||||
self._logger.exception(f"Problem disabling plugin {plugin.key}")
|
||||
result = {
|
||||
"result": False,
|
||||
"uninstalled": True,
|
||||
@@ -1184,9 +1274,7 @@ class PluginManagerPlugin(
|
||||
if plugin.loaded:
|
||||
self._plugin_manager.unload_plugin(plugin.key)
|
||||
except octoprint.plugin.core.PluginLifecycleException as e:
|
||||
self._logger.exception(
|
||||
"Problem unloading plugin {name}".format(name=plugin.key)
|
||||
)
|
||||
self._logger.exception(f"Problem unloading plugin {plugin.key}")
|
||||
result = {
|
||||
"result": False,
|
||||
"uninstalled": True,
|
||||
@@ -1213,7 +1301,7 @@ class PluginManagerPlugin(
|
||||
"plugin": self._to_external_plugin(plugin),
|
||||
}
|
||||
self._send_result_notification("uninstall", result)
|
||||
self._logger.info("Plugin {} uninstalled".format(plugin.key))
|
||||
self._logger.info(f"Plugin {plugin.key} uninstalled")
|
||||
|
||||
self._cleanup_disabled(plugin.key)
|
||||
if cleanup:
|
||||
@@ -1234,7 +1322,7 @@ class PluginManagerPlugin(
|
||||
key = plugin.key
|
||||
result_value = self._to_external_plugin(plugin)
|
||||
|
||||
message = "Cleaning up plugin {}...".format(key)
|
||||
message = f"Cleaning up plugin {key}..."
|
||||
self._logger.info(message)
|
||||
self._log_stdout(message)
|
||||
|
||||
@@ -1248,7 +1336,7 @@ class PluginManagerPlugin(
|
||||
# delete plugin data folder
|
||||
result_data = True
|
||||
if not self._cleanup_data(key):
|
||||
message = "Could not delete data folder of plugin {}".format(key)
|
||||
message = f"Could not delete data folder of plugin {key}"
|
||||
self._logger.exception(message)
|
||||
self._log_stderr(message)
|
||||
result_data = False
|
||||
@@ -1322,7 +1410,7 @@ class PluginManagerPlugin(
|
||||
return True
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Could not delete plugin data folder at {}".format(data_folder)
|
||||
f"Could not delete plugin data folder at {data_folder}"
|
||||
)
|
||||
return False
|
||||
else:
|
||||
@@ -1330,7 +1418,7 @@ class PluginManagerPlugin(
|
||||
|
||||
def command_toggle(self, plugin, command):
|
||||
if plugin.key == "pluginmanager" or (plugin.hidden and plugin.bundled):
|
||||
return make_response("Can't enable/disable Plugin Manager", 400)
|
||||
abort(400, description="Can't enable/disable Plugin Manager")
|
||||
|
||||
pending = (command == "disable" and plugin.key in self._pending_enable) or (
|
||||
command == "enable" and plugin.key in self._pending_disable
|
||||
@@ -1576,9 +1664,7 @@ class PluginManagerPlugin(
|
||||
try:
|
||||
import json
|
||||
|
||||
with io.open(
|
||||
self._repository_cache_path, "rt", encoding="utf-8"
|
||||
) as f:
|
||||
with open(self._repository_cache_path, encoding="utf-8") as f:
|
||||
repo_data = json.load(f)
|
||||
self._repository_mtime = mtime
|
||||
self._logger.info(
|
||||
@@ -1604,9 +1690,7 @@ class PluginManagerPlugin(
|
||||
try:
|
||||
r = requests.get(repository_url, timeout=30)
|
||||
r.raise_for_status()
|
||||
self._logger.info(
|
||||
"Loaded plugin repository data from {}".format(repository_url)
|
||||
)
|
||||
self._logger.info(f"Loaded plugin repository data from {repository_url}")
|
||||
except Exception as e:
|
||||
self._logger.exception(
|
||||
"Could not fetch plugins from repository at {repository_url}: {message}".format(
|
||||
@@ -1618,13 +1702,13 @@ class PluginManagerPlugin(
|
||||
try:
|
||||
repo_data = r.json()
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while reading repository data: {}".format(e))
|
||||
self._logger.exception(f"Error while reading repository data: {e}")
|
||||
return None
|
||||
|
||||
# validation
|
||||
if not isinstance(repo_data, (list, tuple)):
|
||||
self._logger.warning(
|
||||
"Invalid repository data: expected a list, got {!r}".format(repo_data)
|
||||
f"Invalid repository data: expected a list, got {repo_data!r}"
|
||||
)
|
||||
return None
|
||||
|
||||
@@ -1671,7 +1755,7 @@ class PluginManagerPlugin(
|
||||
try:
|
||||
import json
|
||||
|
||||
with io.open(self._notices_cache_path, "rt", encoding="utf-8") as f:
|
||||
with open(self._notices_cache_path, encoding="utf-8") as f:
|
||||
notice_data = json.load(f)
|
||||
self._notices_mtime = mtime
|
||||
self._logger.info("Loaded notice data from disk, was still valid")
|
||||
@@ -1695,7 +1779,7 @@ class PluginManagerPlugin(
|
||||
try:
|
||||
r = requests.get(notices_url, timeout=30)
|
||||
r.raise_for_status()
|
||||
self._logger.info("Loaded plugin notices data from {}".format(notices_url))
|
||||
self._logger.info(f"Loaded plugin notices data from {notices_url}")
|
||||
except Exception as e:
|
||||
self._logger.exception(
|
||||
"Could not fetch notices from {notices_url}: {message}".format(
|
||||
|
||||
@@ -10,6 +10,10 @@
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.get = function (refresh, opts) {
|
||||
console.log(
|
||||
"Deprecated endpoint OctoPrint.plugin.pluginmanager.get, " +
|
||||
"please use OctoPrint.plugin.pluginmanager.get*"
|
||||
);
|
||||
var refresh_repo, refresh_notices, refresh_orphans;
|
||||
if (_.isPlainObject(refresh)) {
|
||||
refresh_repo = refresh.repo || false;
|
||||
@@ -34,13 +38,41 @@
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.getWithRefresh = function (opts) {
|
||||
console.log(
|
||||
"Deprecated endpoint OctoPrint.plugin.pluginmanager.getWithRefresh, " +
|
||||
"please use OctoPrint.plugin.pluginmanager.get*"
|
||||
);
|
||||
return this.get(true, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.getWithoutRefresh = function (opts) {
|
||||
console.log(
|
||||
"Deprecated endpoint OctoPrint.plugin.pluginmanager.getWithoutRefresh, " +
|
||||
"please use OctoPrint.plugin.pluginmanager.get*"
|
||||
);
|
||||
return this.get(false, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.getPlugins = function (refresh, opts) {
|
||||
var url = this.base.getBlueprintUrl("pluginmanager") + "plugins";
|
||||
return this.base.get(url + (refresh ? "?refresh=true" : ""), opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.getPlugin = function (plugin, opts) {
|
||||
var url = this.base.getBlueprintUrl("pluginmanager") + "plugins/" + plugin;
|
||||
return this.base.get(url, opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.getOrphans = function (refresh, opts) {
|
||||
var url = this.base.getBlueprintUrl("pluginmanager") + "orphans";
|
||||
return this.base.get(url + (refresh ? "?refresh=true" : ""), opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.getRepository = function (refresh, opts) {
|
||||
var url = this.base.getBlueprintUrl("pluginmanager") + "repository";
|
||||
return this.base.get(url + (refresh ? "?refresh=true" : ""), opts);
|
||||
};
|
||||
|
||||
OctoPrintPluginManagerClient.prototype.install = function (
|
||||
pluginUrl,
|
||||
dependencyLinks,
|
||||
|
||||
@@ -50,7 +50,7 @@ $(function () {
|
||||
return !item.enabled;
|
||||
}
|
||||
},
|
||||
"name",
|
||||
"popularity",
|
||||
[],
|
||||
[
|
||||
["bundled", "3rdparty"],
|
||||
@@ -174,7 +174,7 @@ $(function () {
|
||||
"#settings_plugin_pluginmanager_repositorydialog_upload_start"
|
||||
);
|
||||
|
||||
self.repositoryAvailable = ko.observable(false);
|
||||
self.repositoryAvailable = ko.observable(undefined);
|
||||
|
||||
self.repositorySearchQuery = ko.observable();
|
||||
self.repositorySearchQuery.subscribe(function () {
|
||||
@@ -499,17 +499,7 @@ $(function () {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.fromResponse = function (data, options) {
|
||||
self._fromPluginsResponse(data.plugins, options);
|
||||
self._fromOrphanResponse(data.orphan_data, options);
|
||||
self._fromRepositoryResponse(data.repository, options);
|
||||
self._fromPipResponse(data.pip, options);
|
||||
|
||||
self.safeMode(data.safe_mode || false);
|
||||
self.online(data.online !== undefined ? data.online : true);
|
||||
};
|
||||
|
||||
self._fromPluginsResponse = function (data, options) {
|
||||
self.fromPluginsResponse = function (data, options) {
|
||||
var evalNotices = options.eval_notices || false;
|
||||
var ignoreNoticeHidden = options.ignore_notice_hidden || false;
|
||||
var ignoreNoticeIgnored = options.ignore_notice_ignored || false;
|
||||
@@ -549,7 +539,7 @@ $(function () {
|
||||
self.plugins.updateItems(data);
|
||||
};
|
||||
|
||||
self._fromOrphanResponse = function (data) {
|
||||
self.fromOrphanResponse = function (data) {
|
||||
var orphans = [];
|
||||
_.each(data, function (value, key) {
|
||||
orphans.push({
|
||||
@@ -561,7 +551,7 @@ $(function () {
|
||||
self.orphans.updateItems(orphans);
|
||||
};
|
||||
|
||||
self._fromRepositoryResponse = function (data) {
|
||||
self.fromRepositoryResponse = function (data) {
|
||||
self.repositoryAvailable(data.available);
|
||||
if (data.available) {
|
||||
self.repositoryplugins.updateItems(data.plugins);
|
||||
@@ -570,7 +560,7 @@ $(function () {
|
||||
}
|
||||
};
|
||||
|
||||
self._fromPipResponse = function (data) {
|
||||
self.fromPipResponse = function (data) {
|
||||
self.pipAvailable(data.available);
|
||||
if (data.available) {
|
||||
self.pipVersion(data.version);
|
||||
@@ -588,41 +578,23 @@ $(function () {
|
||||
}
|
||||
};
|
||||
|
||||
self.dataDeferred = undefined;
|
||||
self.requestData = function (options) {
|
||||
self.dataPluginsDeferred = undefined;
|
||||
self.requestPluginData = function (options) {
|
||||
if (!_.isPlainObject(options)) {
|
||||
options = {
|
||||
refresh_repo: options,
|
||||
refresh_orphans: false,
|
||||
refresh_notices: false,
|
||||
eval_notices: false
|
||||
};
|
||||
options = {};
|
||||
}
|
||||
|
||||
options.refresh_repo = options.refresh_repo || false;
|
||||
options.refresh_orphans = options.refresh_orphans || false;
|
||||
options.refresh_notices = options.refresh_notices || false;
|
||||
options.eval_notices = options.eval_notices || false;
|
||||
|
||||
if (
|
||||
self.dataDeferred &&
|
||||
self.dataDeferred.state() === "pending" &&
|
||||
!options.refresh_repo &&
|
||||
!options.refresh_orphans &&
|
||||
!options.refresh_notices &&
|
||||
!options.eval_notices
|
||||
self.dataPluginsDeferred &&
|
||||
self.dataPluginsDeferred.state() === "pending" &&
|
||||
!!!options.refresh
|
||||
) {
|
||||
return self.dataDeferred.promise();
|
||||
return self.dataPluginsDeferred.promise();
|
||||
}
|
||||
|
||||
var deferred = new $.Deferred();
|
||||
if (
|
||||
!options.refresh_repo &&
|
||||
!options.refresh_orphans &&
|
||||
!options.refresh_notices &&
|
||||
!options.eval_notices
|
||||
) {
|
||||
self.dataDeferred = deferred;
|
||||
if (!!!options.refresh) {
|
||||
self.dataPluginsDeferred = deferred;
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -635,18 +607,99 @@ $(function () {
|
||||
}
|
||||
|
||||
OctoPrint.plugins.pluginmanager
|
||||
.get({
|
||||
repo: options.refresh_repo,
|
||||
notices: options.refresh_notices,
|
||||
orphans: options.refresh_orphans
|
||||
})
|
||||
.getPlugins(!!options.refresh)
|
||||
.fail(function () {
|
||||
self.requestError(true);
|
||||
deferred.reject();
|
||||
})
|
||||
.done(function (data) {
|
||||
self.requestError(false);
|
||||
self.fromResponse(data, options);
|
||||
self.fromPluginsResponse(data.plugins, options);
|
||||
self.fromPipResponse(data.pip);
|
||||
self.safeMode(data.safe_mode || false);
|
||||
deferred.resolveWith(data);
|
||||
});
|
||||
|
||||
return deferred.promise();
|
||||
};
|
||||
|
||||
self.dataOrphansDeferred = undefined;
|
||||
self.requestOrphanData = function (options) {
|
||||
if (!_.isPlainObject(options)) {
|
||||
options = {};
|
||||
}
|
||||
|
||||
if (
|
||||
self.dataOrphansDeferred &&
|
||||
self.dataOrphansDeferred.state() === "pending" &&
|
||||
!!!options.refresh
|
||||
) {
|
||||
return self.dataOrphansDeferred.promise();
|
||||
}
|
||||
|
||||
var deferred = new $.Deferred();
|
||||
if (!!!options.refresh) {
|
||||
self.dataOrphansDeferred = deferred;
|
||||
}
|
||||
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE
|
||||
)
|
||||
) {
|
||||
deferred.fail();
|
||||
return deferred.promise();
|
||||
}
|
||||
|
||||
OctoPrint.plugins.pluginmanager
|
||||
.getOrphans(!!options.refresh)
|
||||
.fail(function () {
|
||||
deferred.reject();
|
||||
})
|
||||
.done(function (data) {
|
||||
self.fromOrphanResponse(data.orphans);
|
||||
deferred.resolveWith(data);
|
||||
});
|
||||
|
||||
return deferred.promise();
|
||||
};
|
||||
|
||||
self.dataRepositoryDeferred = undefined;
|
||||
self.requestRepositoryData = function (options) {
|
||||
if (!_.isPlainObject(options)) {
|
||||
options = {};
|
||||
}
|
||||
|
||||
if (
|
||||
self.dataRepositoryDeferred &&
|
||||
self.dataRepositoryDeferred.state() === "pending" &&
|
||||
!!!options.refresh
|
||||
) {
|
||||
return self.dataRepositoryDeferred.promise();
|
||||
}
|
||||
|
||||
var deferred = new $.Deferred();
|
||||
if (!!!options.refresh) {
|
||||
self.dataRepositoryDeferred = deferred;
|
||||
}
|
||||
|
||||
if (
|
||||
!self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE
|
||||
)
|
||||
) {
|
||||
deferred.fail();
|
||||
return deferred.promise();
|
||||
}
|
||||
|
||||
OctoPrint.plugins.pluginmanager
|
||||
.getRepository(!!options.refresh)
|
||||
.fail(function () {
|
||||
deferred.reject();
|
||||
})
|
||||
.done(function (data) {
|
||||
self.fromRepositoryResponse(data.repository);
|
||||
self.online(data.online !== undefined ? data.online : true);
|
||||
deferred.resolveWith(data);
|
||||
});
|
||||
|
||||
@@ -669,7 +722,7 @@ $(function () {
|
||||
if (data.key === "pluginmanager") return;
|
||||
|
||||
var onSuccess = function () {
|
||||
self.requestData().always(function () {
|
||||
self.requestPluginData().always(function () {
|
||||
self.toggling(false);
|
||||
});
|
||||
},
|
||||
@@ -891,7 +944,7 @@ $(function () {
|
||||
OctoPrint.plugins.pluginmanager
|
||||
.uninstall(data.key, cleanup)
|
||||
.done(function () {
|
||||
self.requestData();
|
||||
self.requestPluginData();
|
||||
})
|
||||
.fail(function () {
|
||||
new PNotify({
|
||||
@@ -947,7 +1000,7 @@ $(function () {
|
||||
OctoPrint.plugins.pluginmanager
|
||||
.cleanup(key)
|
||||
.done(function () {
|
||||
self.requestData();
|
||||
self.requestOrphanData();
|
||||
})
|
||||
.fail(function () {
|
||||
new PNotify({
|
||||
@@ -1019,7 +1072,7 @@ $(function () {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
self.requestData({refresh_repo: true});
|
||||
self.requestRepositoryData({refresh: true});
|
||||
};
|
||||
|
||||
self.refreshNotices = function () {
|
||||
@@ -1027,8 +1080,8 @@ $(function () {
|
||||
return;
|
||||
}
|
||||
|
||||
self.requestData({
|
||||
refresh_notices: true,
|
||||
self.requestPluginData({
|
||||
refresh: true,
|
||||
eval_notices: true,
|
||||
ignore_notice_hidden: true,
|
||||
ignore_notice_ignored: true
|
||||
@@ -1040,7 +1093,7 @@ $(function () {
|
||||
return;
|
||||
}
|
||||
|
||||
self.requestData({
|
||||
self.requestPluginData({
|
||||
eval_notices: true,
|
||||
ignore_notice_hidden: true,
|
||||
ignore_notice_ignored: true
|
||||
@@ -1098,11 +1151,15 @@ $(function () {
|
||||
self.settingsViewModel.saveData(data, function () {
|
||||
self.configurationDialog.modal("hide");
|
||||
self._copyConfig();
|
||||
self.requestData({
|
||||
refresh_repo: true,
|
||||
refresh_notices: true,
|
||||
self.requestPluginData({
|
||||
refresh: true,
|
||||
eval_notices: true
|
||||
});
|
||||
if (self.repositoryAvailable() !== undefined) {
|
||||
self.requestRepositoryData({
|
||||
refresh: true
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1601,7 +1658,7 @@ $(function () {
|
||||
if (!self.hiddenNoticeNotifications[key]) return false;
|
||||
return _.any(
|
||||
_.map(self.hiddenNoticeNotifications[key], function (d) {
|
||||
return date == d;
|
||||
return date === d;
|
||||
})
|
||||
);
|
||||
};
|
||||
@@ -1656,14 +1713,25 @@ $(function () {
|
||||
self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE
|
||||
)
|
||||
) {
|
||||
self.requestData({eval_notices: true});
|
||||
self.requestPluginData({eval_notices: true});
|
||||
} else {
|
||||
self._resetNotifications();
|
||||
}
|
||||
};
|
||||
|
||||
self.onSettingsShown = function () {
|
||||
if (
|
||||
self.loginState.hasPermission(
|
||||
self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE
|
||||
)
|
||||
) {
|
||||
self.requestRepositoryData();
|
||||
self.requestOrphanData();
|
||||
}
|
||||
};
|
||||
|
||||
self.onEventConnectivityChanged = function (payload) {
|
||||
self.requestData({eval_notices: true});
|
||||
self.requestPluginData({eval_notices: true});
|
||||
};
|
||||
|
||||
self._resetNotifications = function () {
|
||||
@@ -1727,7 +1795,7 @@ $(function () {
|
||||
}
|
||||
|
||||
self._processPluginManagementResult(data, action, name);
|
||||
self.requestData();
|
||||
self.requestPluginData();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -153,7 +153,7 @@
|
||||
</div>
|
||||
<div class="tab-pane" id="settings_plugin_pluginmanager_cleanup">
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.requestData({refresh_orphans: true}) }" title="{{ _('Refresh')|edq }}"><i class="fas fa-sync"></i></button>
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.requestOrphanData({refresh: true}) }" title="{{ _('Refresh')|edq }}"><i class="fas fa-sync"></i></button>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Cleanup') }}</h3>
|
||||
|
||||
@@ -5,7 +5,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import io
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
@@ -334,9 +333,7 @@ class SoftwareUpdatePlugin(
|
||||
data = psutil.disk_usage(path)
|
||||
info["free"] = data.free
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while determining disk usage of {}".format(path)
|
||||
)
|
||||
self._logger.exception(f"Error while determining disk usage of {path}")
|
||||
continue
|
||||
|
||||
storage_info[key] = info
|
||||
@@ -372,15 +369,13 @@ class SoftwareUpdatePlugin(
|
||||
)
|
||||
|
||||
def _get_check_overlay(self, url):
|
||||
self._logger.info("Fetching check overlays from {}".format(url))
|
||||
self._logger.info(f"Fetching check overlays from {url}")
|
||||
try:
|
||||
r = requests.get(url, timeout=3.1)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
except Exception as exc:
|
||||
self._logger.error(
|
||||
"Could not fetch check overlay from {}: {}".format(url, exc)
|
||||
)
|
||||
self._logger.error(f"Could not fetch check overlay from {url}: {exc}")
|
||||
return {}
|
||||
else:
|
||||
return data
|
||||
@@ -426,7 +421,7 @@ class SoftwareUpdatePlugin(
|
||||
import yaml
|
||||
|
||||
try:
|
||||
with io.open(self._version_cache_path, "rt", encoding="utf-8") as f:
|
||||
with open(self._version_cache_path, encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
timestamp = os.stat(self._version_cache_path).st_mtime
|
||||
except Exception:
|
||||
@@ -1012,8 +1007,11 @@ class SoftwareUpdatePlugin(
|
||||
}
|
||||
)
|
||||
except exceptions.ConfigurationInvalid as e:
|
||||
return flask.make_response(
|
||||
"Update not properly configured, can't proceed: {}".format(e), 500
|
||||
flask.abort(
|
||||
500,
|
||||
description="Update not properly configured, can't proceed: {}".format(
|
||||
e
|
||||
),
|
||||
)
|
||||
|
||||
def etag():
|
||||
@@ -1078,30 +1076,35 @@ class SoftwareUpdatePlugin(
|
||||
and not self._settings.get_boolean(["ignore_throttled"])
|
||||
):
|
||||
# currently throttled, we refuse to run
|
||||
return flask.make_response(
|
||||
message = (
|
||||
"System is currently throttled, refusing to update "
|
||||
"anything due to possible stability issues",
|
||||
"anything due to possible stability issues"
|
||||
)
|
||||
self._logger.error(message)
|
||||
flask.abort(
|
||||
409,
|
||||
description=message,
|
||||
)
|
||||
|
||||
if self._printer.is_printing() or self._printer.is_paused():
|
||||
# do not update while a print job is running
|
||||
return flask.make_response("Printer is currently printing or paused", 409)
|
||||
flask.abort(409, description="Printer is currently printing or paused")
|
||||
|
||||
if not self._environment_supported:
|
||||
return flask.make_response(
|
||||
"Direct updates are not supported in this Python environment", 409
|
||||
flask.abort(
|
||||
409,
|
||||
description="Direct updates are not supported in this Python environment",
|
||||
)
|
||||
|
||||
if not self._storage_sufficient:
|
||||
return flask.make_response("Not enough free disk space for updating", 409)
|
||||
flask.abort(409, description="Not enough free disk space for updating")
|
||||
|
||||
if "application/json" not in flask.request.headers["Content-Type"]:
|
||||
return flask.make_response("Expected content-type JSON", 400)
|
||||
flask.abort(400, description="Expected content-type JSON")
|
||||
|
||||
json_data = flask.request.get_json(silent=True)
|
||||
if json_data is None:
|
||||
return flask.make_response("Invalid JSON", 400)
|
||||
flask.abort(400, description="Invalid JSON")
|
||||
|
||||
if "targets" in json_data or "checks" in json_data:
|
||||
targets = list(
|
||||
@@ -1124,7 +1127,7 @@ class SoftwareUpdatePlugin(
|
||||
def configure_update(self):
|
||||
json_data = flask.request.get_json(silent=True)
|
||||
if json_data is None:
|
||||
return flask.make_response("Invalid JSON", 400)
|
||||
flask.abort(400)
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
|
||||
@@ -1136,9 +1139,7 @@ class SoftwareUpdatePlugin(
|
||||
try:
|
||||
populated_check = self._populated_check(target, checks[target])
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.debug(
|
||||
"Ignoring unknown check type for target {}".format(target)
|
||||
)
|
||||
self._logger.debug(f"Ignoring unknown check type for target {target}")
|
||||
continue
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
@@ -1306,7 +1307,7 @@ class SoftwareUpdatePlugin(
|
||||
continue
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Could not check {} for updates".format(target)
|
||||
f"Could not check {target} for updates"
|
||||
)
|
||||
continue
|
||||
|
||||
@@ -1457,7 +1458,7 @@ class SoftwareUpdatePlugin(
|
||||
if isinstance(value, dict):
|
||||
lines.append("{!r}: {}".format(key, dict_to_sorted_repr(value)))
|
||||
else:
|
||||
lines.append("{!r}: {!r}".format(key, value))
|
||||
lines.append(f"{key!r}: {value!r}")
|
||||
|
||||
return "{" + ", ".join(lines) + "}"
|
||||
|
||||
@@ -1534,7 +1535,7 @@ class SoftwareUpdatePlugin(
|
||||
error = "unknown_check"
|
||||
except exceptions.NetworkError:
|
||||
self._logger.warning(
|
||||
"Could not check {} for updates due to a network error".format(target)
|
||||
f"Could not check {target} for updates due to a network error"
|
||||
)
|
||||
update_possible = False
|
||||
error = "network"
|
||||
@@ -1548,12 +1549,12 @@ class SoftwareUpdatePlugin(
|
||||
error = "ratelimit"
|
||||
except exceptions.CheckError:
|
||||
self._logger.warning(
|
||||
"Could not check {} for updates due to a check error".format(target)
|
||||
f"Could not check {target} for updates due to a check error"
|
||||
)
|
||||
update_possible = False
|
||||
error = "check"
|
||||
except Exception:
|
||||
self._logger.exception("Could not check {} for updates".format(target))
|
||||
self._logger.exception(f"Could not check {target} for updates")
|
||||
update_possible = False
|
||||
error = "unknown"
|
||||
else:
|
||||
@@ -1563,9 +1564,7 @@ class SoftwareUpdatePlugin(
|
||||
target, check, online=online
|
||||
)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while checking if {} can be updated".format(target)
|
||||
)
|
||||
self._logger.exception(f"Error while checking if {target} can be updated")
|
||||
update_possible = False
|
||||
|
||||
self._version_cache[target] = {
|
||||
@@ -1605,9 +1604,7 @@ class SoftwareUpdatePlugin(
|
||||
try:
|
||||
populated_checks[target] = self._populated_check(target, check)
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.debug(
|
||||
"Ignoring unknown check type for target {}".format(target)
|
||||
)
|
||||
self._logger.debug(f"Ignoring unknown check type for target {target}")
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while populating check prior to update for target {}".format(
|
||||
@@ -1796,7 +1793,7 @@ class SoftwareUpdatePlugin(
|
||||
|
||||
populated_check = self._populated_check(target, check)
|
||||
try:
|
||||
self._logger.info("Starting update of %s to %s..." % (target, target_version))
|
||||
self._logger.info(f"Starting update of {target} to {target_version}...")
|
||||
self._send_client_message(
|
||||
"updating",
|
||||
{
|
||||
@@ -1813,7 +1810,7 @@ class SoftwareUpdatePlugin(
|
||||
target, populated_check, target_version, log_cb=self._log, online=online
|
||||
)
|
||||
target_result = ("success", update_result)
|
||||
self._logger.info("Update of %s to %s successful!" % (target, target_version))
|
||||
self._logger.info(f"Update of {target} to {target_version} successful!")
|
||||
trigger_event(True)
|
||||
|
||||
except exceptions.UnknownUpdateType:
|
||||
@@ -1918,10 +1915,10 @@ class SoftwareUpdatePlugin(
|
||||
util.execute(restart_command, evaluate_returncode=False, do_async=True)
|
||||
except exceptions.ScriptError as e:
|
||||
self._logger.exception(
|
||||
"Error while restarting via command {}".format(restart_command)
|
||||
f"Error while restarting via command {restart_command}"
|
||||
)
|
||||
self._logger.warning("Restart stdout:\n{}".format(e.stdout))
|
||||
self._logger.warning("Restart stderr:\n{}".format(e.stderr))
|
||||
self._logger.warning(f"Restart stdout:\n{e.stdout}")
|
||||
self._logger.warning(f"Restart stderr:\n{e.stderr}")
|
||||
raise exceptions.RestartFailed()
|
||||
|
||||
def _populated_check(self, target, check):
|
||||
@@ -2059,7 +2056,7 @@ class SoftwareUpdatePlugin(
|
||||
data={"loglines": [{"line": line, "stream": stream} for line in lines]},
|
||||
)
|
||||
for line in lines:
|
||||
self._console_logger.debug("{} {}".format(prefix, line))
|
||||
self._console_logger.debug(f"{prefix} {line}")
|
||||
|
||||
def _send_client_message(self, message_type, data=None):
|
||||
self._plugin_manager.send_plugin_message(
|
||||
|
||||
@@ -62,7 +62,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
try:
|
||||
r.raise_for_status()
|
||||
except requests.exceptions.HTTPError as e:
|
||||
click.echo("Could not get update information from server, got {}".format(e))
|
||||
click.echo(f"Could not get update information from server, got {e}")
|
||||
sys.exit(1)
|
||||
|
||||
data = r.json()
|
||||
@@ -230,7 +230,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
|
||||
try:
|
||||
r.raise_for_status()
|
||||
except requests.exceptions.HTTPError as e:
|
||||
click.echo("Could not get update information from server, got {}".format(e))
|
||||
click.echo(f"Could not get update information from server, got {e}")
|
||||
sys.exit(1)
|
||||
|
||||
data = r.json()
|
||||
|
||||
@@ -29,7 +29,7 @@ class NetworkError(Exception):
|
||||
if self.message is not None:
|
||||
return self.message
|
||||
elif self.cause is not None:
|
||||
return "NetworkError caused by {}".format(self.cause)
|
||||
return f"NetworkError caused by {self.cause}"
|
||||
else:
|
||||
return "NetworkError"
|
||||
|
||||
|
||||
@@ -91,14 +91,12 @@ def _execute(command, **kwargs):
|
||||
if not p.commands[0].process:
|
||||
# the process might have been set to None in case of any exception
|
||||
print(
|
||||
"Error while trying to run command {}".format(joined_command),
|
||||
f"Error while trying to run command {joined_command}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return None, [], []
|
||||
except Exception:
|
||||
print(
|
||||
"Error while trying to run command {}".format(joined_command), file=sys.stderr
|
||||
)
|
||||
print(f"Error while trying to run command {joined_command}", file=sys.stderr)
|
||||
traceback.print_exc(file=sys.stderr)
|
||||
return None, [], []
|
||||
|
||||
@@ -214,7 +212,7 @@ def _rescue_changes(git_executable, folder):
|
||||
)
|
||||
if returncode is None or returncode != 0:
|
||||
raise RuntimeError(
|
||||
'Could not update, "git diff" failed with returncode {}'.format(returncode)
|
||||
f'Could not update, "git diff" failed with returncode {returncode}'
|
||||
)
|
||||
if stdout and "".join(stdout).strip():
|
||||
# we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch
|
||||
@@ -222,9 +220,9 @@ def _rescue_changes(git_executable, folder):
|
||||
import time
|
||||
|
||||
timestamp = time.strftime("%Y%m%d%H%M")
|
||||
patch = os.path.join(folder, "{}-preupdate.patch".format(timestamp))
|
||||
patch = os.path.join(folder, f"{timestamp}-preupdate.patch")
|
||||
|
||||
print(">>> Running: git diff and saving output to {}".format(patch))
|
||||
print(f">>> Running: git diff and saving output to {patch}")
|
||||
returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable)
|
||||
if returncode is None or returncode != 0:
|
||||
raise RuntimeError(
|
||||
@@ -233,9 +231,7 @@ def _rescue_changes(git_executable, folder):
|
||||
)
|
||||
)
|
||||
|
||||
import io
|
||||
|
||||
with io.open(patch, "wt", encoding="utf-8", errors="replace") as f:
|
||||
with open(patch, "wt", encoding="utf-8", errors="replace") as f:
|
||||
for line in stdout:
|
||||
f.write(line)
|
||||
|
||||
@@ -274,11 +270,11 @@ def update_source(git_executable, folder, target, force=False, branch=None):
|
||||
returncode, stdout, stderr = _git(["fetch"], folder, git_executable=git_executable)
|
||||
if returncode is None or returncode != 0:
|
||||
raise RuntimeError(
|
||||
'Could not update, "git fetch" failed with returncode {}'.format(returncode)
|
||||
f'Could not update, "git fetch" failed with returncode {returncode}'
|
||||
)
|
||||
|
||||
if branch is not None and branch.strip() != "":
|
||||
print(">>> Running: git checkout {}".format(branch))
|
||||
print(f">>> Running: git checkout {branch}")
|
||||
returncode, stdout, stderr = _git(
|
||||
["checkout", branch], folder, git_executable=git_executable
|
||||
)
|
||||
@@ -293,7 +289,7 @@ def update_source(git_executable, folder, target, force=False, branch=None):
|
||||
returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable)
|
||||
if returncode is None or returncode != 0:
|
||||
raise RuntimeError(
|
||||
'Could not update, "git pull" failed with returncode {}'.format(returncode)
|
||||
f'Could not update, "git pull" failed with returncode {returncode}'
|
||||
)
|
||||
|
||||
if force:
|
||||
@@ -316,7 +312,7 @@ def install_source(python_executable, folder, user=False, sudo=False):
|
||||
print(">>> Running: python setup.py clean")
|
||||
returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable)
|
||||
if returncode is None or returncode != 0:
|
||||
print('"python setup.py clean" failed with returncode {}'.format(returncode))
|
||||
print(f'"python setup.py clean" failed with returncode {returncode}')
|
||||
print("Continuing anyways")
|
||||
|
||||
print(">>> Running: python setup.py install")
|
||||
@@ -407,7 +403,7 @@ def main():
|
||||
if python_executable.endswith('"'):
|
||||
python_executable = python_executable[:-1]
|
||||
|
||||
print("Python executable: {!r}".format(python_executable))
|
||||
print(f"Python executable: {python_executable!r}")
|
||||
|
||||
folder = args.folder
|
||||
|
||||
|
||||
@@ -680,13 +680,20 @@ $(function () {
|
||||
gettext("Updating, please wait.")
|
||||
);
|
||||
})
|
||||
.fail(function () {
|
||||
.fail(function (response) {
|
||||
self.updateInProgress = false;
|
||||
var message =
|
||||
"<p>" +
|
||||
gettext(
|
||||
"The update could not be started. Is it already active? Please consult octoprint.log for details."
|
||||
) +
|
||||
"</p><pre>" +
|
||||
_.escape(response.responseJSON.error) +
|
||||
"</pre>";
|
||||
|
||||
self._showPopup({
|
||||
title: gettext("Update not started!"),
|
||||
text: gettext(
|
||||
"The update could not be started. Is it already active? Please consult octoprint.log for details."
|
||||
),
|
||||
text: message,
|
||||
type: "error",
|
||||
hide: false,
|
||||
buttons: {
|
||||
|
||||
@@ -98,7 +98,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
|
||||
target_version=target_version, target=target_version
|
||||
)
|
||||
|
||||
logger.debug("Target: %s, executing pip install %s" % (target, install_arg))
|
||||
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"}
|
||||
|
||||
@@ -2,7 +2,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import ast
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
@@ -46,7 +45,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
|
||||
folder = None
|
||||
try:
|
||||
try:
|
||||
_log_message("Download file from {}".format(url))
|
||||
_log_message(f"Download file from {url}")
|
||||
folder = TemporaryDirectory()
|
||||
path = download_file(url, folder.name)
|
||||
except Exception as exc:
|
||||
@@ -55,29 +54,25 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
|
||||
filename = os.path.basename(path)
|
||||
_, ext = os.path.splitext(filename)
|
||||
if ext not in (".py",):
|
||||
raise exceptions.UpdateError(
|
||||
"File is not a python file: {}".format(filename), None
|
||||
)
|
||||
raise exceptions.UpdateError(f"File is not a python file: {filename}", None)
|
||||
|
||||
try:
|
||||
with io.open(path, "rb") as f:
|
||||
with open(path, "rb") as f:
|
||||
ast.parse(f.read(), filename=path)
|
||||
except Exception:
|
||||
logger.exception("Could not parse {} as python file".format(path), None)
|
||||
logger.exception(f"Could not parse {path} as python file", None)
|
||||
raise exceptions.UpdateError(
|
||||
"Could not parse {} as python file.".format(filename), None
|
||||
f"Could not parse {filename} as python file.", None
|
||||
)
|
||||
|
||||
destination = os.path.join(settings().getBaseFolder("plugins"), filename)
|
||||
|
||||
try:
|
||||
_log_message("Copy {} to {}".format(path, destination))
|
||||
_log_message(f"Copy {path} to {destination}")
|
||||
shutil.copy(path, destination)
|
||||
except Exception:
|
||||
logger.exception("Could not copy {} to {}".format(path, destination))
|
||||
raise exceptions.UpdateError(
|
||||
"Could not copy {} to {}".format(path, destination), None
|
||||
)
|
||||
logger.exception(f"Could not copy {path} to {destination}")
|
||||
raise exceptions.UpdateError(f"Could not copy {path} to {destination}", None)
|
||||
|
||||
return "ok"
|
||||
finally:
|
||||
|
||||
@@ -78,9 +78,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
### pre update
|
||||
|
||||
if pre_update_script is not None:
|
||||
logger.debug(
|
||||
"Target: %s, running pre-update script: %s" % (target, pre_update_script)
|
||||
)
|
||||
logger.debug(f"Target: {target}, running pre-update script: {pre_update_script}")
|
||||
try:
|
||||
caller.checked_call(pre_update_script, cwd=folder)
|
||||
except CommandlineError as e:
|
||||
@@ -100,7 +98,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
force="true" if force_exact_version else "false",
|
||||
)
|
||||
|
||||
logger.debug("Target %s, running update script: %s" % (target, update_command))
|
||||
logger.debug(f"Target {target}, running update script: {update_command}")
|
||||
|
||||
caller.checked_call(update_command, cwd=folder)
|
||||
except CommandlineError as e:
|
||||
@@ -116,7 +114,9 @@ def perform_update(target, check, target_version, log_cb=None, online=True):
|
||||
|
||||
if post_update_script is not None:
|
||||
logger.debug(
|
||||
"Target: %s, running post-update script %s..." % (target, post_update_script)
|
||||
"Target: {}, running post-update script {}...".format(
|
||||
target, post_update_script
|
||||
)
|
||||
)
|
||||
try:
|
||||
caller.checked_call(post_update_script, cwd=folder)
|
||||
|
||||
@@ -27,9 +27,7 @@ def execute(command, cwd=None, evaluate_returncode=True, **kwargs):
|
||||
async_=do_async,
|
||||
)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception(
|
||||
"Error while executing command: {}".format(command)
|
||||
)
|
||||
logging.getLogger(__name__).exception(f"Error while executing command: {command}")
|
||||
returncode = p.returncode if p is not None else None
|
||||
stdout = p.stdout.text if p is not None and p.stdout is not None else ""
|
||||
stderr = p.stderr.text if p is not None and p.stderr is not None else ""
|
||||
|
||||
@@ -21,7 +21,7 @@ from . import ( # noqa: F401
|
||||
class GithubRateLimitCheckError(RateLimitCheckError):
|
||||
def __init__(self, remaining, ratelimit, reset):
|
||||
if reset:
|
||||
message = "Github rate limit exceeded, reset at {}".format(reset)
|
||||
message = f"Github rate limit exceeded, reset at {reset}"
|
||||
else:
|
||||
message = "Github rate limit exceeded"
|
||||
super().__init__(message, remaining=remaining, limit=ratelimit, reset=reset)
|
||||
|
||||
@@ -24,7 +24,7 @@ def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
|
||||
auth_value = base64.b64encode(
|
||||
b"{user}:{pw}".format(user=api_user, pw=api_password)
|
||||
)
|
||||
headers["authorization"] = "Basic {}".format(auth_value)
|
||||
headers["authorization"] = f"Basic {auth_value}"
|
||||
|
||||
try:
|
||||
r = requests.get(url, headers=headers, timeout=(3.05, 30))
|
||||
@@ -79,17 +79,13 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs):
|
||||
remote_commit = _get_latest_commit(
|
||||
check["user"], check["repo"], branch, api_user, api_password
|
||||
)
|
||||
remote_name = (
|
||||
"Commit {commit}".format(commit=remote_commit)
|
||||
if remote_commit is not None
|
||||
else "-"
|
||||
)
|
||||
remote_name = f"Commit {remote_commit}" if remote_commit is not None else "-"
|
||||
|
||||
information["remote"] = {"name": remote_name, "value": remote_commit}
|
||||
is_current = (
|
||||
current is not None and current == remote_commit
|
||||
) or remote_commit is None
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
|
||||
logger.debug(f"Target: {target}, local: {current}, remote: {remote_commit}")
|
||||
|
||||
return information, is_current
|
||||
@@ -56,6 +56,6 @@ def get_latest(target, check, online=True, *args, **kwargs):
|
||||
logger = logging.getLogger(
|
||||
"octoprint.plugins.softwareupdate.version_checks.github_commit"
|
||||
)
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, local_name, remote_name))
|
||||
logger.debug(f"Target: {target}, local: {local_name}, remote: {remote_name}")
|
||||
|
||||
return information, is_current
|
||||
@@ -97,8 +97,6 @@ def get_latest(target, check, online=True, *args, **kwargs):
|
||||
logger = logging.getLogger(
|
||||
"octoprint.plugins.softwareupdate.version_checks.git_commit"
|
||||
)
|
||||
logger.debug(
|
||||
"Target: %s, local: %s, remote: %s" % (target, local_commit, remote_commit)
|
||||
)
|
||||
logger.debug(f"Target: {target}, local: {local_commit}, remote: {remote_commit}")
|
||||
|
||||
return information, is_current
|
||||
@@ -83,17 +83,13 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs):
|
||||
remote_commit = _get_latest_commit(
|
||||
check["user"], check["repo"], branch, apikey=apikey
|
||||
)
|
||||
remote_name = (
|
||||
"Commit {commit}".format(commit=remote_commit)
|
||||
if remote_commit is not None
|
||||
else "-"
|
||||
)
|
||||
remote_name = f"Commit {remote_commit}" if remote_commit is not None else "-"
|
||||
|
||||
information["remote"] = {"name": remote_name, "value": remote_commit}
|
||||
is_current = (
|
||||
current is not None and current == remote_commit
|
||||
) or remote_commit is None
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
|
||||
logger.debug(f"Target: {target}, local: {current}, remote: {remote_commit}")
|
||||
|
||||
return information, is_current
|
||||
@@ -198,7 +198,7 @@ def _get_comparable_version_semantic(version_string, force_base=True):
|
||||
version = semantic_version.Version.coerce(version_string, partial=False)
|
||||
|
||||
if force_base:
|
||||
version_string = "{}.{}.{}".format(version.major, version.minor, version.patch)
|
||||
version_string = f"{version.major}.{version.minor}.{version.patch}"
|
||||
version = semantic_version.Version.coerce(version_string, partial=False)
|
||||
|
||||
return version
|
||||
@@ -355,7 +355,7 @@ def get_latest(
|
||||
"release_notes": release_notes,
|
||||
}
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag))
|
||||
logger.debug(f"Target: {target}, local: {current}, remote: {remote_tag}")
|
||||
|
||||
return information, _is_current(
|
||||
information, compare_type, custom=custom_compare, force_base=force_base
|
||||
|
||||
@@ -26,7 +26,7 @@ def get_latest(target, check, online=True, *args, **kwargs):
|
||||
method = check.get("header_method", "head")
|
||||
prefix = check.get("header_prefix", header)
|
||||
if prefix:
|
||||
prefix = "{} ".format(prefix)
|
||||
prefix = f"{prefix} "
|
||||
|
||||
try:
|
||||
with requests.request(method, url) as r:
|
||||
|
||||
@@ -479,7 +479,7 @@ class TrackingPlugin(
|
||||
# Don't print the URL or UUID! That would expose the UUID in forums/tickets
|
||||
# if pasted. It's okay for the user to know their uuid, but it shouldn't be shared.
|
||||
|
||||
headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())}
|
||||
headers = {"User-Agent": f"OctoPrint/{get_octoprint_version_string()}"}
|
||||
try:
|
||||
params = urlencode(kwargs, doseq=True).replace("+", "%20")
|
||||
|
||||
@@ -488,9 +488,7 @@ class TrackingPlugin(
|
||||
else:
|
||||
requests.get(url, params=params, timeout=3.1, headers=headers)
|
||||
|
||||
self._logger.info(
|
||||
"Sent tracking event {}, payload: {!r}".format(event, kwargs)
|
||||
)
|
||||
self._logger.info(f"Sent tracking event {event}, payload: {kwargs!r}")
|
||||
except Exception:
|
||||
if self._logger.isEnabledFor(logging.DEBUG):
|
||||
self._logger.exception(
|
||||
|
||||
@@ -3,7 +3,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
|
||||
|
||||
import collections
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
@@ -303,7 +302,7 @@ class VirtualPrinter:
|
||||
|
||||
@timeout.setter
|
||||
def timeout(self, value):
|
||||
self._logger.debug("Setting read timeout to {}s".format(value))
|
||||
self._logger.debug(f"Setting read timeout to {value}s")
|
||||
self._read_timeout = value
|
||||
|
||||
@property
|
||||
@@ -312,7 +311,7 @@ class VirtualPrinter:
|
||||
|
||||
@write_timeout.setter
|
||||
def write_timeout(self, value):
|
||||
self._logger.debug("Setting write timeout to {}s".format(value))
|
||||
self._logger.debug(f"Setting write timeout to {value}s")
|
||||
self._write_timeout = value
|
||||
|
||||
@property
|
||||
@@ -496,7 +495,7 @@ class VirtualPrinter:
|
||||
|
||||
try:
|
||||
# if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first
|
||||
letter_handler = "_gcode_{}".format(letter)
|
||||
letter_handler = f"_gcode_{letter}"
|
||||
if hasattr(self, letter_handler):
|
||||
code = command_match.group(2)
|
||||
handled = getattr(self, letter_handler)(code, data)
|
||||
@@ -504,7 +503,7 @@ class VirtualPrinter:
|
||||
continue
|
||||
|
||||
# then look for a method _gcode_<command> and execute that if it exists
|
||||
command_handler = "_gcode_{}".format(command)
|
||||
command_handler = f"_gcode_{command}"
|
||||
if hasattr(self, command_handler):
|
||||
handled = getattr(self, command_handler)(data)
|
||||
if handled:
|
||||
@@ -544,7 +543,7 @@ class VirtualPrinter:
|
||||
self.currentExtruder = t
|
||||
self._send("Active Extruder: %d" % self.currentExtruder)
|
||||
else:
|
||||
self._send("echo:T{} Invalid extruder ".format(t))
|
||||
self._send(f"echo:T{t} Invalid extruder ")
|
||||
|
||||
# noinspection PyUnusedLocal
|
||||
def _gcode_F(self, code, data):
|
||||
@@ -691,7 +690,7 @@ class VirtualPrinter:
|
||||
if not self._okBeforeCommandOutput:
|
||||
ok = self._ok()
|
||||
if ok:
|
||||
output = "{} {}".format(self._ok(), output)
|
||||
output = f"{self._ok()} {output}"
|
||||
self._send(output)
|
||||
return True
|
||||
|
||||
@@ -707,7 +706,10 @@ class VirtualPrinter:
|
||||
def _gcode_M117(self, data: str) -> None:
|
||||
# we'll just use this to echo a message, to allow playing around with pause triggers
|
||||
if self._echoOnM117:
|
||||
self._send("echo:%s" % re.search(r"M117\s+(.*)", data).group(1))
|
||||
try:
|
||||
self._send("echo:%s" % re.search(r"M117\s+(.*)", data).group(1))
|
||||
except AttributeError:
|
||||
self._send("echo:")
|
||||
|
||||
def _gcode_M155(self, data: str) -> None:
|
||||
matchS = re.search(r"S([0-9]+)", data)
|
||||
@@ -1236,7 +1238,7 @@ class VirtualPrinter:
|
||||
| Unsets the busy loop.
|
||||
"""
|
||||
for line in usage.split("\n"):
|
||||
self._send("echo: {}".format(line.strip()))
|
||||
self._send(f"echo: {line.strip()}")
|
||||
elif data == "action_pause":
|
||||
self._send("// action:pause")
|
||||
elif data == "action_resume":
|
||||
@@ -1306,9 +1308,7 @@ class VirtualPrinter:
|
||||
|
||||
if sleep_match is not None:
|
||||
interval = int(sleep_match.group(1))
|
||||
self._send(
|
||||
"// sleeping for {interval} seconds".format(interval=interval)
|
||||
)
|
||||
self._send(f"// sleeping for {interval} seconds")
|
||||
self._debug_sleep = interval
|
||||
elif sleep_after_match is not None:
|
||||
command = sleep_after_match.group(1)
|
||||
@@ -1463,7 +1463,7 @@ class VirtualPrinter:
|
||||
["smoothieTemperatureReporting"]
|
||||
):
|
||||
continue
|
||||
temps["T{}".format(i)] = (self.temp[i], self.targetTemp[i])
|
||||
temps[f"T{i}"] = (self.temp[i], self.targetTemp[i])
|
||||
|
||||
if self._settings.get_boolean(["hasBed"]):
|
||||
temps["B"] = (self.bedTemp, self.bedTargetTemp)
|
||||
@@ -1500,7 +1500,7 @@ class VirtualPrinter:
|
||||
if includeOk:
|
||||
ok = self._ok()
|
||||
if ok:
|
||||
output = "{} {}".format(ok, output)
|
||||
output = f"{ok} {output}"
|
||||
self._send(output)
|
||||
|
||||
def _parseHotendCommand(
|
||||
@@ -1742,7 +1742,7 @@ class VirtualPrinter:
|
||||
|
||||
handle = None
|
||||
try:
|
||||
handle = io.open(file, "wt", encoding="utf-8")
|
||||
handle = open(file, "wt", encoding="utf-8")
|
||||
except Exception:
|
||||
self._send("error writing to file")
|
||||
if handle is not None:
|
||||
@@ -1769,7 +1769,7 @@ class VirtualPrinter:
|
||||
def _sdPrintingWorker(self):
|
||||
self._selectedSdFilePos = 0
|
||||
try:
|
||||
with io.open(self._selectedSdFile, "rt", encoding="utf-8") as f:
|
||||
with open(self._selectedSdFile, encoding="utf-8") as f:
|
||||
for line in iter(f.readline, ""):
|
||||
if self._killed or not self._sdPrinting:
|
||||
break
|
||||
@@ -1930,7 +1930,7 @@ class VirtualPrinter:
|
||||
|
||||
def loop():
|
||||
while self._busy:
|
||||
self._send("echo:busy {}".format(self._busy))
|
||||
self._send(f"echo:busy {self._busy}")
|
||||
time.sleep(self._busyInterval)
|
||||
self._sendOk()
|
||||
|
||||
@@ -1944,9 +1944,9 @@ class VirtualPrinter:
|
||||
|
||||
def _showPrompt(self, text, choices):
|
||||
self._hidePrompt()
|
||||
self._send("//action:prompt_begin {}".format(text))
|
||||
self._send(f"//action:prompt_begin {text}")
|
||||
for choice in choices:
|
||||
self._send("//action:prompt_button {}".format(choice))
|
||||
self._send(f"//action:prompt_button {choice}")
|
||||
self._send("//action:prompt_show")
|
||||
|
||||
def _hidePrompt(self):
|
||||
@@ -1970,7 +1970,7 @@ class VirtualPrinter:
|
||||
return 0
|
||||
|
||||
if b"M112" in data and self._supportM112:
|
||||
self._seriallog.info("<<< {}".format(u_data))
|
||||
self._seriallog.info(f"<<< {u_data}")
|
||||
self._kill()
|
||||
return len(data)
|
||||
|
||||
@@ -1978,7 +1978,7 @@ class VirtualPrinter:
|
||||
written = self.incoming.put(
|
||||
data, timeout=self._write_timeout, partial=True
|
||||
)
|
||||
self._seriallog.info("<<< {}".format(u_data))
|
||||
self._seriallog.info(f"<<< {u_data}")
|
||||
return written
|
||||
except queue.Full:
|
||||
self._logger.info(
|
||||
@@ -2113,13 +2113,13 @@ class VirtualEEPROM:
|
||||
def _initialise_eeprom(self):
|
||||
if os.path.exists(self._eeprom_file_path):
|
||||
# file exists, read it
|
||||
with io.open(self._eeprom_file_path, "rt", encoding="utf-8") as eeprom_file:
|
||||
with open(self._eeprom_file_path, encoding="utf-8") as eeprom_file:
|
||||
data = json.load(eeprom_file)
|
||||
return data
|
||||
else:
|
||||
# no eeprom file, make new one with defaults
|
||||
data = self.get_default_settings()
|
||||
with io.open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file:
|
||||
with open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file:
|
||||
eeprom_file.write(to_unicode(json.dumps(data)))
|
||||
return data
|
||||
|
||||
@@ -2230,7 +2230,7 @@ class VirtualEEPROM:
|
||||
|
||||
def save_settings(self):
|
||||
# M500 behind-the-scenes
|
||||
with io.open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file:
|
||||
with open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file:
|
||||
eeprom_file.write(to_unicode(json.dumps(self._eeprom)))
|
||||
|
||||
def read_settings(self):
|
||||
@@ -2238,7 +2238,7 @@ class VirtualEEPROM:
|
||||
if not os.path.exists(self._eeprom_file_path):
|
||||
self.load_defaults()
|
||||
self.save_settings()
|
||||
with io.open(self._eeprom_file_path, "rt") as eeprom_file:
|
||||
with open(self._eeprom_file_path) as eeprom_file:
|
||||
self._eeprom = json.load(eeprom_file)
|
||||
|
||||
def load_defaults(self):
|
||||
|
||||
@@ -145,7 +145,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
|
||||
import copy
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
from os import scandir
|
||||
@@ -475,7 +474,7 @@ class PrinterProfileManager:
|
||||
try:
|
||||
profile = self._load_from_path(path)
|
||||
except InvalidProfileError:
|
||||
self._logger.warning("Profile {} is invalid, skipping".format(identifier))
|
||||
self._logger.warning(f"Profile {identifier} is invalid, skipping")
|
||||
continue
|
||||
|
||||
if profile is None:
|
||||
@@ -503,7 +502,7 @@ class PrinterProfileManager:
|
||||
|
||||
import yaml
|
||||
|
||||
with io.open(path, "rt", encoding="utf-8") as f:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
profile = yaml.safe_load(f)
|
||||
|
||||
if profile is None or not isinstance(profile, dict):
|
||||
@@ -549,7 +548,7 @@ class PrinterProfileManager:
|
||||
self._logger.exception(
|
||||
"Error while trying to save profile %s" % profile["id"]
|
||||
)
|
||||
raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e)))
|
||||
raise SaveError("Cannot save profile {}: {}".format(profile["id"], str(e)))
|
||||
|
||||
def _remove_from_path(self, path):
|
||||
try:
|
||||
|
||||
@@ -14,7 +14,7 @@ import threading
|
||||
import time
|
||||
from collections import namedtuple
|
||||
|
||||
from frozendict import frozendict
|
||||
from immutabledict import immutabledict
|
||||
|
||||
import octoprint.util.json
|
||||
from octoprint import util as util
|
||||
@@ -73,7 +73,7 @@ def _serial_factory(port=None, baudrate=None):
|
||||
)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception(
|
||||
"Error while creating serial via factory {}".format(name)
|
||||
f"Error while creating serial via factory {name}"
|
||||
)
|
||||
return None
|
||||
|
||||
@@ -101,10 +101,10 @@ class Printer(
|
||||
from collections import deque
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._logger_job = logging.getLogger("{}.job".format(__name__))
|
||||
self._logger_job = logging.getLogger(f"{__name__}.job")
|
||||
|
||||
self._dict = (
|
||||
frozendict
|
||||
immutabledict
|
||||
if settings().getBoolean(["devel", "useFrozenDictForPrinterState"])
|
||||
else dict
|
||||
)
|
||||
@@ -157,13 +157,11 @@ class Printer(
|
||||
try:
|
||||
estimator = hook()
|
||||
if estimator is not None:
|
||||
self._logger.info(
|
||||
"Using print time estimator provided by {}".format(name)
|
||||
)
|
||||
self._logger.info(f"Using print time estimator provided by {name}")
|
||||
self._estimator_factory = estimator
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while processing analysis queues from {}".format(name),
|
||||
f"Error while processing analysis queues from {name}",
|
||||
extra={"plugin": name},
|
||||
)
|
||||
|
||||
@@ -245,7 +243,7 @@ class Printer(
|
||||
|
||||
@property
|
||||
def firmware_info(self):
|
||||
return frozendict(self._firmware_info) if self._firmware_info else None
|
||||
return immutabledict(self._firmware_info) if self._firmware_info else None
|
||||
|
||||
# ~~ handling of PrinterCallbacks
|
||||
|
||||
@@ -332,7 +330,7 @@ class Printer(
|
||||
plugin_data[name] = additional
|
||||
except ValueError:
|
||||
self._logger.exception(
|
||||
"Invalid additional data from plugin {}".format(name),
|
||||
f"Invalid additional data from plugin {name}",
|
||||
extra={"plugin": name},
|
||||
)
|
||||
except Exception:
|
||||
@@ -404,8 +402,8 @@ class Printer(
|
||||
|
||||
from octoprint.logging.handlers import CommunicationLogHandler
|
||||
|
||||
CommunicationLogHandler.arm_rollover(u"CONNECTION")
|
||||
CommunicationLogHandler.arm_rollover(u"COMMDEBUG")
|
||||
CommunicationLogHandler.arm_rollover("CONNECTION")
|
||||
CommunicationLogHandler.arm_rollover("COMMDEBUG")
|
||||
|
||||
if not logging.getLogger("CONNECTION").isEnabledFor(logging.DEBUG):
|
||||
# is protocol.log is not enabled, log a line to explain to reduce "connection.log is empty" in tickets...
|
||||
@@ -525,7 +523,7 @@ class Printer(
|
||||
|
||||
transport_class = lookup_transport(selected_transport)
|
||||
if not transport_class:
|
||||
raise ValueError("Invalid transport: {}".format(selected_transport))
|
||||
raise ValueError(f"Invalid transport: {selected_transport}")
|
||||
|
||||
transport = transport_class(**transport_kwargs)
|
||||
self._transport = transport
|
||||
@@ -536,7 +534,7 @@ class Printer(
|
||||
|
||||
protocol_class = lookup_protocol(selected_protocol)
|
||||
if not protocol_class:
|
||||
raise ValueError("Invalid protocol: {}".format(selected_protocol))
|
||||
raise ValueError(f"Invalid protocol: {selected_protocol}")
|
||||
|
||||
protocol = protocol_class(**protocol_kwargs)
|
||||
self._protocol = protocol
|
||||
@@ -623,7 +621,7 @@ class Printer(
|
||||
# this code preserves existing CamelCase
|
||||
event_name = name[0].upper() + name[1:]
|
||||
|
||||
event_start = "GcodeScript{}Running".format(event_name)
|
||||
event_start = f"GcodeScript{event_name}Running"
|
||||
payload = context.get("event", None) if isinstance(context, dict) else None
|
||||
|
||||
eventManager().fire(event_start, payload)
|
||||
@@ -642,7 +640,7 @@ class Printer(
|
||||
if must_be_set:
|
||||
raise
|
||||
|
||||
event_end = "GcodeScript{}Finished".format(event_name)
|
||||
event_end = f"GcodeScript{event_name}Finished"
|
||||
eventManager().fire(event_end, payload)
|
||||
|
||||
def jog(self, axes, relative=True, speed=None, *args, **kwargs):
|
||||
@@ -654,9 +652,7 @@ class Printer(
|
||||
raise ValueError("amount not set")
|
||||
amount = args[0]
|
||||
if not isinstance(amount, (int, float)):
|
||||
raise ValueError(
|
||||
"amount must be a valid number: {amount}".format(amount=amount)
|
||||
)
|
||||
raise ValueError(f"amount must be a valid number: {amount}")
|
||||
|
||||
axes = {}
|
||||
axes[axis] = amount
|
||||
@@ -689,9 +685,7 @@ class Printer(
|
||||
if isinstance(axes, str):
|
||||
axes = [axes]
|
||||
else:
|
||||
raise ValueError(
|
||||
"axes is neither a list nor a string: {axes}".format(axes=axes)
|
||||
)
|
||||
raise ValueError(f"axes is neither a list nor a string: {axes}")
|
||||
|
||||
validated_axes = list(
|
||||
filter(
|
||||
@@ -699,16 +693,14 @@ class Printer(
|
||||
)
|
||||
)
|
||||
if len(axes) != len(validated_axes):
|
||||
raise ValueError("axes contains invalid axes: {axes}".format(axes=axes))
|
||||
raise ValueError(f"axes contains invalid axes: {axes}")
|
||||
|
||||
kwargs = {axes: True for axes in validated_axes}
|
||||
self._protocol.home(**kwargs)
|
||||
|
||||
def extrude(self, amount, speed=None, *args, **kwargs):
|
||||
if not isinstance(amount, (int, float)):
|
||||
raise ValueError(
|
||||
"amount must be a valid number: {amount}".format(amount=amount)
|
||||
)
|
||||
raise ValueError(f"amount must be a valid number: {amount}")
|
||||
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
@@ -731,7 +723,7 @@ class Printer(
|
||||
|
||||
def change_tool(self, tool, *args, **kwargs):
|
||||
if not PrinterInterface.valid_tool_regex.match(tool):
|
||||
raise ValueError('tool must match "tool[0-9]+": {tool}'.format(tool=tool))
|
||||
raise ValueError(f'tool must match "tool[0-9]+": {tool}')
|
||||
|
||||
tool_num = int(tool[len("tool") :])
|
||||
self._protocol.change_tool(
|
||||
@@ -748,9 +740,7 @@ class Printer(
|
||||
)
|
||||
|
||||
if not isinstance(value, (int, float)) or value < 0:
|
||||
raise ValueError(
|
||||
"value must be a valid number >= 0: {value}".format(value=value)
|
||||
)
|
||||
raise ValueError(f"value must be a valid number >= 0: {value}")
|
||||
|
||||
tags = kwargs.get("tags", set()) | {"trigger:printer.set_temperature"}
|
||||
self._protocol.set_temperature(heater, value, wait=False, tags=tags)
|
||||
@@ -770,13 +760,9 @@ class Printer(
|
||||
)
|
||||
|
||||
if len(validated_keys) != len(offsets):
|
||||
raise ValueError(
|
||||
"offsets contains invalid keys: {offsets}".format(offsets=offsets)
|
||||
)
|
||||
raise ValueError(f"offsets contains invalid keys: {offsets}")
|
||||
if len(validated_values) != len(offsets):
|
||||
raise ValueError(
|
||||
"offsets contains invalid values: {offsets}".format(offsets=offsets)
|
||||
)
|
||||
raise ValueError(f"offsets contains invalid values: {offsets}")
|
||||
|
||||
if self._protocol is None:
|
||||
return
|
||||
@@ -793,9 +779,9 @@ class Printer(
|
||||
factor = int(factor * 100)
|
||||
|
||||
if min_val and factor < min_val:
|
||||
raise ValueError("factor must be a value >={}".format(min_val))
|
||||
raise ValueError(f"factor must be a value >={min_val}")
|
||||
elif max_val and factor > max_val:
|
||||
raise ValueError("factor must be a value <={}".format(max_val))
|
||||
raise ValueError(f"factor must be a value <={max_val}")
|
||||
|
||||
return factor
|
||||
|
||||
@@ -963,9 +949,9 @@ class Printer(
|
||||
elif state == ProtocolState.PAUSED:
|
||||
return "Paused"
|
||||
elif state == ProtocolState.DISCONNECTED_WITH_ERROR:
|
||||
return "Error: {}".format(self._protocol.error)
|
||||
return f"Error: {self._protocol.error}"
|
||||
|
||||
return "Unknown state ({})".format(self._protocol.state)
|
||||
return f"Unknown state ({self._protocol.state})"
|
||||
|
||||
def get_state_id(self, state=None, *args, **kwargs):
|
||||
if state is None:
|
||||
@@ -999,11 +985,11 @@ class Printer(
|
||||
return self._protocol.error
|
||||
|
||||
def get_current_data(self, *args, **kwargs):
|
||||
return util.thaw_frozendict(self._state_monitor.get_current_data())
|
||||
return util.thaw_immutabledict(self._state_monitor.get_current_data())
|
||||
|
||||
def get_current_job(self):
|
||||
data = self._state_monitor.get_current_data()
|
||||
return util.thaw_frozendict(data["job"])
|
||||
return util.thaw_immutabledict(data["job"])
|
||||
|
||||
def get_current_temperatures(self, *args, **kwargs):
|
||||
if self._protocol is not None:
|
||||
@@ -1194,7 +1180,7 @@ class Printer(
|
||||
sd_upload_succeeded,
|
||||
sd_upload_failed,
|
||||
*args,
|
||||
**kwargs
|
||||
**kwargs,
|
||||
)
|
||||
if result is not None:
|
||||
return result
|
||||
@@ -1577,7 +1563,7 @@ class Printer(
|
||||
callback.on_printer_send_initial_data(data)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
u"Error while pushing initial state update to callback {}".format(
|
||||
"Error while pushing initial state update to callback {}".format(
|
||||
callback
|
||||
),
|
||||
extra={"callback": fqcn(callback)},
|
||||
@@ -1636,9 +1622,7 @@ class Printer(
|
||||
if protocol != self._protocol:
|
||||
return
|
||||
|
||||
self._logger.info(
|
||||
"Protocol state changed from {} to {}".format(old_state, new_state)
|
||||
)
|
||||
self._logger.info(f"Protocol state changed from {old_state} to {new_state}")
|
||||
|
||||
# forward relevant state changes to file manager
|
||||
if old_state == ProtocolState.PROCESSING:
|
||||
|
||||
@@ -4,7 +4,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import atexit
|
||||
import base64
|
||||
import io
|
||||
import logging
|
||||
import logging.config
|
||||
import mimetypes
|
||||
@@ -37,6 +36,7 @@ from flask_login import ( # noqa: F401
|
||||
)
|
||||
from watchdog.observers import Observer
|
||||
from watchdog.observers.polling import PollingObserver
|
||||
from werkzeug.exceptions import HTTPException
|
||||
|
||||
import octoprint.util
|
||||
import octoprint.util.net
|
||||
@@ -60,8 +60,8 @@ except ImportError:
|
||||
fcntl = None
|
||||
|
||||
SUCCESS = {}
|
||||
NO_CONTENT = ("", 204)
|
||||
NOT_MODIFIED = ("Not Modified", 304)
|
||||
NO_CONTENT = ("", 204, {"Content-Type": "text/plain"})
|
||||
NOT_MODIFIED = ("Not Modified", 304, {"Content-Type": "text/plain"})
|
||||
|
||||
app = Flask("octoprint")
|
||||
|
||||
@@ -396,7 +396,7 @@ class Server:
|
||||
analysis_queue_factories.update(**additional_factories)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while processing analysis queues from {}".format(name),
|
||||
f"Error while processing analysis queues from {name}",
|
||||
extra={"plugin": name},
|
||||
)
|
||||
analysisQueue = octoprint.filemanager.analysis.AnalysisQueue(
|
||||
@@ -495,7 +495,7 @@ class Server:
|
||||
groupManager = factory(components, self._settings)
|
||||
if groupManager is not None:
|
||||
self._logger.debug(
|
||||
"Created group manager instance from factory {}".format(name)
|
||||
f"Created group manager instance from factory {name}"
|
||||
)
|
||||
break
|
||||
except Exception:
|
||||
@@ -529,7 +529,7 @@ class Server:
|
||||
userManager = factory(components, self._settings)
|
||||
if userManager is not None:
|
||||
self._logger.debug(
|
||||
"Created user manager instance from factory {}".format(name)
|
||||
f"Created user manager instance from factory {name}"
|
||||
)
|
||||
break
|
||||
except Exception:
|
||||
@@ -560,13 +560,11 @@ class Server:
|
||||
try:
|
||||
printer = factory(components)
|
||||
if printer is not None:
|
||||
self._logger.debug(
|
||||
"Created printer instance from factory {}".format(name)
|
||||
)
|
||||
self._logger.debug(f"Created printer instance from factory {name}")
|
||||
break
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while creating printer instance from factory {}".format(name),
|
||||
f"Error while creating printer instance from factory {name}",
|
||||
extra={"plugin": name},
|
||||
)
|
||||
else:
|
||||
@@ -759,23 +757,38 @@ class Server:
|
||||
lambda path: not octoprint.util.is_hidden_path(path), status_code=404
|
||||
)
|
||||
}
|
||||
|
||||
valid_timelapse = lambda path: not octoprint.util.is_hidden_path(
|
||||
path
|
||||
) and octoprint.timelapse.valid_timelapse(path)
|
||||
timelapse_path_validator = {
|
||||
"path_validation": util.tornado.path_validation_factory(
|
||||
lambda path: not octoprint.util.is_hidden_path(path)
|
||||
and octoprint.timelapse.valid_timelapse(path),
|
||||
valid_timelapse,
|
||||
status_code=404,
|
||||
)
|
||||
}
|
||||
timelapses_path_validator = {
|
||||
"path_validation": util.tornado.path_validation_factory(
|
||||
lambda path: not octoprint.util.is_hidden_path(path)
|
||||
and octoprint.timelapse.valid_timelapse(path),
|
||||
lambda path: valid_timelapse(path)
|
||||
and os.path.realpath(os.path.abspath(path)).startswith(
|
||||
settings().getBaseFolder("timelapse")
|
||||
),
|
||||
status_code=400,
|
||||
)
|
||||
}
|
||||
|
||||
valid_log = lambda path: not octoprint.util.is_hidden_path(
|
||||
path
|
||||
) and path.endswith(".log")
|
||||
log_path_validator = {
|
||||
"path_validation": util.tornado.path_validation_factory(
|
||||
valid_log,
|
||||
status_code=404,
|
||||
)
|
||||
}
|
||||
logs_path_validator = {
|
||||
"path_validation": util.tornado.path_validation_factory(
|
||||
lambda path: not octoprint.util.is_hidden_path(path)
|
||||
lambda path: valid_log(path)
|
||||
and os.path.realpath(os.path.abspath(path)).startswith(
|
||||
settings().getBaseFolder("logs")
|
||||
),
|
||||
@@ -853,6 +866,7 @@ class Server:
|
||||
},
|
||||
download_handler_kwargs,
|
||||
log_permission_validator,
|
||||
log_path_validator,
|
||||
),
|
||||
),
|
||||
# zipped log file bundles
|
||||
@@ -1150,9 +1164,7 @@ class Server:
|
||||
if self._host == "::":
|
||||
if self._v6_only:
|
||||
# only v6
|
||||
self._logger.info(
|
||||
"Listening on http://[::]:{port}".format(port=self._port)
|
||||
)
|
||||
self._logger.info(f"Listening on http://[::]:{self._port}")
|
||||
else:
|
||||
# all v4 and v6
|
||||
self._logger.info(
|
||||
@@ -1337,7 +1349,7 @@ class Server:
|
||||
logger.info("Server heartbeat <3")
|
||||
|
||||
interval = settings().getFloat(["server", "heartbeat"])
|
||||
logger.info("Starting server heartbeat, {}s interval".format(interval))
|
||||
logger.info(f"Starting server heartbeat, {interval}s interval")
|
||||
|
||||
timer = octoprint.util.RepeatedTimer(interval, log_heartbeat)
|
||||
timer.start()
|
||||
@@ -1437,7 +1449,7 @@ class Server:
|
||||
result.add(locale.language)
|
||||
if locale.territory:
|
||||
# if a territory is specified, add that too
|
||||
result.add("%s_%s" % (locale.language, locale.territory))
|
||||
result.add(f"{locale.language}_{locale.territory}")
|
||||
|
||||
return result
|
||||
|
||||
@@ -1505,7 +1517,7 @@ class Server:
|
||||
tag += ' target="_blank" rel="noreferrer noopener"'
|
||||
|
||||
content = match.group("content")
|
||||
return "<{tag}>{content}</a>".format(tag=tag, content=content)
|
||||
return f"<{tag}>{content}</a>"
|
||||
|
||||
return html_link_regex.sub(repl, text)
|
||||
|
||||
@@ -1740,12 +1752,19 @@ class Server:
|
||||
# do not remove or the index view won't be found
|
||||
import octoprint.server.views # noqa: F401
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import make_api_error
|
||||
|
||||
blueprints = OrderedDict()
|
||||
blueprints["/api"] = api
|
||||
json_errors = ["/api"]
|
||||
|
||||
# also register any blueprints defined in BlueprintPlugins
|
||||
blueprints.update(self._prepare_blueprint_plugins())
|
||||
(
|
||||
blueprint_from_plugins,
|
||||
api_prefixes_from_plugins,
|
||||
) = self._prepare_blueprint_plugins()
|
||||
blueprints.update(blueprint_from_plugins)
|
||||
json_errors += api_prefixes_from_plugins
|
||||
|
||||
# and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves
|
||||
blueprints.update(self._prepare_asset_plugins())
|
||||
@@ -1757,8 +1776,16 @@ class Server:
|
||||
for url_prefix, blueprint in blueprints.items():
|
||||
app.register_blueprint(blueprint, url_prefix=url_prefix)
|
||||
|
||||
@app.errorhandler(HTTPException)
|
||||
def _handle_api_error(ex):
|
||||
if any(map(lambda x: request.path.startswith(x), json_errors)):
|
||||
return make_api_error(ex.description, ex.code)
|
||||
else:
|
||||
return ex
|
||||
|
||||
def _prepare_blueprint_plugins(self):
|
||||
blueprints = OrderedDict()
|
||||
api_prefixes = []
|
||||
|
||||
blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(
|
||||
octoprint.plugin.BlueprintPlugin
|
||||
@@ -1766,6 +1793,9 @@ class Server:
|
||||
for plugin in blueprint_plugins:
|
||||
try:
|
||||
blueprint, prefix = self._prepare_blueprint_plugin(plugin)
|
||||
api_prefixes += map(
|
||||
lambda x: prefix + x, plugin.get_blueprint_api_prefixes()
|
||||
)
|
||||
blueprints[prefix] = blueprint
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
@@ -1775,7 +1805,7 @@ class Server:
|
||||
)
|
||||
continue
|
||||
|
||||
return blueprints
|
||||
return blueprints, api_prefixes
|
||||
|
||||
def _prepare_asset_plugins(self):
|
||||
blueprints = OrderedDict()
|
||||
@@ -1812,7 +1842,7 @@ class Server:
|
||||
if plugin.is_blueprint_protected():
|
||||
blueprint.before_request(requireLoginRequestHandler)
|
||||
|
||||
url_prefix = "/plugin/{name}".format(name=name)
|
||||
url_prefix = f"/plugin/{name}"
|
||||
app.register_blueprint(blueprint, url_prefix=url_prefix)
|
||||
|
||||
if self._logger:
|
||||
@@ -1827,7 +1857,7 @@ class Server:
|
||||
def _prepare_asset_plugin(self, plugin):
|
||||
name = plugin._identifier
|
||||
|
||||
url_prefix = "/plugin/{name}".format(name=name)
|
||||
url_prefix = f"/plugin/{name}"
|
||||
blueprint = Blueprint(
|
||||
"plugin." + name, name, static_folder=plugin.get_asset_folder()
|
||||
)
|
||||
@@ -1887,7 +1917,7 @@ class Server:
|
||||
|
||||
cli_key_file = os.path.join(self._settings.getBaseFolder("generated"), "cli.key")
|
||||
cli_key = generate_api_key()
|
||||
with io.open(cli_key_file, "w", encoding="utf8") as f:
|
||||
with open(cli_key_file, "w", encoding="utf8") as f:
|
||||
f.write(cli_key)
|
||||
|
||||
return cli_key
|
||||
@@ -2172,7 +2202,7 @@ class Server:
|
||||
js_plugins_bundle = Bundle(
|
||||
*js_plugins.values(),
|
||||
output="webassets/packed_plugins.js",
|
||||
filters=",".join(js_plugin_filters)
|
||||
filters=",".join(js_plugin_filters),
|
||||
)
|
||||
|
||||
js_app_bundle = Bundle(
|
||||
@@ -2185,7 +2215,7 @@ class Server:
|
||||
js_client_core_bundle = Bundle(
|
||||
*clientjs_core,
|
||||
output="webassets/packed_client_core.js",
|
||||
filters=",".join(js_filters)
|
||||
filters=",".join(js_filters),
|
||||
)
|
||||
|
||||
if len(clientjs_plugins) == 0:
|
||||
@@ -2194,7 +2224,7 @@ class Server:
|
||||
js_client_plugins_bundle = Bundle(
|
||||
*clientjs_plugins.values(),
|
||||
output="webassets/packed_client_plugins.js",
|
||||
filters=",".join(js_plugin_filters)
|
||||
filters=",".join(js_plugin_filters),
|
||||
)
|
||||
|
||||
js_client_bundle = Bundle(
|
||||
@@ -2225,7 +2255,7 @@ class Server:
|
||||
css_core_bundle = Bundle(
|
||||
*css_core,
|
||||
output="webassets/packed_core.css",
|
||||
filters=",".join(css_filters)
|
||||
filters=",".join(css_filters),
|
||||
)
|
||||
|
||||
if len(css_plugins) == 0:
|
||||
@@ -2234,7 +2264,7 @@ class Server:
|
||||
css_plugins_bundle = Bundle(
|
||||
*css_plugins,
|
||||
output="webassets/packed_plugins.css",
|
||||
filters=",".join(css_filters)
|
||||
filters=",".join(css_filters),
|
||||
)
|
||||
|
||||
css_app_bundle = Bundle(
|
||||
@@ -2259,7 +2289,7 @@ class Server:
|
||||
less_core_bundle = Bundle(
|
||||
*less_core,
|
||||
output="webassets/packed_core.less",
|
||||
filters=",".join(less_filters)
|
||||
filters=",".join(less_filters),
|
||||
)
|
||||
|
||||
if len(less_plugins) == 0:
|
||||
@@ -2268,7 +2298,7 @@ class Server:
|
||||
less_plugins_bundle = Bundle(
|
||||
*less_plugins,
|
||||
output="webassets/packed_plugins.less",
|
||||
filters=",".join(less_filters)
|
||||
filters=",".join(less_filters),
|
||||
)
|
||||
|
||||
less_app_bundle = Bundle(
|
||||
@@ -2284,13 +2314,13 @@ class Server:
|
||||
assets.register("js_client_core", js_client_core_bundle)
|
||||
for plugin, bundle in clientjs_plugins.items():
|
||||
# register our collected clientjs plugin bundles so that they are bound to the environment
|
||||
assets.register("js_client_plugin_{}".format(plugin), bundle)
|
||||
assets.register(f"js_client_plugin_{plugin}", bundle)
|
||||
assets.register("js_client_plugins", js_client_plugins_bundle)
|
||||
assets.register("js_client", js_client_bundle)
|
||||
assets.register("js_core", js_core_bundle)
|
||||
for plugin, bundle in js_plugins.items():
|
||||
# register our collected plugin bundles so that they are bound to the environment
|
||||
assets.register("js_plugin_{}".format(plugin), bundle)
|
||||
assets.register(f"js_plugin_{plugin}", bundle)
|
||||
assets.register("js_plugins", js_plugins_bundle)
|
||||
assets.register("js_app", js_app_bundle)
|
||||
assets.register("css_libs", css_libs_bundle)
|
||||
@@ -2381,7 +2411,7 @@ class Server:
|
||||
if not os.path.isfile(path):
|
||||
return ""
|
||||
|
||||
with io.open(path, "rb") as f:
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
return data
|
||||
|
||||
@@ -2436,9 +2466,7 @@ class Server:
|
||||
|
||||
if host == "::":
|
||||
if self._v6_only:
|
||||
self._logger.debug(
|
||||
"Starting intermediary server on http://[::]:{port}".format(port=port)
|
||||
)
|
||||
self._logger.debug(f"Starting intermediary server on http://[::]:{port}")
|
||||
else:
|
||||
self._logger.debug(
|
||||
"Starting intermediary server on http://0.0.0.0:{port} and http://[::]:{port}".format(
|
||||
@@ -2526,7 +2554,7 @@ class Server:
|
||||
return "{}: {}".format(plugin, definition["name"])
|
||||
|
||||
def permission_role(plugin, role):
|
||||
return "plugin_{}_{}".format(plugin, role)
|
||||
return f"plugin_{plugin}_{role}"
|
||||
|
||||
def process_regular_permission(plugin_info, definition):
|
||||
permissions = []
|
||||
@@ -2556,7 +2584,7 @@ class Server:
|
||||
plugin=plugin_info.key,
|
||||
dangerous=dangerous,
|
||||
default_groups=default_groups,
|
||||
*roles_and_permissions
|
||||
*roles_and_permissions,
|
||||
)
|
||||
setattr(
|
||||
octoprint.access.permissions.Permissions,
|
||||
@@ -2567,7 +2595,7 @@ class Server:
|
||||
plugin=plugin_info.key,
|
||||
dangerous=dangerous,
|
||||
default_groups=default_groups,
|
||||
*roles_and_permissions
|
||||
*roles_and_permissions,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -2615,7 +2643,7 @@ class Server:
|
||||
postponed.append((plugin_info, p))
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while creating permission instance/s from {}".format(name)
|
||||
f"Error while creating permission instance/s from {name}"
|
||||
)
|
||||
|
||||
# final resolution passes
|
||||
|
||||
@@ -2,11 +2,11 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import logging
|
||||
|
||||
from flask import (
|
||||
Blueprint,
|
||||
Response,
|
||||
abort,
|
||||
current_app,
|
||||
g,
|
||||
@@ -78,31 +78,47 @@ def pluginData(name):
|
||||
lambda p: p._identifier == name, octoprint.plugin.SimpleApiPlugin
|
||||
)
|
||||
if not api_plugins:
|
||||
return make_response("Not found", 404)
|
||||
abort(404)
|
||||
|
||||
if len(api_plugins) > 1:
|
||||
return make_response(
|
||||
"More than one api provider registered for {name}, can't proceed".format(
|
||||
name=name
|
||||
),
|
||||
500,
|
||||
)
|
||||
abort(500, description="More than one api provider registered, can't proceed")
|
||||
|
||||
try:
|
||||
api_plugin = api_plugins[0]
|
||||
if api_plugin.is_api_adminonly() and not current_user.is_admin:
|
||||
return make_response("Forbidden", 403)
|
||||
abort(403)
|
||||
|
||||
response = api_plugin.on_api_get(request)
|
||||
|
||||
if response is not None:
|
||||
message = (
|
||||
"Rewriting response from {} to use abort(msg, code) - please "
|
||||
"consider upgrading the implementation accordingly".format(name)
|
||||
)
|
||||
if (
|
||||
isinstance(response, Response)
|
||||
and response.mimetype == "text/html"
|
||||
and response.status_code >= 300
|
||||
):
|
||||
# this actually looks like an error response
|
||||
logging.getLogger(__name__).info(message)
|
||||
abort(response.status_code, description=response.data)
|
||||
elif (
|
||||
isinstance(response, tuple)
|
||||
and len(response) == 2
|
||||
and isinstance(response[0], (str, bytes))
|
||||
and response[1] >= 300
|
||||
):
|
||||
# this actually looks like an error response
|
||||
logging.getLogger(__name__).info(message)
|
||||
abort(response[1], response[0])
|
||||
return response
|
||||
return NO_CONTENT
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception(
|
||||
"Error calling SimpleApiPlugin {}".format(name), extra={"plugin": name}
|
||||
f"Error calling SimpleApiPlugin {name}", extra={"plugin": name}
|
||||
)
|
||||
return abort(500)
|
||||
|
||||
@@ -118,24 +134,19 @@ def pluginCommand(name):
|
||||
)
|
||||
|
||||
if not api_plugins:
|
||||
return make_response("Not found", 404)
|
||||
abort(400)
|
||||
|
||||
if len(api_plugins) > 1:
|
||||
return make_response(
|
||||
"More than one api provider registered for {name}, can't proceed".format(
|
||||
name=name
|
||||
),
|
||||
500,
|
||||
)
|
||||
abort(500, description="More than one api provider registered, can't proceed")
|
||||
|
||||
api_plugin = api_plugins[0]
|
||||
try:
|
||||
valid_commands = api_plugin.get_api_commands()
|
||||
if valid_commands is None:
|
||||
return make_response("Method not allowed", 405)
|
||||
abort(405)
|
||||
|
||||
if api_plugin.is_api_adminonly() and not Permissions.ADMIN.can():
|
||||
return make_response("Forbidden", 403)
|
||||
abort(403)
|
||||
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
@@ -149,7 +160,7 @@ def pluginCommand(name):
|
||||
raise
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception(
|
||||
"Error while executing SimpleApiPlugin {}".format(name),
|
||||
f"Error while executing SimpleApiPlugin {name}",
|
||||
extra={"plugin": name},
|
||||
)
|
||||
return abort(500)
|
||||
@@ -251,21 +262,13 @@ def wizardFinish():
|
||||
# ~~ system state
|
||||
|
||||
|
||||
@api.route("/state", methods=["GET"])
|
||||
@no_firstrun_access
|
||||
def apiPrinterState():
|
||||
return make_response(
|
||||
("/api/state has been deprecated, use /api/printer instead", 405, [])
|
||||
)
|
||||
|
||||
|
||||
@api.route("/version", methods=["GET"])
|
||||
@Permissions.STATUS.require(403)
|
||||
def apiVersion():
|
||||
return jsonify(
|
||||
server=octoprint.server.VERSION,
|
||||
api=VERSION,
|
||||
text="OctoPrint {}".format(octoprint.server.DISPLAY_VERSION),
|
||||
text=f"OctoPrint {octoprint.server.DISPLAY_VERSION}",
|
||||
)
|
||||
|
||||
|
||||
@@ -300,7 +303,7 @@ def login():
|
||||
if user is not None:
|
||||
if octoprint.server.userManager.check_password(username, password):
|
||||
if not user.is_active:
|
||||
return make_response(("Your account is deactivated", 403, []))
|
||||
abort(403)
|
||||
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
session["usersession.id"] = user.session
|
||||
@@ -337,12 +340,12 @@ def login():
|
||||
|
||||
return r
|
||||
|
||||
return make_response(("User unknown or password incorrect", 403, []))
|
||||
abort(403)
|
||||
|
||||
elif "passive" in data:
|
||||
return passive_login()
|
||||
|
||||
return make_response("Neither user and pass attributes nor passive flag present", 400)
|
||||
abort(400, description="Neither user and pass attributes nor passive flag present")
|
||||
|
||||
|
||||
@api.route("/logout", methods=["POST"])
|
||||
@@ -478,7 +481,7 @@ def _test_path(data):
|
||||
os.makedirs(path)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception(
|
||||
"Error while trying to create {}".format(path)
|
||||
f"Error while trying to create {path}"
|
||||
)
|
||||
return jsonify(
|
||||
path=path,
|
||||
@@ -511,12 +514,12 @@ def _test_path(data):
|
||||
if check_writable_dir and check_type == "dir":
|
||||
try:
|
||||
test_path = os.path.join(path, ".testballoon.txt")
|
||||
with io.open(test_path, "wb") as f:
|
||||
with open(test_path, "wb") as f:
|
||||
f.write(b"Test")
|
||||
os.remove(test_path)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception(
|
||||
"Error while testing if {} is really writable".format(path)
|
||||
f"Error while testing if {path} is really writable"
|
||||
)
|
||||
return jsonify(
|
||||
path=path,
|
||||
@@ -586,12 +589,7 @@ def _test_url(data):
|
||||
try:
|
||||
timeout = float(data["timeout"])
|
||||
except Exception:
|
||||
return make_response(
|
||||
"{!r} is not a valid value for timeout (must be int or float)".format(
|
||||
data["timeout"]
|
||||
),
|
||||
400,
|
||||
)
|
||||
abort(400, description="timeout is invalid")
|
||||
|
||||
if "validSsl" in data:
|
||||
valid_ssl = data["validSsl"] in valid_boolean_trues
|
||||
@@ -615,13 +613,13 @@ def _test_url(data):
|
||||
|
||||
if "content_type_whitelist" in data:
|
||||
if not isinstance(data["content_type_whitelist"], (list, tuple)):
|
||||
return make_response("content_type_whitelist must be a list of mime types")
|
||||
abort(400, description="content_type_whitelist must be a list of mime types")
|
||||
content_type_whitelist = list(
|
||||
map(util.parse_mime_type, data["content_type_whitelist"])
|
||||
)
|
||||
if "content_type_blacklist" in data:
|
||||
if not isinstance(data["content_type_whitelist"], (list, tuple)):
|
||||
return make_response("content_type_blacklist must be a list of mime types")
|
||||
abort(400, description="content_type_blacklist must be a list of mime types")
|
||||
content_type_blacklist = list(
|
||||
map(util.parse_mime_type, data["content_type_blacklist"])
|
||||
)
|
||||
@@ -686,7 +684,7 @@ def _test_url(data):
|
||||
response_result["content"] = content
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception(
|
||||
"Error while running a test {} request on {}".format(method, url)
|
||||
f"Error while running a test {method} request on {url}"
|
||||
)
|
||||
outcome = False
|
||||
|
||||
@@ -702,28 +700,18 @@ def _test_server(data):
|
||||
try:
|
||||
port = int(data["port"])
|
||||
except Exception:
|
||||
return make_response(
|
||||
"{!r} is not a valid value for port (must be int)".format(data["port"]), 400
|
||||
)
|
||||
abort(400, description="Invalid value for port")
|
||||
|
||||
timeout = 3.05
|
||||
if "timeout" in data:
|
||||
try:
|
||||
timeout = float(data["timeout"])
|
||||
except Exception:
|
||||
return make_response(
|
||||
"{!r} is not a valid value for timeout (must be int or float)".format(
|
||||
data["timeout"]
|
||||
),
|
||||
400,
|
||||
)
|
||||
abort(400, description="Invalid value for timeout")
|
||||
|
||||
protocol = data.get("protocol", "tcp")
|
||||
if protocol not in ("tcp", "udp"):
|
||||
return make_response(
|
||||
"{!r} is not a valid value for protocol, must be tcp or udp".format(protocol),
|
||||
400,
|
||||
)
|
||||
abort(400, description="Invalid value for protocol")
|
||||
|
||||
from octoprint.util import server_reachable
|
||||
|
||||
|
||||
@@ -2,9 +2,8 @@ __author__ = "Marc Hannappel <salandora@gmail.com>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import abort, jsonify, make_response, request
|
||||
from flask import abort, jsonify, request
|
||||
from flask_login import current_user
|
||||
from werkzeug.exceptions import BadRequest
|
||||
|
||||
import octoprint.access.groups as groups
|
||||
import octoprint.access.users as users
|
||||
@@ -36,19 +35,16 @@ def get_groups():
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def add_group():
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
abort(400, description="Expected content-type JSON")
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
data = request.get_json()
|
||||
|
||||
if "key" not in data:
|
||||
return make_response("Missing mandatory key field", 400)
|
||||
abort(400, description="key is missing")
|
||||
if "name" not in data:
|
||||
return make_response("Missing mandatory name field", 400)
|
||||
abort(400, description="name is missing")
|
||||
if "permissions" not in data:
|
||||
return make_response("Missing mandatory permissions field", 400)
|
||||
abort(400, description="permissions are missing")
|
||||
|
||||
key = data["key"]
|
||||
name = data["name"]
|
||||
@@ -87,12 +83,9 @@ def get_group(key):
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def update_group(key):
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
abort(400, description="Expected content-type JSON")
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
data = request.get_json()
|
||||
|
||||
try:
|
||||
kwargs = {}
|
||||
@@ -146,22 +139,18 @@ def get_users():
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def add_user():
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
abort(400, description="Expected content-type JSON")
|
||||
|
||||
data = request.get_json()
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
abort(400, description="Malformed JSON body in request")
|
||||
|
||||
if "name" not in data:
|
||||
return make_response("Missing mandatory name field", 400)
|
||||
abort(400, description="name is missing")
|
||||
if "password" not in data:
|
||||
return make_response("Missing mandatory password field", 400)
|
||||
abort(400, description="password is missing")
|
||||
if "active" not in data:
|
||||
return make_response("Missing mandatory active field", 400)
|
||||
abort(400, description="active is missing")
|
||||
|
||||
name = data["name"]
|
||||
password = data["password"]
|
||||
@@ -204,12 +193,12 @@ def update_user(username):
|
||||
user = userManager.find_user(username)
|
||||
if user is not None:
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
abort(400, description="Expected content-type JSON")
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
data = request.get_json()
|
||||
|
||||
if data is None:
|
||||
abort(400, description="Malformed JSON body in request")
|
||||
|
||||
# change groups
|
||||
if "groups" in data:
|
||||
@@ -221,9 +210,6 @@ def update_user(username):
|
||||
permissions = data["permissions"]
|
||||
userManager.change_user_permissions(username, permissions)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
# change activation
|
||||
if "active" in data:
|
||||
userManager.change_user_activation(
|
||||
@@ -258,27 +244,24 @@ def change_password_for_user(username):
|
||||
and (current_user.get_name() == username or current_user.is_admin)
|
||||
):
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
abort(400, description="Expected content-type JSON")
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
data = request.get_json()
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
abort(400, description="Malformed JSON body in request")
|
||||
|
||||
if "password" not in data or not data["password"]:
|
||||
return make_response("password is missing from request", 400)
|
||||
abort(400, description="password is missing")
|
||||
|
||||
try:
|
||||
userManager.change_user_password(username, data["password"])
|
||||
except users.UnknownUser:
|
||||
return make_response(("Unknown user: %s" % username, 404, []))
|
||||
abort(404)
|
||||
|
||||
return jsonify(SUCCESS)
|
||||
else:
|
||||
return make_response(("Forbidden", 403, []))
|
||||
abort(403)
|
||||
|
||||
|
||||
@api.route("/access/users/<username>/settings", methods=["GET"])
|
||||
@@ -292,12 +275,12 @@ def get_settings_for_user(username):
|
||||
and not current_user.has_permission(Permissions.ADMIN)
|
||||
)
|
||||
):
|
||||
return make_response("Forbidden", 403)
|
||||
abort(403)
|
||||
|
||||
try:
|
||||
return jsonify(userManager.get_all_user_settings(username))
|
||||
except users.UnknownUser:
|
||||
return make_response("Unknown user: %s" % username, 404)
|
||||
abort(404)
|
||||
|
||||
|
||||
@api.route("/access/users/<username>/settings", methods=["PATCH"])
|
||||
@@ -311,21 +294,18 @@ def change_settings_for_user(username):
|
||||
and not current_user.has_permission(Permissions.ADMIN)
|
||||
)
|
||||
):
|
||||
return make_response("Forbidden", 403)
|
||||
abort(403)
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
data = request.get_json()
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
abort(400, description="Malformed JSON body in request")
|
||||
|
||||
try:
|
||||
userManager.change_user_settings(username, data)
|
||||
return jsonify(SUCCESS)
|
||||
except users.UnknownUser:
|
||||
return make_response("Unknown user: %s" % username, 404)
|
||||
abort(404)
|
||||
|
||||
|
||||
@api.route("/access/users/<username>/apikey", methods=["DELETE"])
|
||||
@@ -342,10 +322,10 @@ def delete_apikey_for_user(username):
|
||||
try:
|
||||
userManager.delete_api_key(username)
|
||||
except users.UnknownUser:
|
||||
return make_response(("Unknown user: %s" % username, 404, []))
|
||||
abort(404)
|
||||
return jsonify(SUCCESS)
|
||||
else:
|
||||
return make_response(("Forbidden", 403, []))
|
||||
abort(403)
|
||||
|
||||
|
||||
@api.route("/access/users/<username>/apikey", methods=["POST"])
|
||||
@@ -365,10 +345,10 @@ def generate_apikey_for_user(username):
|
||||
try:
|
||||
apikey = userManager.generate_api_key(username)
|
||||
except users.UnknownUser:
|
||||
return make_response(("Unknown user: %s" % username, 404, []))
|
||||
abort(404)
|
||||
return jsonify({"apikey": apikey})
|
||||
else:
|
||||
return make_response(("Forbidden", 403, []))
|
||||
abort(403)
|
||||
|
||||
|
||||
def _to_external_permissions(*permissions):
|
||||
|
||||
@@ -2,7 +2,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import jsonify, make_response, request
|
||||
from flask import abort, jsonify, request
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.comm.protocol import all_protocols
|
||||
@@ -74,7 +74,7 @@ def connectionCommand():
|
||||
if "printerProfile" in data:
|
||||
printerProfile = data["printerProfile"]
|
||||
if not printerProfileManager.exists(printerProfile):
|
||||
return make_response("Invalid printer profile: %s" % printerProfile, 400)
|
||||
abort(400, description="printerProfile is invalid")
|
||||
kwargs["profile"] = printerProfile
|
||||
|
||||
if "save" in data and data["save"]: # TODO
|
||||
|
||||
@@ -8,7 +8,7 @@ import os
|
||||
import threading
|
||||
|
||||
import psutil
|
||||
from flask import jsonify, make_response, request, url_for
|
||||
from flask import abort, jsonify, make_response, request, url_for
|
||||
|
||||
import octoprint.filemanager
|
||||
import octoprint.filemanager.storage
|
||||
@@ -156,7 +156,7 @@ def readGcodeFiles():
|
||||
recursive=recursive,
|
||||
allow_from_cache=not force,
|
||||
)
|
||||
files.extend(_getFileList(FileDestinations.SDCARD))
|
||||
files.extend(_getFileList(FileDestinations.SDCARD, allow_from_cache=not force))
|
||||
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("uploads", check_writable=False))
|
||||
return jsonify(files=files, free=usage.free, total=usage.total)
|
||||
@@ -179,7 +179,7 @@ def readGcodeFiles():
|
||||
)
|
||||
def readGcodeFilesForOrigin(origin):
|
||||
if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown origin: %s" % origin, 404)
|
||||
abort(404)
|
||||
|
||||
filter = request.values.get("filter", False)
|
||||
recursive = request.values.get("recursive", "false") in valid_boolean_trues
|
||||
@@ -215,7 +215,10 @@ def readGcodeFilesForOrigin(origin):
|
||||
)
|
||||
def readGcodeFile(target, filename):
|
||||
if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown target: %s" % target, 404)
|
||||
abort(404)
|
||||
|
||||
if not _validate(target, filename):
|
||||
abort(404)
|
||||
|
||||
recursive = False
|
||||
if "recursive" in request.values:
|
||||
@@ -223,7 +226,7 @@ def readGcodeFile(target, filename):
|
||||
|
||||
file = _getFileDetails(target, filename, recursive=recursive)
|
||||
if not file:
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
abort(404)
|
||||
|
||||
return jsonify(file)
|
||||
|
||||
@@ -243,12 +246,14 @@ def _getFileDetails(origin, path, recursive=True):
|
||||
logtarget=__name__ + ".timings",
|
||||
message="{func}({func_args},{func_kwargs}) took {timing:.2f}ms",
|
||||
incl_func_args=True,
|
||||
log_enter=True,
|
||||
message_enter="Entering {func}({func_args},{func_kwargs})...",
|
||||
)
|
||||
def _getFileList(
|
||||
origin, path=None, filter=None, recursive=False, level=0, allow_from_cache=True
|
||||
):
|
||||
if origin == FileDestinations.SDCARD:
|
||||
sdFileList = printer.get_sd_files()
|
||||
sdFileList = printer.get_sd_files(refresh=not allow_from_cache)
|
||||
|
||||
files = []
|
||||
if sdFileList is not None:
|
||||
@@ -287,7 +292,7 @@ def _getFileList(
|
||||
)
|
||||
|
||||
with _file_cache_mutex:
|
||||
cache_key = "{}:{}:{}:{}".format(origin, path, recursive, filter)
|
||||
cache_key = f"{origin}:{path}:{recursive}:{filter}"
|
||||
files, lastmodified = _file_cache.get(cache_key, ([], None))
|
||||
# recursive needs to be True for lastmodified queries so we get lastmodified of whole subtree - #3422
|
||||
if (
|
||||
@@ -449,7 +454,7 @@ def uploadGcodeFile(target):
|
||||
)
|
||||
if input_upload_name in request.values and input_upload_path in request.values:
|
||||
if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown target: %s" % target, 404)
|
||||
abort(404)
|
||||
|
||||
upload = octoprint.filemanager.util.DiskFileWrapper(
|
||||
request.values[input_upload_name], request.values[input_upload_path]
|
||||
@@ -463,12 +468,12 @@ def uploadGcodeFile(target):
|
||||
try:
|
||||
userdata = json.loads(request.values["userdata"])
|
||||
except Exception:
|
||||
return make_response("userdata contains invalid JSON", 400)
|
||||
abort(400, description="userdata contains invalid JSON")
|
||||
|
||||
if target == FileDestinations.SDCARD and not settings().getBoolean(
|
||||
["feature", "sdSupport"]
|
||||
):
|
||||
return make_response("SD card support is disabled", 404)
|
||||
abort(404)
|
||||
|
||||
sd = target == FileDestinations.SDCARD
|
||||
selectAfterUpload = (
|
||||
@@ -488,14 +493,12 @@ def uploadGcodeFile(target):
|
||||
printer.is_operational()
|
||||
and not (printer.is_printing() or printer.is_paused())
|
||||
):
|
||||
return make_response(
|
||||
"Can not upload to SD card, printer is either not operational or already busy",
|
||||
abort(
|
||||
409,
|
||||
description="Can not upload to SD card, printer is either not operational or already busy",
|
||||
)
|
||||
if not printer.is_sd_ready():
|
||||
return make_response(
|
||||
"Can not upload to SD card, not yet initialized", 409
|
||||
)
|
||||
abort(409, description="Can not upload to SD card, not yet initialized")
|
||||
|
||||
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||
try:
|
||||
@@ -513,9 +516,7 @@ def uploadGcodeFile(target):
|
||||
futureFilename = None
|
||||
|
||||
if futureFilename is None:
|
||||
return make_response(
|
||||
"Can not upload file %s, wrong format?" % upload.filename, 415
|
||||
)
|
||||
abort(415, description="Can not upload file, wrong format?")
|
||||
|
||||
if "path" in request.values and request.values["path"]:
|
||||
# we currently only support uploads to sdcard via local, so first target is local instead of "target"
|
||||
@@ -532,10 +533,9 @@ def uploadGcodeFile(target):
|
||||
)
|
||||
|
||||
if not printer.can_modify_file(futureFullPathInStorage, sd):
|
||||
return make_response(
|
||||
"Trying to overwrite file that is currently being printed: %s"
|
||||
% futureFullPath,
|
||||
abort(
|
||||
409,
|
||||
description="Trying to overwrite file that is currently being printed",
|
||||
)
|
||||
|
||||
reselect = printer.is_current_file(futureFullPathInStorage, sd)
|
||||
@@ -594,16 +594,9 @@ def uploadGcodeFile(target):
|
||||
)
|
||||
except octoprint.filemanager.storage.StorageError as e:
|
||||
if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE:
|
||||
return make_response(
|
||||
'Could not upload the file "{}", invalid type'.format(
|
||||
upload.filename
|
||||
),
|
||||
400,
|
||||
)
|
||||
abort(400, description="Could not upload file, invalid type")
|
||||
else:
|
||||
return make_response(
|
||||
'Could not upload the file "{}"'.format(upload.filename), 500
|
||||
)
|
||||
abort(500, description="Could not upload file")
|
||||
|
||||
if octoprint.filemanager.valid_file_type(added_file, "stl"):
|
||||
filename = added_file
|
||||
@@ -688,13 +681,13 @@ def uploadGcodeFile(target):
|
||||
foldername = request.values["foldername"]
|
||||
|
||||
if target not in [FileDestinations.LOCAL]:
|
||||
return make_response("Unknown target: %s" % target, 400)
|
||||
abort(400, description="target is invalid")
|
||||
|
||||
canonPath, canonName = fileManager.canonicalize(target, foldername)
|
||||
futurePath = fileManager.sanitize_path(target, canonPath)
|
||||
futureName = fileManager.sanitize_name(target, canonName)
|
||||
if not futureName or not futurePath:
|
||||
return make_response("Can't create a folder with an empty name", 400)
|
||||
abort(400, description="folder name is empty")
|
||||
|
||||
if "path" in request.values and request.values["path"]:
|
||||
futurePath = fileManager.sanitize_path(
|
||||
@@ -703,10 +696,7 @@ def uploadGcodeFile(target):
|
||||
|
||||
futureFullPath = fileManager.join_path(target, futurePath, futureName)
|
||||
if octoprint.filemanager.valid_file_type(futureName):
|
||||
return make_response(
|
||||
"Can't create a folder named %s, please try another name" % futureName,
|
||||
409,
|
||||
)
|
||||
abort(409, description="Can't create folder, please try another name")
|
||||
|
||||
try:
|
||||
added_folder = fileManager.add_folder(
|
||||
@@ -714,11 +704,9 @@ def uploadGcodeFile(target):
|
||||
)
|
||||
except octoprint.filemanager.storage.StorageError as e:
|
||||
if e.code == octoprint.filemanager.storage.StorageError.INVALID_DIRECTORY:
|
||||
return make_response(
|
||||
"Could not create folder {}, invalid directory".format(futureName)
|
||||
)
|
||||
abort(400, description="Could not create folder, invalid directory")
|
||||
else:
|
||||
return make_response("Could not create folder {}".format(futureName))
|
||||
abort(500, description="Could not create folder")
|
||||
|
||||
location = url_for(
|
||||
".readGcodeFile",
|
||||
@@ -738,14 +726,17 @@ def uploadGcodeFile(target):
|
||||
return r
|
||||
|
||||
else:
|
||||
return make_response("No file to upload and no folder to create", 400)
|
||||
abort(400, description="No file to upload and no folder to create")
|
||||
|
||||
|
||||
@api.route("/files/<string:target>/<path:filename>", methods=["POST"])
|
||||
@no_firstrun_access
|
||||
def gcodeFileCommand(filename, target):
|
||||
if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown target: %s" % target, 404)
|
||||
abort(404)
|
||||
|
||||
if not _validate(target, filename):
|
||||
abort(404)
|
||||
|
||||
# valid file commands, dict mapping command name to mandatory parameters
|
||||
valid_commands = {
|
||||
@@ -765,31 +756,28 @@ def gcodeFileCommand(filename, target):
|
||||
if command == "select":
|
||||
with Permissions.FILES_SELECT.require(403):
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response(
|
||||
"File not found on '%s': %s" % (target, filename), 404
|
||||
)
|
||||
abort(404)
|
||||
|
||||
# selects/loads a file
|
||||
if not octoprint.filemanager.valid_file_type(filename, type="machinecode"):
|
||||
return make_response(
|
||||
"Cannot select {filename} for printing, not a machinecode file".format(
|
||||
**locals()
|
||||
),
|
||||
abort(
|
||||
415,
|
||||
description="Cannot select file for printing, not a machinecode file",
|
||||
)
|
||||
|
||||
if not printer.is_ready():
|
||||
return make_response(
|
||||
"Printer is already printing, cannot select a new file", 409
|
||||
abort(
|
||||
409,
|
||||
description="Printer is already printing, cannot select a new file",
|
||||
)
|
||||
|
||||
print_after_loading = False
|
||||
if "print" in data and data["print"] in valid_boolean_trues:
|
||||
with Permissions.PRINT.require(403):
|
||||
if not printer.is_operational():
|
||||
return make_response(
|
||||
"Printer is not operational, cannot directly start printing",
|
||||
abort(
|
||||
409,
|
||||
description="Printer is not operational, cannot directly start printing",
|
||||
)
|
||||
print_after_loading = True
|
||||
|
||||
@@ -799,9 +787,7 @@ def gcodeFileCommand(filename, target):
|
||||
elif command == "slice":
|
||||
with Permissions.SLICE.require(403):
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response(
|
||||
"File not found on '%s': %s" % (target, filename), 404
|
||||
)
|
||||
abort(404)
|
||||
|
||||
try:
|
||||
if "slicer" in data:
|
||||
@@ -814,14 +800,9 @@ def gcodeFileCommand(filename, target):
|
||||
slicer_instance = slicingManager.get_slicer("cura")
|
||||
|
||||
else:
|
||||
return make_response(
|
||||
"Cannot slice {filename}, no slicer available".format(**locals()),
|
||||
415,
|
||||
)
|
||||
except octoprint.slicing.UnknownSlicer as e:
|
||||
return make_response(
|
||||
"Slicer {slicer} is not available".format(slicer=e.slicer), 400
|
||||
)
|
||||
abort(415, description="Cannot slice file, no slicer available")
|
||||
except octoprint.slicing.UnknownSlicer:
|
||||
abort(404)
|
||||
|
||||
if not any(
|
||||
[
|
||||
@@ -831,9 +812,7 @@ def gcodeFileCommand(filename, target):
|
||||
)
|
||||
]
|
||||
):
|
||||
return make_response(
|
||||
"Cannot slice {filename}, not a model file".format(**locals()), 415
|
||||
)
|
||||
abort(415, description="Cannot slice file, not a model file")
|
||||
|
||||
cores = psutil.cpu_count()
|
||||
if (
|
||||
@@ -842,11 +821,9 @@ def gcodeFileCommand(filename, target):
|
||||
and (cores is None or cores < 2)
|
||||
):
|
||||
# slicer runs on same device as OctoPrint, slicing while printing is hence disabled
|
||||
return make_response(
|
||||
"Cannot slice on {slicer} while printing on single core systems or systems of unknown core count due to performance reasons".format(
|
||||
**locals()
|
||||
),
|
||||
abort(
|
||||
409,
|
||||
description="Cannot slice on this slicer while printing on single core systems or systems of unknown core count due to performance reasons",
|
||||
)
|
||||
|
||||
if "destination" in data and data["destination"]:
|
||||
@@ -890,10 +867,9 @@ def gcodeFileCommand(filename, target):
|
||||
and currentOrigin == target
|
||||
and (printer.is_printing() or printer.is_paused())
|
||||
):
|
||||
make_response(
|
||||
"Trying to slice into file that is currently being printed: %s"
|
||||
% full_path,
|
||||
abort(
|
||||
409,
|
||||
description="Trying to slice into file that is currently being printed",
|
||||
)
|
||||
|
||||
if "profile" in data and data["profile"]:
|
||||
@@ -923,17 +899,18 @@ def gcodeFileCommand(filename, target):
|
||||
select_after_slicing = False
|
||||
if "select" in data and data["select"] in valid_boolean_trues:
|
||||
if not printer.is_operational():
|
||||
return make_response(
|
||||
"Printer is not operational, cannot directly select for printing",
|
||||
abort(
|
||||
409,
|
||||
description="Printer is not operational, cannot directly select for printing",
|
||||
)
|
||||
select_after_slicing = True
|
||||
|
||||
print_after_slicing = False
|
||||
if "print" in data and data["print"] in valid_boolean_trues:
|
||||
if not printer.is_operational():
|
||||
return make_response(
|
||||
"Printer is not operational, cannot directly start printing", 409
|
||||
abort(
|
||||
409,
|
||||
description="Printer is not operational, cannot directly start printing",
|
||||
)
|
||||
select_after_slicing = print_after_slicing = True
|
||||
|
||||
@@ -975,11 +952,8 @@ def gcodeFileCommand(filename, target):
|
||||
),
|
||||
)
|
||||
except octoprint.slicing.UnknownProfile:
|
||||
return make_response(
|
||||
"Profile {profile} doesn't exist".format(**locals()), 400
|
||||
)
|
||||
abort(404, description="Unknown profile")
|
||||
|
||||
files = {}
|
||||
location = url_for(
|
||||
".readGcodeFile", target=target, filename=full_path, _external=True
|
||||
)
|
||||
@@ -1005,9 +979,7 @@ def gcodeFileCommand(filename, target):
|
||||
elif command == "analyse":
|
||||
with Permissions.FILES_UPLOAD.require(403):
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response(
|
||||
"File not found on '%s': %s" % (target, filename), 404
|
||||
)
|
||||
abort(404)
|
||||
|
||||
printer_profile = None
|
||||
if "printerProfile" in data and data["printerProfile"]:
|
||||
@@ -1016,24 +988,18 @@ def gcodeFileCommand(filename, target):
|
||||
if not fileManager.analyse(
|
||||
target, filename, printer_profile_id=printer_profile
|
||||
):
|
||||
return make_response(
|
||||
"No analysis possible for {} on {}".format(filename, target), 400
|
||||
)
|
||||
abort(400, description="No analysis possible")
|
||||
|
||||
elif command == "copy" or command == "move":
|
||||
with Permissions.FILES_UPLOAD.require(403):
|
||||
# Copy and move are only possible on local storage
|
||||
if target not in [FileDestinations.LOCAL]:
|
||||
return make_response(
|
||||
"Unsupported target for {}: {}".format(command, target), 400
|
||||
)
|
||||
abort(400, description=f"Unsupported target for {command}")
|
||||
|
||||
if not _verifyFileExists(target, filename) and not _verifyFolderExists(
|
||||
target, filename
|
||||
):
|
||||
return make_response(
|
||||
"File or folder not found on {}: {}".format(target, filename), 404
|
||||
)
|
||||
abort(404)
|
||||
|
||||
path, name = fileManager.split_path(target, filename)
|
||||
|
||||
@@ -1054,35 +1020,20 @@ def gcodeFileCommand(filename, target):
|
||||
if _verifyFileExists(target, destination) or _verifyFolderExists(
|
||||
target, destination
|
||||
):
|
||||
return make_response(
|
||||
"File or folder does already exist on {}: {}".format(
|
||||
target, destination
|
||||
),
|
||||
409,
|
||||
)
|
||||
abort(409, description="File or folder does already exist")
|
||||
|
||||
is_file = fileManager.file_exists(target, filename)
|
||||
is_folder = fileManager.folder_exists(target, filename)
|
||||
|
||||
if not (is_file or is_folder):
|
||||
return make_response(
|
||||
"{} on {} is neither file or folder, can't {}".format(
|
||||
filename, target, command
|
||||
),
|
||||
400,
|
||||
)
|
||||
abort(400, description=f"Neither file nor folder, can't {command}")
|
||||
|
||||
if command == "copy":
|
||||
# destination already there? error...
|
||||
if _verifyFileExists(target, destination) or _verifyFolderExists(
|
||||
target, destination
|
||||
):
|
||||
return make_response(
|
||||
"File or folder does already exist on {}: {}".format(
|
||||
target, destination
|
||||
),
|
||||
409,
|
||||
)
|
||||
abort(409, description="File or folder does already exist")
|
||||
|
||||
if is_file:
|
||||
fileManager.copy_file(target, filename, destination)
|
||||
@@ -1092,11 +1043,9 @@ def gcodeFileCommand(filename, target):
|
||||
elif command == "move":
|
||||
with Permissions.FILES_DELETE.require(403):
|
||||
if _isBusy(target, filename):
|
||||
return make_response(
|
||||
"Trying to move a file or folder that is currently in use: {}".format(
|
||||
filename
|
||||
),
|
||||
abort(
|
||||
409,
|
||||
description="Trying to move a file or folder that is currently in use",
|
||||
)
|
||||
|
||||
# destination already there AND not ourselves (= display rename)? error...
|
||||
@@ -1104,12 +1053,7 @@ def gcodeFileCommand(filename, target):
|
||||
_verifyFileExists(target, destination)
|
||||
or _verifyFolderExists(target, destination)
|
||||
) and sanitized_destination != filename:
|
||||
return make_response(
|
||||
"File or folder does already exist on {}: {}".format(
|
||||
target, destination
|
||||
),
|
||||
409,
|
||||
)
|
||||
abort(409, description="File or folder does already exist")
|
||||
|
||||
# deselect the file if it's currently selected
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
@@ -1150,21 +1094,20 @@ def gcodeFileCommand(filename, target):
|
||||
@no_firstrun_access
|
||||
@Permissions.FILES_DELETE.require(403)
|
||||
def deleteGcodeFile(filename, target):
|
||||
if not _validate(target, filename):
|
||||
abort(404)
|
||||
|
||||
if not _verifyFileExists(target, filename) and not _verifyFolderExists(
|
||||
target, filename
|
||||
):
|
||||
return make_response(
|
||||
"File/Folder not found on '%s': %s" % (target, filename), 404
|
||||
)
|
||||
abort(404)
|
||||
|
||||
if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
abort(404)
|
||||
|
||||
if _verifyFileExists(target, filename):
|
||||
if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown target: %s" % target, 400)
|
||||
|
||||
if _isBusy(target, filename):
|
||||
return make_response(
|
||||
"Trying to delete a file that is currently in use: %s" % filename, 409
|
||||
)
|
||||
abort(409, description="Trying to delete a file that is currently in use")
|
||||
|
||||
# deselect the file if it's currently selected
|
||||
currentOrigin, currentPath = _getCurrentFile()
|
||||
@@ -1182,14 +1125,10 @@ def deleteGcodeFile(filename, target):
|
||||
fileManager.remove_file(target, filename)
|
||||
|
||||
elif _verifyFolderExists(target, filename):
|
||||
if target not in [FileDestinations.LOCAL]:
|
||||
return make_response("Unknown target: %s" % target, 400)
|
||||
|
||||
if _isBusy(target, filename):
|
||||
return make_response(
|
||||
"Trying to delete a folder that contains a file that is currently in use: %s"
|
||||
% filename,
|
||||
abort(
|
||||
409,
|
||||
description="Trying to delete a folder that contains a file that is currently in use",
|
||||
)
|
||||
|
||||
# deselect the file if it's currently selected
|
||||
@@ -1220,6 +1159,12 @@ def _getCurrentFile():
|
||||
return None, None
|
||||
|
||||
|
||||
def _validate(target, filename):
|
||||
return filename == "/".join(
|
||||
map(lambda x: fileManager.sanitize_name(target, x), filename.split("/"))
|
||||
)
|
||||
|
||||
|
||||
class WerkzeugFileWrapper(octoprint.filemanager.util.AbstractFileWrapper):
|
||||
"""
|
||||
A wrapper around a Werkzeug ``FileStorage`` object.
|
||||
|
||||
@@ -2,7 +2,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import jsonify, make_response, request
|
||||
from flask import abort, jsonify, request
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.server import NO_CONTENT, current_user, printer
|
||||
@@ -14,7 +14,7 @@ from octoprint.server.util.flask import get_json_command_from_request, no_firstr
|
||||
@no_firstrun_access
|
||||
def controlJob():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
abort(409, description="Printer is not operational")
|
||||
|
||||
valid_commands = {"start": [], "restart": [], "pause": [], "cancel": []}
|
||||
|
||||
@@ -31,22 +31,23 @@ def controlJob():
|
||||
with Permissions.PRINT.require(403):
|
||||
if command == "start":
|
||||
if activePrintjob:
|
||||
return make_response(
|
||||
"Printer already has an active print job, did you mean 'restart'?",
|
||||
abort(
|
||||
409,
|
||||
description="Printer already has an active print job, did you mean 'restart'?",
|
||||
)
|
||||
printer.start_print(tags=tags, user=user)
|
||||
elif command == "restart":
|
||||
if not printer.is_paused():
|
||||
return make_response(
|
||||
"Printer does not have an active print job or is not paused", 409
|
||||
abort(
|
||||
409,
|
||||
description="Printer does not have an active print job or is not paused",
|
||||
)
|
||||
printer.start_print(tags=tags, user=user)
|
||||
elif command == "pause":
|
||||
if not activePrintjob:
|
||||
return make_response(
|
||||
"Printer is neither printing nor paused, 'pause' command cannot be performed",
|
||||
abort(
|
||||
409,
|
||||
description="Printer is neither printing nor paused, 'pause' command cannot be performed",
|
||||
)
|
||||
action = data.get("action", "toggle")
|
||||
if action == "toggle":
|
||||
@@ -56,17 +57,12 @@ def controlJob():
|
||||
elif action == "resume":
|
||||
printer.resume_print(tags=tags, user=user)
|
||||
else:
|
||||
return make_response(
|
||||
"Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format(
|
||||
action
|
||||
),
|
||||
400,
|
||||
)
|
||||
abort(400, description="Unknown action")
|
||||
elif command == "cancel":
|
||||
if not activePrintjob:
|
||||
return make_response(
|
||||
"Printer is neither printing nor paused, 'cancel' command cannot be performed",
|
||||
abort(
|
||||
409,
|
||||
description="Printer is neither printing nor paused, 'cancel' command cannot be performed",
|
||||
)
|
||||
printer.cancel_print(tags=tags, user=user)
|
||||
return NO_CONTENT
|
||||
|
||||
@@ -2,7 +2,6 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import tarfile
|
||||
@@ -10,7 +9,7 @@ import zipfile
|
||||
from collections import defaultdict
|
||||
from os import scandir
|
||||
|
||||
from flask import jsonify, make_response, request
|
||||
from flask import abort, jsonify, request
|
||||
from flask_babel import Locale
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
@@ -44,7 +43,7 @@ def getInstalledLanguagePacks():
|
||||
import yaml
|
||||
|
||||
try:
|
||||
with io.open(meta_path, "rt", encoding="utf-8") as f:
|
||||
with open(meta_path, encoding="utf-8") as f:
|
||||
meta = yaml.safe_load(f)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Could not load %s", meta_path)
|
||||
@@ -127,7 +126,7 @@ def uploadLanguagePack():
|
||||
input_name + "." + settings().get(["server", "uploads", "nameSuffix"])
|
||||
)
|
||||
if input_upload_path not in request.values or input_upload_name not in request.values:
|
||||
return make_response("No file included", 400)
|
||||
abort(400, description="No file included")
|
||||
|
||||
upload_name = request.values[input_upload_name]
|
||||
upload_path = request.values[input_upload_path]
|
||||
@@ -138,8 +137,9 @@ def uploadLanguagePack():
|
||||
)
|
||||
)
|
||||
if not len(exts):
|
||||
return make_response(
|
||||
"File doesn't have a valid extension for a language pack archive", 400
|
||||
abort(
|
||||
400,
|
||||
description="File doesn't have a valid extension for a language pack archive",
|
||||
)
|
||||
|
||||
target_path = settings().getBaseFolder("translations")
|
||||
@@ -149,7 +149,7 @@ def uploadLanguagePack():
|
||||
elif zipfile.is_zipfile(upload_path):
|
||||
_unpack_uploaded_zipfile(upload_path, target_path)
|
||||
else:
|
||||
return make_response("Neither zip file nor tarball included", 400)
|
||||
abort(400, description="Neither zip file nor tarball included")
|
||||
|
||||
return getInstalledLanguagePacks()
|
||||
|
||||
|
||||
@@ -4,8 +4,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import re
|
||||
|
||||
from flask import Response, jsonify, make_response, request
|
||||
from werkzeug.exceptions import BadRequest
|
||||
from flask import Response, abort, jsonify, request
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.printer import UnknownScript
|
||||
@@ -21,7 +20,7 @@ from octoprint.settings import settings, valid_boolean_trues
|
||||
@Permissions.STATUS.require(403)
|
||||
def printerState():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
abort(409, description="Printer is not operational")
|
||||
|
||||
# process excludes
|
||||
excludes = []
|
||||
@@ -71,7 +70,7 @@ def printerState():
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerToolCommand():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
abort(409, description="Printer is not operational")
|
||||
|
||||
valid_commands = {
|
||||
"select": ["tool"],
|
||||
@@ -92,9 +91,7 @@ def printerToolCommand():
|
||||
if command == "select":
|
||||
tool = data["tool"]
|
||||
if not isinstance(tool, str) or re.match(validation_regex, tool) is None:
|
||||
return make_response("Invalid tool: %s" % tool, 400)
|
||||
if not tool.startswith("tool"):
|
||||
return make_response("Invalid tool for selection: %s" % tool, 400)
|
||||
abort(400, description="tool is invalid")
|
||||
|
||||
printer.change_tool(tool, tags=tags)
|
||||
|
||||
@@ -106,11 +103,9 @@ def printerToolCommand():
|
||||
validated_values = {}
|
||||
for tool, value in targets.items():
|
||||
if re.match(validation_regex, tool) is None:
|
||||
return make_response(
|
||||
"Invalid target for setting temperature: %s" % tool, 400
|
||||
)
|
||||
abort(400, description="targets contains invalid tool")
|
||||
if not isinstance(value, (int, float)):
|
||||
return make_response("Not a number for %s: %r" % (tool, value), 400)
|
||||
abort(400, description="targets contains invalid value")
|
||||
validated_values[tool] = value
|
||||
|
||||
# perform the actual temperature commands
|
||||
@@ -125,15 +120,9 @@ def printerToolCommand():
|
||||
validated_values = {}
|
||||
for tool, value in offsets.items():
|
||||
if re.match(validation_regex, tool) is None:
|
||||
return make_response(
|
||||
"Invalid target for setting temperature: %s" % tool, 400
|
||||
)
|
||||
if not isinstance(value, (int, float)):
|
||||
return make_response("Not a number for %s: %r" % (tool, value), 400)
|
||||
if not -50 <= value <= 50:
|
||||
return make_response(
|
||||
"Offset %s not in range [-50, 50]: %f" % (tool, value), 400
|
||||
)
|
||||
abort(400, description="offsets contains invalid tool")
|
||||
if not isinstance(value, (int, float)) or not -50 <= value <= 50:
|
||||
abort(400, description="offsets contains invalid value")
|
||||
validated_values[tool] = value
|
||||
|
||||
# set the offsets
|
||||
@@ -143,22 +132,22 @@ def printerToolCommand():
|
||||
elif command == "extrude":
|
||||
if printer.is_printing():
|
||||
# do not extrude when a print job is running
|
||||
return make_response("Printer is currently printing", 409)
|
||||
abort(409, description="Printer is currently printing")
|
||||
|
||||
amount = data["amount"]
|
||||
speed = data.get("speed", None)
|
||||
if not isinstance(amount, (int, float)):
|
||||
return make_response("Not a number for extrusion amount: %r" % amount, 400)
|
||||
abort(400, description="amount is invalid")
|
||||
printer.extrude(amount, speed=speed, tags=tags)
|
||||
|
||||
elif command == "flowrate":
|
||||
factor = data["factor"]
|
||||
if not isinstance(factor, (int, float)):
|
||||
return make_response("Not a number for flow rate: %r" % factor, 400)
|
||||
abort(400, description="factor is invalid")
|
||||
try:
|
||||
printer.flow_rate(factor, tags=tags)
|
||||
except ValueError as e:
|
||||
return make_response("Invalid value for flow rate: %s" % str(e), 400)
|
||||
except ValueError:
|
||||
abort(400, description="factor is invalid")
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
@@ -168,7 +157,7 @@ def printerToolCommand():
|
||||
@Permissions.STATUS.require(403)
|
||||
def printerToolState():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
abort(409, description="Printer is not operational")
|
||||
|
||||
return jsonify(_get_temperature_data(_keep_tools))
|
||||
|
||||
@@ -181,10 +170,10 @@ def printerToolState():
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerBedCommand():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
abort(409, description="Printer is not operational")
|
||||
|
||||
if not printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
return make_response("Printer does not have a heated bed", 409)
|
||||
abort(409, description="Printer does not have a heated bed")
|
||||
|
||||
valid_commands = {"target": ["target"], "offset": ["offset"]}
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
@@ -199,7 +188,7 @@ def printerBedCommand():
|
||||
|
||||
# make sure the target is a number
|
||||
if not isinstance(target, (int, float)):
|
||||
return make_response("Not a number: %r" % target, 400)
|
||||
abort(400, description="target is invalid")
|
||||
|
||||
# perform the actual temperature command
|
||||
printer.set_temperature("bed", target, tags=tags)
|
||||
@@ -209,10 +198,8 @@ def printerBedCommand():
|
||||
offset = data["offset"]
|
||||
|
||||
# make sure the offset is valid
|
||||
if not isinstance(offset, (int, float)):
|
||||
return make_response("Not a number: %r" % offset, 400)
|
||||
if not -50 <= offset <= 50:
|
||||
return make_response("Offset not in range [-50, 50]: %f" % offset, 400)
|
||||
if not isinstance(offset, (int, float)) or not -50 <= offset <= 50:
|
||||
abort(400, description="offset is invalid")
|
||||
|
||||
# set the offsets
|
||||
printer.set_temperature_offset({"bed": offset})
|
||||
@@ -225,10 +212,10 @@ def printerBedCommand():
|
||||
@Permissions.STATUS.require(403)
|
||||
def printerBedState():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
abort(409, description="Printer is not operational")
|
||||
|
||||
if not printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
return make_response("Printer does not have a heated bed", 409)
|
||||
abort(409, description="Printer does not have a heated bed")
|
||||
|
||||
data = _get_temperature_data(_keep_bed)
|
||||
if isinstance(data, Response):
|
||||
@@ -245,10 +232,10 @@ def printerBedState():
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerChamberCommand():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
abort(409, description="Printer is not operational")
|
||||
|
||||
if not printerProfileManager.get_current_or_default()["heatedChamber"]:
|
||||
return make_response("Printer does not have a heated chamber", 409)
|
||||
abort(409, description="Printer does not have a heated chamber")
|
||||
|
||||
valid_commands = {"target": ["target"], "offset": ["offset"]}
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
@@ -263,7 +250,7 @@ def printerChamberCommand():
|
||||
|
||||
# make sure the target is a number
|
||||
if not isinstance(target, (int, float)):
|
||||
return make_response("Not a number: %r" % target, 400)
|
||||
abort(400, description="target is invalid")
|
||||
|
||||
# perform the actual temperature command
|
||||
printer.set_temperature("chamber", target, tags=tags)
|
||||
@@ -273,10 +260,8 @@ def printerChamberCommand():
|
||||
offset = data["offset"]
|
||||
|
||||
# make sure the offset is valid
|
||||
if not isinstance(offset, (int, float)):
|
||||
return make_response("Not a number: %r" % offset, 400)
|
||||
if not -50 <= offset <= 50:
|
||||
return make_response("Offset not in range [-50, 50]: %f" % offset, 400)
|
||||
if not isinstance(offset, (int, float)) or not -50 <= offset <= 50:
|
||||
abort(400, description="offset is invalid")
|
||||
|
||||
# set the offsets
|
||||
printer.set_temperature_offset({"chamber": offset})
|
||||
@@ -289,10 +274,10 @@ def printerChamberCommand():
|
||||
@Permissions.STATUS.require(403)
|
||||
def printerChamberState():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
abort(409, description="Printer is not operational")
|
||||
|
||||
if not printerProfileManager.get_current_or_default()["heatedChamber"]:
|
||||
return make_response("Printer does not have a heated chamber", 409)
|
||||
abort(409, description="Printer does not have a heated chamber")
|
||||
|
||||
data = _get_temperature_data(_keep_chamber)
|
||||
if isinstance(data, Response):
|
||||
@@ -315,7 +300,7 @@ def printerPrintheadCommand():
|
||||
|
||||
if not printer.is_operational() or (printer.is_printing() and command != "feedrate"):
|
||||
# do not jog when a print job is running or we don't have a connection
|
||||
return make_response("Printer is not operational or currently printing", 409)
|
||||
abort(409, description="Printer is not operational or currently printing")
|
||||
|
||||
tags = {"source:api", "api:printer.printhead"}
|
||||
|
||||
@@ -328,9 +313,7 @@ def printerPrintheadCommand():
|
||||
if axis in data:
|
||||
value = data[axis]
|
||||
if not isinstance(value, (int, float)):
|
||||
return make_response(
|
||||
"Not a number for axis %s: %r" % (axis, value), 400
|
||||
)
|
||||
abort(400, description="axis value is invalid")
|
||||
validated_values[axis] = value
|
||||
|
||||
absolute = "absolute" in data and data["absolute"] in valid_boolean_trues
|
||||
@@ -345,7 +328,7 @@ def printerPrintheadCommand():
|
||||
axes = data["axes"]
|
||||
for axis in axes:
|
||||
if axis not in valid_axes:
|
||||
return make_response("Invalid axis: %s" % axis, 400)
|
||||
abort(400, description="axis is invalid")
|
||||
validated_values.append(axis)
|
||||
|
||||
# execute the home command
|
||||
@@ -354,11 +337,11 @@ def printerPrintheadCommand():
|
||||
elif command == "feedrate":
|
||||
factor = data["factor"]
|
||||
if not isinstance(factor, (int, float)):
|
||||
return make_response("Not a number for feed rate: %r" % factor, 400)
|
||||
abort(400, description="factor is invalid")
|
||||
try:
|
||||
printer.feed_rate(factor, tags=tags)
|
||||
except ValueError as e:
|
||||
return make_response("Invalid value for feed rate: %s" % str(e), 400)
|
||||
except ValueError:
|
||||
abort(400, description="factor is invalid")
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
@@ -371,10 +354,10 @@ def printerPrintheadCommand():
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerSdCommand():
|
||||
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||
return make_response("SD support is disabled", 404)
|
||||
abort(404, description="SD support is disabled")
|
||||
|
||||
if not printer.is_operational() or printer.is_printing() or printer.is_paused():
|
||||
return make_response("Printer is not operational or currently busy", 409)
|
||||
abort(409, description="Printer is not operational or currently busy")
|
||||
|
||||
valid_commands = {"init": [], "refresh": [], "release": []}
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
@@ -398,7 +381,7 @@ def printerSdCommand():
|
||||
@Permissions.STATUS.require(403)
|
||||
def printerSdState():
|
||||
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||
return make_response("SD support is disabled", 404)
|
||||
abort(404, description="SD support is disabled")
|
||||
|
||||
return jsonify(ready=printer.is_sd_ready())
|
||||
|
||||
@@ -411,27 +394,22 @@ def printerSdState():
|
||||
@Permissions.CONTROL.require(403)
|
||||
def printerCommand():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
abort(409, description="Printer is not operational")
|
||||
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
return make_response("Expected content type JSON", 400)
|
||||
abort(400, description="Expected content type JSON")
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
data = request.get_json()
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
abort(400, description="Malformed JSON body in request")
|
||||
|
||||
if "command" in data and "commands" in data:
|
||||
return make_response("'command' and 'commands' are mutually exclusive", 400)
|
||||
abort(400, description="'command' and 'commands' are mutually exclusive")
|
||||
elif ("command" in data or "commands" in data) and "script" in data:
|
||||
return make_response(
|
||||
"'command'/'commands' and 'script' are mutually exclusive", 400
|
||||
)
|
||||
abort(400, description="'command'/'commands' and 'script' are mutually exclusive")
|
||||
elif not ("command" in data or "commands" in data or "script" in data):
|
||||
return make_response("Need one of 'command', 'commands' or 'script'", 400)
|
||||
abort(400, description="Need one of 'command', 'commands' or 'script'")
|
||||
|
||||
parameters = {}
|
||||
if "parameters" in data:
|
||||
@@ -444,7 +422,7 @@ def printerCommand():
|
||||
commands = [data["command"]]
|
||||
else:
|
||||
if not isinstance(data["commands"], (list, tuple)):
|
||||
return make_response("'commands' needs to be a list", 400)
|
||||
abort(400, description="commands is invalid")
|
||||
commands = data["commands"]
|
||||
|
||||
commandsToSend = []
|
||||
@@ -465,7 +443,7 @@ def printerCommand():
|
||||
try:
|
||||
printer.script(script_name, context=context, tags=tags)
|
||||
except UnknownScript:
|
||||
return make_response("Unknown script: {script_name}".format(**locals()), 404)
|
||||
abort(404, description="Unknown script")
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
@@ -480,7 +458,7 @@ def getCustomControls():
|
||||
|
||||
def _get_temperature_data(preprocessor):
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
abort(409, description="Printer is not operational")
|
||||
|
||||
tempData = printer.get_current_temperatures()
|
||||
|
||||
|
||||
@@ -5,8 +5,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import copy
|
||||
|
||||
from flask import jsonify, make_response, request, url_for
|
||||
from werkzeug.exceptions import BadRequest
|
||||
from flask import abort, jsonify, request, url_for
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.printer.profile import CouldNotOverwriteError, InvalidProfileError
|
||||
@@ -56,18 +55,15 @@ def printerProfilesList():
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def printerProfilesAdd():
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
abort(400, description="Expected content-type JSON")
|
||||
|
||||
try:
|
||||
json_data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
json_data = request.get_json()
|
||||
|
||||
if json_data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
abort(400, description="Malformed JSON body in request")
|
||||
|
||||
if "profile" not in json_data:
|
||||
return make_response("No profile included in request", 400)
|
||||
abort(400, description="profile is missing")
|
||||
|
||||
base_profile = printerProfileManager.get_default()
|
||||
if "basedOn" in json_data and isinstance(json_data["basedOn"], str):
|
||||
@@ -91,25 +87,20 @@ def printerProfilesAdd():
|
||||
profile = dict_merge(base_profile, new_profile)
|
||||
|
||||
if "id" not in profile:
|
||||
return make_response("Profile does not contain mandatory 'id' field", 400)
|
||||
abort(400, description="profile.id is missing")
|
||||
if "name" not in profile:
|
||||
return make_response("Profile does not contain mandatory 'name' field", 400)
|
||||
abort(400, description="profile.name is missing")
|
||||
|
||||
try:
|
||||
saved_profile = printerProfileManager.save(
|
||||
profile, allow_overwrite=False, make_default=make_default, trigger_event=True
|
||||
)
|
||||
except InvalidProfileError:
|
||||
return make_response("Profile is invalid", 400)
|
||||
abort(400, description="profile is invalid")
|
||||
except CouldNotOverwriteError:
|
||||
return make_response(
|
||||
"Profile {} already exists and overwriting was not allowed".format(
|
||||
profile["id"]
|
||||
),
|
||||
400,
|
||||
)
|
||||
abort(400, description="Profile already exists and overwriting was not allowed")
|
||||
except Exception as e:
|
||||
return make_response("Could not save profile: %s" % str(e), 500)
|
||||
abort(500, description="Could not save profile: %s" % str(e))
|
||||
else:
|
||||
return jsonify({"profile": _convert_profile(saved_profile)})
|
||||
|
||||
@@ -120,7 +111,7 @@ def printerProfilesAdd():
|
||||
def printerProfilesGet(identifier):
|
||||
profile = printerProfileManager.get(identifier)
|
||||
if profile is None:
|
||||
return make_response("Unknown profile: %s" % identifier, 404)
|
||||
abort(404)
|
||||
else:
|
||||
return jsonify(_convert_profile(profile))
|
||||
|
||||
@@ -131,13 +122,11 @@ def printerProfilesGet(identifier):
|
||||
def printerProfilesDelete(identifier):
|
||||
current_profile = printerProfileManager.get_current()
|
||||
if current_profile and current_profile["id"] == identifier:
|
||||
return make_response(
|
||||
"Cannot delete currently selected profile: {}".format(identifier), 409
|
||||
)
|
||||
abort(409, description="Cannot delete currently selected profile")
|
||||
|
||||
default_profile = printerProfileManager.get_default()
|
||||
if default_profile and default_profile["id"] == identifier:
|
||||
return make_response("Cannot delete default profile: {}".format(identifier), 409)
|
||||
abort(409, description="Cannot delete default profile")
|
||||
|
||||
printerProfileManager.remove(identifier, trigger_event=True)
|
||||
return NO_CONTENT
|
||||
@@ -148,18 +137,14 @@ def printerProfilesDelete(identifier):
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def printerProfilesUpdate(identifier):
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
json_data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
abort(400, description="Expected content-type JSON")
|
||||
|
||||
json_data = request.get_json()
|
||||
if json_data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
abort(400, description="Malformed JSON body in request")
|
||||
|
||||
if "profile" not in json_data:
|
||||
return make_response("No profile included in request", 400)
|
||||
abort(400, description="profile missing")
|
||||
|
||||
profile = printerProfileManager.get(identifier)
|
||||
if profile is None:
|
||||
@@ -183,13 +168,11 @@ def printerProfilesUpdate(identifier):
|
||||
trigger_event=True,
|
||||
)
|
||||
except InvalidProfileError:
|
||||
return make_response("Profile is invalid", 400)
|
||||
abort(400, description="profile is invalid")
|
||||
except CouldNotOverwriteError:
|
||||
return make_response(
|
||||
"Profile already exists and overwriting was not allowed", 400
|
||||
)
|
||||
abort(400, description="Profile already exists and overwriting was not allowed")
|
||||
except Exception as e:
|
||||
return make_response("Could not save profile: %s" % str(e), 500)
|
||||
abort(500, description="Could not save profile: %s" % str(e))
|
||||
else:
|
||||
return jsonify({"profile": _convert_profile(saved_profile)})
|
||||
|
||||
|
||||
@@ -4,9 +4,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import logging
|
||||
|
||||
from flask import abort, jsonify, make_response, request
|
||||
from flask import abort, jsonify, request
|
||||
from flask_login import current_user
|
||||
from werkzeug.exceptions import BadRequest
|
||||
|
||||
import octoprint.plugin
|
||||
import octoprint.util
|
||||
@@ -142,7 +141,10 @@ def getSettings():
|
||||
"g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"]),
|
||||
"autoUppercaseBlacklist": s.get(["feature", "autoUppercaseBlacklist"]),
|
||||
},
|
||||
"gcodeAnalysis": {"runAt": s.get(["gcodeAnalysis", "runAt"])},
|
||||
"gcodeAnalysis": {
|
||||
"runAt": s.get(["gcodeAnalysis", "runAt"]),
|
||||
"bedZ": s.getFloat(["gcodeAnalysis", "bedZ"]),
|
||||
},
|
||||
"serial": {
|
||||
"exclusive": s.getBoolean(["serial", "exclusive"]),
|
||||
"autoconnect": s.getBoolean(["serial", "autoconnect"]),
|
||||
@@ -361,22 +363,11 @@ def _get_plugin_settings():
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def setSettings():
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
abort(400, description="Expected content-type JSON")
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not isinstance(data, dict):
|
||||
return make_response(
|
||||
"Malformed request, need settings dictionary, "
|
||||
"got a {} instead: {!r}".format(type(data).__name__, data),
|
||||
400,
|
||||
)
|
||||
data = request.get_json()
|
||||
if data is None or not isinstance(data, dict):
|
||||
abort(400, description="Malformed JSON body in request")
|
||||
|
||||
response = _saveSettings(data)
|
||||
if response:
|
||||
@@ -456,7 +447,7 @@ def _saveSettings(data):
|
||||
|
||||
s.setBaseFolder(folder, future[folder])
|
||||
except Exception:
|
||||
return make_response("At least one of the configured folders is invalid", 400)
|
||||
abort(400, description="At least one of the configured folders is invalid")
|
||||
|
||||
if "api" in data:
|
||||
if "allowCrossOrigin" in data["api"]:
|
||||
@@ -589,6 +580,8 @@ def _saveSettings(data):
|
||||
if "gcodeAnalysis" in data:
|
||||
if "runAt" in data["gcodeAnalysis"]:
|
||||
s.set(["gcodeAnalysis", "runAt"], data["gcodeAnalysis"]["runAt"])
|
||||
if "bedZ" in data["gcodeAnalysis"]:
|
||||
s.setBoolean(["gcodeAnalysis", "bedZ"], data["gcodeAnalysis"]["bedZ"])
|
||||
|
||||
if "serial" in data:
|
||||
if "autoconnect" in data["serial"]:
|
||||
|
||||
@@ -2,8 +2,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import jsonify, make_response, request, url_for
|
||||
from werkzeug.exceptions import BadRequest
|
||||
from flask import abort, jsonify, make_response, request, url_for
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
from octoprint.server import slicingManager
|
||||
@@ -138,7 +137,7 @@ def slicingListSlicerProfiles(slicer):
|
||||
try:
|
||||
return jsonify(_getSlicingProfilesData(slicer, require_configured=configured))
|
||||
except (UnknownSlicer, SlicerNotConfigured):
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
abort(404)
|
||||
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["GET"])
|
||||
@@ -148,9 +147,9 @@ def slicingGetSlicerProfile(slicer, name):
|
||||
try:
|
||||
profile = slicingManager.load_profile(slicer, name, require_configured=False)
|
||||
except UnknownSlicer:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
abort(404)
|
||||
except UnknownProfile:
|
||||
return make_response("Profile not found", 404)
|
||||
abort(404)
|
||||
|
||||
result = _getSlicingProfileData(slicer, name, profile)
|
||||
result["data"] = profile.data
|
||||
@@ -162,15 +161,11 @@ def slicingGetSlicerProfile(slicer, name):
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def slicingAddSlicerProfile(slicer, name):
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
json_data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
abort(400, description="Expected content-type JSON")
|
||||
|
||||
json_data = request.get_json()
|
||||
if json_data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
abort(400, description="Malformed JSON body in request")
|
||||
|
||||
data = {}
|
||||
display_name = None
|
||||
@@ -192,7 +187,7 @@ def slicingAddSlicerProfile(slicer, name):
|
||||
description=description,
|
||||
)
|
||||
except UnknownSlicer:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
abort(404, description="Unknown slicer")
|
||||
|
||||
result = _getSlicingProfileData(slicer, name, profile)
|
||||
r = make_response(jsonify(result), 201)
|
||||
@@ -205,24 +200,18 @@ def slicingAddSlicerProfile(slicer, name):
|
||||
@Permissions.SETTINGS.require(403)
|
||||
def slicingPatchSlicerProfile(slicer, name):
|
||||
if "application/json" not in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
abort(400, description="Expected content-type JSON")
|
||||
|
||||
try:
|
||||
profile = slicingManager.load_profile(slicer, name, require_configured=False)
|
||||
except UnknownSlicer:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
return abort(404)
|
||||
except UnknownProfile:
|
||||
return make_response(
|
||||
"Profile {name} for slicer {slicer} not found".format(**locals()), 404
|
||||
)
|
||||
|
||||
try:
|
||||
json_data = request.get_json()
|
||||
except BadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
return abort(404)
|
||||
|
||||
json_data = request.get_json()
|
||||
if json_data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
abort(400, description="Malformed JSON body in request")
|
||||
|
||||
data = {}
|
||||
display_name = None
|
||||
@@ -259,13 +248,13 @@ def slicingDelSlicerProfile(slicer, name):
|
||||
try:
|
||||
slicingManager.delete_profile(slicer, name)
|
||||
except UnknownSlicer:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
abort(404)
|
||||
except CouldNotDeleteProfile as e:
|
||||
return make_response(
|
||||
"Could not delete profile {profile} for slicer {slicer}: {cause}".format(
|
||||
profile=name, slicer=slicer, cause=str(e.cause)
|
||||
),
|
||||
abort(
|
||||
500,
|
||||
description="Could not delete profile for slicer: {cause}".format(
|
||||
cause=str(e.cause)
|
||||
),
|
||||
)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
@@ -7,7 +7,7 @@ import threading
|
||||
|
||||
import psutil
|
||||
import sarge
|
||||
from flask import jsonify, make_response, request, url_for
|
||||
from flask import abort, jsonify, request, url_for
|
||||
from flask_babel import gettext
|
||||
|
||||
from octoprint.access.permissions import Permissions
|
||||
@@ -84,7 +84,7 @@ def performSystemAction():
|
||||
data = request.values
|
||||
|
||||
if "action" not in data:
|
||||
return make_response("action to perform is not defined", 400)
|
||||
abort(400, description="action is missing")
|
||||
|
||||
return executeSystemCommand("custom", data["action"])
|
||||
|
||||
@@ -108,7 +108,7 @@ def retrieveSystemCommandsForSource(source):
|
||||
elif source == "custom":
|
||||
specs = _get_custom_command_specs()
|
||||
else:
|
||||
return make_response("Unknown system command source: {}".format(source), 404)
|
||||
abort(404)
|
||||
|
||||
return jsonify(_to_client_specs(specs))
|
||||
|
||||
@@ -120,18 +120,15 @@ def executeSystemCommand(source, command):
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
if command == "divider":
|
||||
return make_response("Dividers cannot be executed", 400)
|
||||
abort(400, description="Dividers cannot be executed")
|
||||
|
||||
command_spec = _get_command_spec(source, command)
|
||||
if not command_spec:
|
||||
return make_response("Command {}:{} not found".format(source, command), 404)
|
||||
abort(404)
|
||||
|
||||
if "command" not in command_spec:
|
||||
return make_response(
|
||||
"Command {}:{} does not define a command to execute, can't proceed".format(
|
||||
source, command
|
||||
),
|
||||
500,
|
||||
abort(
|
||||
500, description="Command does not define a command to execute, can't proceed"
|
||||
)
|
||||
|
||||
do_async = command_spec.get("async", False)
|
||||
@@ -145,16 +142,16 @@ def executeSystemCommand(source, command):
|
||||
)
|
||||
)
|
||||
else:
|
||||
logger.info("Performing command for {}:{}".format(source, command))
|
||||
logger.info(f"Performing command for {source}:{command}")
|
||||
|
||||
try:
|
||||
if "before" in command_spec and callable(command_spec["before"]):
|
||||
command_spec["before"]()
|
||||
except Exception as e:
|
||||
if not do_ignore:
|
||||
error = 'Command "before" for {}:{} failed: {}'.format(source, command, e)
|
||||
error = f'Command "before" for {source}:{command} failed: {e}'
|
||||
logger.warning(error)
|
||||
return make_response(error, 500)
|
||||
abort(500, description=error)
|
||||
|
||||
try:
|
||||
|
||||
@@ -191,13 +188,13 @@ def executeSystemCommand(source, command):
|
||||
try:
|
||||
execute()
|
||||
except CommandFailed as exc:
|
||||
return make_response(exc.error, 500)
|
||||
abort(500, exc.error)
|
||||
|
||||
except Exception as e:
|
||||
if not do_ignore:
|
||||
error = "Command for {}:{} failed: {}".format(source, command, e)
|
||||
error = f"Command for {source}:{command} failed: {e}"
|
||||
logger.warning(error)
|
||||
return make_response(error, 500)
|
||||
abort(500, error)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
@@ -300,7 +297,7 @@ def _get_custom_command_specs():
|
||||
action = spec["action"]
|
||||
if action == "divider":
|
||||
dividers += 1
|
||||
action = "divider_{}".format(dividers)
|
||||
action = f"divider_{dividers}"
|
||||
specs[action] = copied
|
||||
return specs
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import logging
|
||||
import os
|
||||
import threading
|
||||
|
||||
from flask import jsonify, make_response, request, url_for
|
||||
from flask import abort, jsonify, request, url_for
|
||||
|
||||
import octoprint.timelapse
|
||||
import octoprint.util as util
|
||||
@@ -177,9 +177,9 @@ def deleteTimelapse(filename):
|
||||
os.remove(full_path)
|
||||
except Exception as ex:
|
||||
logging.getLogger(__file__).exception(
|
||||
"Error deleting timelapse file {}".format(full_path)
|
||||
f"Error deleting timelapse file {full_path}"
|
||||
)
|
||||
return make_response("Unexpected error: {}".format(ex), 500)
|
||||
abort(500, description=f"Unexpected error: {ex}")
|
||||
|
||||
return getTimelapseData()
|
||||
|
||||
@@ -205,8 +205,8 @@ def processUnrenderedTimelapseCommand(name):
|
||||
|
||||
if command == "render":
|
||||
if printer.is_printing() or printer.is_paused():
|
||||
return make_response(
|
||||
"Printer is currently printing, cannot render timelapse", 409
|
||||
abort(
|
||||
409, description="Printer is currently printing, cannot render timelapse"
|
||||
)
|
||||
octoprint.timelapse.render_unrendered_timelapse(name)
|
||||
|
||||
@@ -228,68 +228,56 @@ def setTimelapseConfig():
|
||||
try:
|
||||
postRoll = int(data["postRoll"])
|
||||
except ValueError:
|
||||
return make_response(
|
||||
"Invalid value for postRoll: %r" % data["postRoll"], 400
|
||||
)
|
||||
abort(400, description="postRoll is invalid")
|
||||
else:
|
||||
if postRoll >= 0:
|
||||
config["postRoll"] = postRoll
|
||||
else:
|
||||
return make_response("Invalid value for postRoll: %d" % postRoll, 400)
|
||||
abort(400, description="postRoll is invalid")
|
||||
|
||||
if "fps" in data:
|
||||
try:
|
||||
fps = int(data["fps"])
|
||||
except ValueError:
|
||||
return make_response("Invalid value for fps: %r" % data["fps"], 400)
|
||||
abort(400, description="fps is invalid")
|
||||
else:
|
||||
if fps > 0:
|
||||
config["fps"] = fps
|
||||
else:
|
||||
return make_response("Invalid value for fps: %d" % fps, 400)
|
||||
abort(400, description="fps is invalid")
|
||||
|
||||
if "interval" in data:
|
||||
try:
|
||||
interval = int(data["interval"])
|
||||
except ValueError:
|
||||
return make_response(
|
||||
"Invalid value for interval: %r" % data["interval"], 400
|
||||
)
|
||||
abort(400, description="interval is invalid")
|
||||
else:
|
||||
if interval > 0:
|
||||
config["options"]["interval"] = interval
|
||||
else:
|
||||
return make_response("Invalid value for interval: %d" % interval, 400)
|
||||
abort(400, description="interval is invalid")
|
||||
|
||||
if "retractionZHop" in data:
|
||||
try:
|
||||
retractionZHop = float(data["retractionZHop"])
|
||||
except ValueError:
|
||||
return make_response(
|
||||
"Invalid value for retraction Z-Hop: %r" % data["retractionZHop"], 400
|
||||
)
|
||||
abort(400, description="retractionZHop is invalid")
|
||||
else:
|
||||
if retractionZHop >= 0:
|
||||
config["options"]["retractionZHop"] = retractionZHop
|
||||
else:
|
||||
return make_response(
|
||||
"Invalid value for retraction Z-Hop: %f" % retractionZHop, 400
|
||||
)
|
||||
abort(400, description="retractionZHop is invalid")
|
||||
|
||||
if "minDelay" in data:
|
||||
try:
|
||||
minDelay = float(data["minDelay"])
|
||||
except ValueError:
|
||||
return make_response(
|
||||
"Invalid value for minimum delay: %r" % data["minDelay"], 400
|
||||
)
|
||||
abort(400, description="minDelay is invalid")
|
||||
else:
|
||||
if minDelay > 0:
|
||||
config["options"]["minDelay"] = minDelay
|
||||
else:
|
||||
return make_response(
|
||||
"Invalid value for minimum delay: %f" % minDelay, 400
|
||||
)
|
||||
abort(400, description="minDelay is invalid")
|
||||
|
||||
if (
|
||||
admin_permission.can()
|
||||
|
||||
@@ -44,7 +44,7 @@ def loginFromApiKeyRequestHandler():
|
||||
if loginUserFromApiKey():
|
||||
_flask.g.login_via_apikey = True
|
||||
except InvalidApiKeyException:
|
||||
return _flask.make_response("Invalid API key", 403)
|
||||
_flask.abort(403)
|
||||
|
||||
|
||||
def loginFromAuthorizationHeaderRequestHandler():
|
||||
@@ -55,7 +55,7 @@ def loginFromAuthorizationHeaderRequestHandler():
|
||||
if loginUserFromAuthorizationHeader():
|
||||
_flask.g.login_via_header = True
|
||||
except InvalidApiKeyException:
|
||||
return _flask.make_response("Invalid API key", 403)
|
||||
_flask.abort(403)
|
||||
|
||||
|
||||
class InvalidApiKeyException(Exception):
|
||||
@@ -117,7 +117,7 @@ def requireLoginRequestHandler():
|
||||
|
||||
user = flask_login.current_user
|
||||
if user is None or user.is_anonymous or not user.is_active:
|
||||
return flask.make_response("Forbidden", 403)
|
||||
_flask.abort(403)
|
||||
|
||||
|
||||
def corsRequestHandler():
|
||||
@@ -318,7 +318,7 @@ def get_authorization_header(request):
|
||||
def get_plugin_hash():
|
||||
from octoprint.plugin import plugin_manager
|
||||
|
||||
plugin_signature = lambda impl: "{}:{}".format(impl._identifier, impl._plugin_version)
|
||||
plugin_signature = lambda impl: f"{impl._identifier}:{impl._plugin_version}"
|
||||
template_plugins = list(
|
||||
map(
|
||||
plugin_signature,
|
||||
|
||||
@@ -5,7 +5,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import functools
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
@@ -151,9 +150,7 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
|
||||
)
|
||||
break
|
||||
else:
|
||||
logger.debug(
|
||||
"No translations for locale {} in core folders".format(locale)
|
||||
)
|
||||
logger.debug(f"No translations for locale {locale} in core folders")
|
||||
translations = translations.merge(core_translations)
|
||||
|
||||
ctx.babel_translations = translations
|
||||
@@ -215,7 +212,7 @@ def fix_webassets_cache():
|
||||
|
||||
filename = os.path.join(self.directory, "%s" % hash)
|
||||
try:
|
||||
f = io.open(filename, "rb")
|
||||
f = open(filename, "rb")
|
||||
except OSError as e:
|
||||
if e.errno != errno.ENOENT:
|
||||
error_logger.exception(
|
||||
@@ -615,7 +612,7 @@ def _local_networks():
|
||||
continue
|
||||
|
||||
local_networks.add(network)
|
||||
logger.debug("Added network {} to localNetworks".format(network))
|
||||
logger.debug(f"Added network {network} to localNetworks")
|
||||
|
||||
if network.version == 4:
|
||||
network_v6 = network.ipv6()
|
||||
@@ -664,9 +661,7 @@ def passive_login():
|
||||
def determine_user(u):
|
||||
if not u.is_anonymous and u.is_active:
|
||||
# known active user
|
||||
logger.info(
|
||||
"Passively logging in user {} from {}".format(u.get_id(), remote_address)
|
||||
)
|
||||
logger.info(f"Passively logging in user {u.get_id()} from {remote_address}")
|
||||
|
||||
elif (
|
||||
settings().getBoolean(["accessControl", "autologinLocal"])
|
||||
@@ -998,9 +993,7 @@ class PreemptiveCache:
|
||||
entries = cleanup_function(root, entries)
|
||||
if not entries:
|
||||
del all_data[root]
|
||||
self._logger.debug(
|
||||
"Removed root {} from preemptive cache".format(root)
|
||||
)
|
||||
self._logger.debug(f"Removed root {root} from preemptive cache")
|
||||
elif len(entries) < old_count:
|
||||
all_data[root] = entries
|
||||
self._logger.debug(
|
||||
@@ -1018,7 +1011,7 @@ class PreemptiveCache:
|
||||
cache_data = None
|
||||
with self._lock:
|
||||
try:
|
||||
with io.open(self.cachefile, "rt") as f:
|
||||
with open(self.cachefile) as f:
|
||||
cache_data = yaml.safe_load(f)
|
||||
except OSError as e:
|
||||
import errno
|
||||
@@ -1026,7 +1019,7 @@ class PreemptiveCache:
|
||||
if e.errno != errno.ENOENT:
|
||||
raise
|
||||
except Exception:
|
||||
self._logger.exception("Error while reading {}".format(self.cachefile))
|
||||
self._logger.exception(f"Error while reading {self.cachefile}")
|
||||
|
||||
if cache_data is None:
|
||||
cache_data = {}
|
||||
@@ -1057,7 +1050,7 @@ class PreemptiveCache:
|
||||
allow_unicode=True,
|
||||
)
|
||||
except Exception:
|
||||
self._logger.exception("Error while writing {}".format(self.cachefile))
|
||||
self._logger.exception(f"Error while writing {self.cachefile}")
|
||||
|
||||
def set_data(self, root, data):
|
||||
with self._lock:
|
||||
@@ -1106,12 +1099,12 @@ class PreemptiveCache:
|
||||
to_persist = copy.deepcopy(data)
|
||||
to_persist["_timestamp"] = time.time()
|
||||
to_persist["_count"] = 1
|
||||
self._logger.info("Adding entry for {} and {!r}".format(root, to_persist))
|
||||
self._logger.info(f"Adding entry for {root} and {to_persist!r}")
|
||||
else:
|
||||
to_persist["_timestamp"] = time.time()
|
||||
to_persist["_count"] = to_persist.get("_count", 0) + 1
|
||||
self._logger.debug(
|
||||
"Updating timestamp and counter for {} and {!r}".format(root, data)
|
||||
f"Updating timestamp and counter for {root} and {data!r}"
|
||||
)
|
||||
|
||||
self.set_data(root, [to_persist] + other)
|
||||
@@ -1150,7 +1143,7 @@ def preemptively_cached(cache, data, unless=None):
|
||||
cache.record(data, unless=unless)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception(
|
||||
"Error while recording preemptive cache entry: {!r}".format(data)
|
||||
f"Error while recording preemptive cache entry: {data!r}"
|
||||
)
|
||||
return f(*args, **kwargs)
|
||||
|
||||
@@ -1297,11 +1290,13 @@ def with_revalidation_checking(
|
||||
def decorator(f):
|
||||
@functools.wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
from octoprint.server import NOT_MODIFIED
|
||||
|
||||
lm = lastmodified_factory()
|
||||
etag = etag_factory(lm)
|
||||
|
||||
if condition(lm, etag) and not unless():
|
||||
return make_response("Not Modified", 304)
|
||||
return NOT_MODIFIED
|
||||
|
||||
# generate response
|
||||
response = f(*args, **kwargs)
|
||||
@@ -1539,7 +1534,7 @@ def no_firstrun_access(func):
|
||||
octoprint.server.userManager is None
|
||||
or not octoprint.server.userManager.has_been_customized()
|
||||
):
|
||||
return flask.make_response("OctoPrint isn't setup yet", 403)
|
||||
flask.abort(403)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return decorated_view
|
||||
@@ -1561,9 +1556,7 @@ def firstrun_only_access(func):
|
||||
):
|
||||
return func(*args, **kwargs)
|
||||
else:
|
||||
return flask.make_response(
|
||||
"OctoPrint is already setup, this resource is not longer available.", 403
|
||||
)
|
||||
flask.abort(403)
|
||||
|
||||
return decorated_view
|
||||
|
||||
@@ -1578,34 +1571,56 @@ def get_remote_address(request):
|
||||
def get_json_command_from_request(request, valid_commands):
|
||||
content_type = request.headers.get("Content-Type", None)
|
||||
if content_type is None or "application/json" not in content_type:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
flask.abort(400, description="Expected content-type JSON")
|
||||
|
||||
data = request.get_json()
|
||||
if data is None:
|
||||
return (
|
||||
None,
|
||||
None,
|
||||
make_response("Malformed JSON body or wrong content-type in request", 400),
|
||||
flask.abort(
|
||||
400, description="Malformed JSON body or wrong content-type in request"
|
||||
)
|
||||
if "command" not in data or data["command"] not in valid_commands:
|
||||
return None, None, make_response("Expected valid command", 400)
|
||||
flask.abort(400, description="command is invalid")
|
||||
|
||||
command = data["command"]
|
||||
for parameter in valid_commands[command]:
|
||||
if parameter not in data:
|
||||
return (
|
||||
None,
|
||||
None,
|
||||
make_response(
|
||||
"Mandatory parameter %s missing for command %s"
|
||||
% (parameter, command),
|
||||
400,
|
||||
),
|
||||
)
|
||||
if any(map(lambda x: x not in data, valid_commands[command])):
|
||||
flask.abort(400, description="Mandatory parameters missing")
|
||||
|
||||
return command, data, None
|
||||
|
||||
|
||||
def make_text_response(message, status):
|
||||
"""
|
||||
Helper to generate basic text responses.
|
||||
|
||||
Response will have the provided message as body, the provided status code, and
|
||||
a content type of "text/plain".
|
||||
|
||||
Args:
|
||||
message: The message in the response body
|
||||
status: The HTTP status code
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
return make_response(message, status, {"Content-Type": "text/plain"})
|
||||
|
||||
|
||||
def make_api_error(message, status):
|
||||
"""
|
||||
Helper to generate API error responses in JSON format.
|
||||
|
||||
Turns something like ``make_api_error("Not Found", 404)`` into a JSON response
|
||||
with body ``{"error": "Not Found"}``.
|
||||
|
||||
Args:
|
||||
message: The error message to put into the response
|
||||
status: The HTTP status code
|
||||
|
||||
Returns: a flask response to return to the client
|
||||
"""
|
||||
return make_response(flask.jsonify(error=message), status)
|
||||
|
||||
|
||||
##~~ Flask-Assets resolver with plugin asset support
|
||||
|
||||
|
||||
|
||||
@@ -173,9 +173,9 @@ class PrinterStateConnection(
|
||||
|
||||
def __str__(self):
|
||||
if self._remoteAddress:
|
||||
return "{!r} connected to {}".format(self, self._remoteAddress)
|
||||
return f"{self!r} connected to {self._remoteAddress}"
|
||||
else:
|
||||
return "Unconnected {!r}".format(self)
|
||||
return f"Unconnected {self!r}"
|
||||
|
||||
def on_open(self, info):
|
||||
self._pluginManager.register_message_receiver(self.on_plugin_message)
|
||||
@@ -279,7 +279,7 @@ class PrinterStateConnection(
|
||||
self._on_login(user)
|
||||
else:
|
||||
self._logger.warning(
|
||||
"Unknown user/session combo: {}:{}".format(user_id, user_session)
|
||||
f"Unknown user/session combo: {user_id}:{user_session}"
|
||||
)
|
||||
self._on_logout()
|
||||
|
||||
@@ -437,9 +437,7 @@ class PrinterStateConnection(
|
||||
and hasattr(self._user, "session")
|
||||
and user.session == self._user.session
|
||||
):
|
||||
self._logger.info(
|
||||
"User {} logged out, logging out on socket".format(user.get_id())
|
||||
)
|
||||
self._logger.info(f"User {user.get_id()} logged out, logging out on socket")
|
||||
self._on_logout()
|
||||
|
||||
if stale:
|
||||
@@ -453,7 +451,7 @@ class PrinterStateConnection(
|
||||
|
||||
def on_user_removed(self, userid):
|
||||
if self._user.get_id() == userid:
|
||||
self._logger.info("User {} deleted, logging out on socket".format(userid))
|
||||
self._logger.info(f"User {userid} deleted, logging out on socket")
|
||||
self._on_logout()
|
||||
self._sendReauthRequired("removed")
|
||||
|
||||
@@ -477,7 +475,7 @@ class PrinterStateConnection(
|
||||
proceed = proceed and hook(self, self._user)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error processing register hook handler for plugin {}".format(name),
|
||||
f"Error processing register hook handler for plugin {name}",
|
||||
extra={"plugin": name},
|
||||
)
|
||||
|
||||
@@ -542,7 +540,7 @@ class PrinterStateConnection(
|
||||
proceed = proceed and hook(self, self._user, type, payload)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error processing emit hook handler from plugin {}".format(name),
|
||||
f"Error processing emit hook handler from plugin {name}",
|
||||
extra={"plugin": name},
|
||||
)
|
||||
|
||||
@@ -585,7 +583,7 @@ class PrinterStateConnection(
|
||||
except Exception as e:
|
||||
if self._logger.isEnabledFor(logging.DEBUG):
|
||||
self._logger.exception(
|
||||
"Could not send message to client {}".format(self._remoteAddress)
|
||||
f"Could not send message to client {self._remoteAddress}"
|
||||
)
|
||||
else:
|
||||
self._logger.warning(
|
||||
@@ -608,7 +606,7 @@ class PrinterStateConnection(
|
||||
hook(self, self._user)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error processing authed hook handler for plugin {}".format(name),
|
||||
f"Error processing authed hook handler for plugin {name}",
|
||||
extra={"plugin": name},
|
||||
)
|
||||
|
||||
@@ -641,6 +639,6 @@ class PrinterStateConnection(
|
||||
hook(self, self._user)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error processing authed hook handler for plugin {}".format(name),
|
||||
f"Error processing authed hook handler for plugin {name}",
|
||||
extra={"plugin": name},
|
||||
)
|
||||
@@ -1181,9 +1181,13 @@ class LargeResponseHandler(
|
||||
|
||||
def compute_etag(self):
|
||||
if self._etag_generator is not None:
|
||||
return self._etag_generator(self)
|
||||
etag = self._etag_generator(self)
|
||||
else:
|
||||
return self.get_content_version(self.absolute_path)
|
||||
etag = str(self.get_content_version(self.absolute_path))
|
||||
|
||||
if not etag.endswith('"'):
|
||||
etag = f'"{etag}"'
|
||||
return etag
|
||||
|
||||
# noinspection PyAttributeOutsideInit
|
||||
def get_content_type(self):
|
||||
@@ -1326,7 +1330,7 @@ class UrlProxyHandler(
|
||||
if not extension:
|
||||
return None
|
||||
|
||||
return "%s%s" % (self._basename, extension)
|
||||
return f"{self._basename}{extension}"
|
||||
|
||||
|
||||
class StaticDataHandler(
|
||||
@@ -1369,7 +1373,7 @@ class DeprecatedEndpointHandler(CorsSupportMixin, tornado.web.RequestHandler):
|
||||
def _handle_method(self, *args, **kwargs):
|
||||
to_url = self._url.format(*args)
|
||||
self._logger.info(
|
||||
"Redirecting deprecated endpoint {} to {}".format(self.request.path, to_url)
|
||||
f"Redirecting deprecated endpoint {self.request.path} to {to_url}"
|
||||
)
|
||||
self.redirect(to_url, permanent=True)
|
||||
|
||||
@@ -1427,7 +1431,7 @@ class StaticZipBundleHandler(CorsSupportMixin, tornado.web.RequestHandler):
|
||||
if self._as_attachment:
|
||||
self.set_header(
|
||||
"Content-Disposition",
|
||||
'attachment; filename="{}"'.format(self.get_attachment_name()),
|
||||
f'attachment; filename="{self.get_attachment_name()}"',
|
||||
)
|
||||
|
||||
import zipstream
|
||||
@@ -1572,7 +1576,7 @@ class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler):
|
||||
self.set_header("Content-Type", "application/zip")
|
||||
self.set_header(
|
||||
"Content-Disposition",
|
||||
'attachment; filename="{}"'.format(get_systeminfo_bundle_name()),
|
||||
f'attachment; filename="{get_systeminfo_bundle_name()}"',
|
||||
)
|
||||
|
||||
for chunk in z:
|
||||
|
||||
@@ -57,7 +57,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
if not self._valid_path(path):
|
||||
continue
|
||||
|
||||
self._logger.info("Found {}, trying to add it".format(path))
|
||||
self._logger.info(f"Found {path}, trying to add it")
|
||||
self._upload(path)
|
||||
self._logger.info("... initial scan done.")
|
||||
|
||||
@@ -147,7 +147,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
# file is still there - that should only happen if something went wrong, so mark it as failed
|
||||
# noinspection PyBroadException
|
||||
try:
|
||||
shutil.move(path, "{}.failed".format(path))
|
||||
shutil.move(path, f"{path}.failed")
|
||||
except Exception:
|
||||
# something went really wrong here.... but we can't do anything about it, so just log it
|
||||
self._logger.exception(
|
||||
@@ -190,7 +190,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
last_size = new_size
|
||||
time.sleep(interval)
|
||||
|
||||
self._logger.debug("File at {} is stable, moving it".format(path))
|
||||
self._logger.debug(f"File at {path} is stable, moving it")
|
||||
self._upload(path)
|
||||
|
||||
def _valid_path(self, path):
|
||||
|
||||
@@ -4,7 +4,6 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
|
||||
import base64
|
||||
import datetime
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
@@ -104,7 +103,7 @@ def _preemptive_data(
|
||||
d.update(data)
|
||||
except Exception:
|
||||
_logger.exception(
|
||||
"Error collecting data for preemptive cache from plugin {}".format(key)
|
||||
f"Error collecting data for preemptive cache from plugin {key}"
|
||||
)
|
||||
|
||||
# add additional request data if we have any
|
||||
@@ -129,7 +128,7 @@ def _cache_key(ui, url=None, locale=None, additional_key_data=None):
|
||||
if locale is None:
|
||||
locale = g.locale.language if g.locale else "en"
|
||||
|
||||
k = "ui:{}:{}:{}".format(ui, url, locale)
|
||||
k = f"ui:{ui}:{url}:{locale}"
|
||||
if callable(additional_key_data):
|
||||
try:
|
||||
ak = additional_key_data()
|
||||
@@ -160,7 +159,7 @@ def _add_additional_assets(hook):
|
||||
result += assets
|
||||
except Exception:
|
||||
_logger.exception(
|
||||
"Error fetching theming CSS to include from plugin {}".format(name),
|
||||
f"Error fetching theming CSS to include from plugin {name}",
|
||||
extra={"plugin": name},
|
||||
)
|
||||
return result
|
||||
@@ -273,7 +272,7 @@ def in_cache():
|
||||
break
|
||||
except Exception:
|
||||
_logger.exception(
|
||||
"Error while calling plugin {}, skipping it".format(plugin._identifier),
|
||||
f"Error while calling plugin {plugin._identifier}, skipping it",
|
||||
extra={"plugin": plugin._identifier},
|
||||
)
|
||||
else:
|
||||
@@ -297,9 +296,7 @@ def in_cache():
|
||||
)
|
||||
return response
|
||||
elif util.flask.is_in_cache(key):
|
||||
_logger.info(
|
||||
"Found path {} in cache (key: {}), signaling as cached".format(path, key)
|
||||
)
|
||||
_logger.info(f"Found path {path} in cache (key: {key}), signaling as cached")
|
||||
return response
|
||||
elif util.flask.is_cache_bypassed(key):
|
||||
_logger.info(
|
||||
@@ -309,9 +306,7 @@ def in_cache():
|
||||
)
|
||||
return response
|
||||
else:
|
||||
_logger.debug(
|
||||
"Path {} not yet cached (key: {}), signaling as missing".format(path, key)
|
||||
)
|
||||
_logger.debug(f"Path {path} not yet cached (key: {key}), signaling as missing")
|
||||
return abort(404)
|
||||
|
||||
|
||||
@@ -619,7 +614,7 @@ def index():
|
||||
|
||||
if forced_view:
|
||||
# we have view forced by the preemptive cache
|
||||
_logger.debug("Forcing rendering of view {}".format(forced_view))
|
||||
_logger.debug(f"Forcing rendering of view {forced_view}")
|
||||
if forced_view != "_default":
|
||||
plugin = pluginManager.get_plugin_info(forced_view, require_enabled=True)
|
||||
if plugin is not None and isinstance(
|
||||
@@ -706,7 +701,7 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
|
||||
|
||||
permissions = [permission.as_dict() for permission in Permissions.all()]
|
||||
filetypes = list(sorted(full_extension_tree().keys()))
|
||||
extensions = list(map(lambda ext: ".{}".format(ext), get_all_extensions()))
|
||||
extensions = list(map(lambda ext: f".{ext}", get_all_extensions()))
|
||||
|
||||
# ~~ prepare full set of template vars for rendering
|
||||
|
||||
@@ -1684,7 +1679,7 @@ def _get_translations(locale, domain):
|
||||
|
||||
def messages_from_po(path, locale, domain):
|
||||
messages = {}
|
||||
with io.open(path, mode="rt", encoding="utf-8") as f:
|
||||
with open(path, mode="rt", encoding="utf-8") as f:
|
||||
catalog = read_po(f, locale=locale, domain=domain)
|
||||
|
||||
for message in catalog:
|
||||
|
||||
+15
-17
@@ -22,7 +22,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import copy
|
||||
import fnmatch
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
@@ -257,6 +256,7 @@ default_settings = {
|
||||
"throttle_highprio": 0.0,
|
||||
"throttle_lines": 100,
|
||||
"runAt": "idle", # 'never', 'idle', 'always'
|
||||
"bedZ": 0.0,
|
||||
},
|
||||
"feature": {
|
||||
"temperatureGraph": True,
|
||||
@@ -410,7 +410,7 @@ default_settings = {
|
||||
"terminalFilters": [
|
||||
{
|
||||
"name": "Suppress temperature messages",
|
||||
"regex": r"(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+((P|B|N)\d+\s+)*)?(B|T\d*):\d+)",
|
||||
"regex": r"(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+([PBN]\d+\s+)*)?([BCLPR]|T\d*):-?\d+)",
|
||||
},
|
||||
{
|
||||
"name": "Suppress SD status messages",
|
||||
@@ -988,7 +988,7 @@ class Settings:
|
||||
|
||||
def load(self, migrate=False):
|
||||
if os.path.exists(self._configfile) and os.path.isfile(self._configfile):
|
||||
with io.open(self._configfile, "rt", encoding="utf-8", errors="replace") as f:
|
||||
with open(self._configfile, encoding="utf-8", errors="replace") as f:
|
||||
try:
|
||||
self._config = yaml.safe_load(f)
|
||||
self._mtime = self.last_modified
|
||||
@@ -1029,11 +1029,9 @@ class Settings:
|
||||
try:
|
||||
overlay_config = self.load_overlay(path, migrate=migrate)
|
||||
self.add_overlay(overlay_config)
|
||||
self._logger.info("Added config overlay from {}".format(path))
|
||||
self._logger.info(f"Added config overlay from {path}")
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Could not add config overlay from {}".format(path)
|
||||
)
|
||||
self._logger.exception(f"Could not add config overlay from {path}")
|
||||
|
||||
if os.path.isfile(overlay):
|
||||
process(overlay)
|
||||
@@ -1060,7 +1058,7 @@ class Settings:
|
||||
|
||||
if isinstance(overlay, str):
|
||||
if os.path.exists(overlay) and os.path.isfile(overlay):
|
||||
with io.open(overlay, "rt", encoding="utf-8", errors="replace") as f:
|
||||
with open(overlay, encoding="utf-8", errors="replace") as f:
|
||||
config = yaml.safe_load(f)
|
||||
elif isinstance(overlay, dict):
|
||||
config = overlay
|
||||
@@ -1071,7 +1069,7 @@ class Settings:
|
||||
|
||||
if not isinstance(config, dict):
|
||||
raise ValueError(
|
||||
"Configuration data must be a dict but is a {}".format(config.__class__)
|
||||
f"Configuration data must be a dict but is a {config.__class__}"
|
||||
)
|
||||
|
||||
if migrate:
|
||||
@@ -2393,7 +2391,7 @@ class Settings:
|
||||
preprocessors=None,
|
||||
error_on_path=False,
|
||||
*args,
|
||||
**kwargs
|
||||
**kwargs,
|
||||
):
|
||||
if not path:
|
||||
if error_on_path:
|
||||
@@ -2665,7 +2663,7 @@ class SubSettings:
|
||||
if item in self.deprecated_access_methods:
|
||||
new = self.deprecated_access_methods[item]
|
||||
decorator = deprecated(
|
||||
"{old} has been renamed to {new}".format(old=item, new=new),
|
||||
f"{item} has been renamed to {new}",
|
||||
stacklevel=2,
|
||||
)
|
||||
item = new
|
||||
@@ -2725,7 +2723,7 @@ def _validate_folder(
|
||||
if not os.path.exists(folder):
|
||||
if os.path.islink(folder):
|
||||
# broken symlink, see #2644
|
||||
raise OSError("Folder at {} appears to be a broken symlink".format(folder))
|
||||
raise OSError(f"Folder at {folder} appears to be a broken symlink")
|
||||
|
||||
elif create:
|
||||
# non existing, but we are allowed to create it
|
||||
@@ -2733,7 +2731,7 @@ def _validate_folder(
|
||||
os.makedirs(folder)
|
||||
except Exception:
|
||||
if log_error:
|
||||
logger.exception("Could not create {}".format(folder))
|
||||
logger.exception(f"Could not create {folder}")
|
||||
raise OSError(
|
||||
"Folder for type {} at {} does not exist and creation failed".format(
|
||||
type, folder
|
||||
@@ -2742,11 +2740,11 @@ def _validate_folder(
|
||||
|
||||
else:
|
||||
# not extisting, not allowed to create it
|
||||
raise OSError("No such folder: {}".format(folder))
|
||||
raise OSError(f"No such folder: {folder}")
|
||||
|
||||
elif os.path.isfile(folder):
|
||||
# hardening against misconfiguration, see #1953
|
||||
raise OSError("Expected a folder at {} but found a file instead".format(folder))
|
||||
raise OSError(f"Expected a folder at {folder} but found a file instead")
|
||||
|
||||
elif check_writable:
|
||||
# make sure we can also write into the folder
|
||||
@@ -2761,10 +2759,10 @@ def _validate_folder(
|
||||
# to determine whether things are *actually* writable
|
||||
testfile = os.path.join(folder, ".testballoon.txt")
|
||||
try:
|
||||
with io.open(testfile, "wt", encoding="utf-8") as f:
|
||||
with open(testfile, "wt", encoding="utf-8") as f:
|
||||
f.write("test")
|
||||
os.remove(testfile)
|
||||
except Exception:
|
||||
if log_error:
|
||||
logger.exception("Could not write test file to {}".format(folder))
|
||||
logger.exception(f"Could not write test file to {folder}")
|
||||
raise OSError(error)
|
||||
@@ -724,9 +724,7 @@ class SlicingManager:
|
||||
|
||||
name = self._sanitize(name)
|
||||
|
||||
path = os.path.join(
|
||||
self.get_slicer_profile_path(slicer), "{name}.profile".format(name=name)
|
||||
)
|
||||
path = os.path.join(self.get_slicer_profile_path(slicer), f"{name}.profile")
|
||||
if not os.path.realpath(path).startswith(os.path.realpath(self._profile_path)):
|
||||
raise OSError(
|
||||
"Path to profile {name} tried to break out of allows sub path".format(
|
||||
|
||||
@@ -67,7 +67,7 @@ class SlicerNotConfigured(SlicerException):
|
||||
|
||||
def __init__(self, slicer, *args, **kwargs):
|
||||
SlicerException.__init__(self, slicer, *args, **kwargs)
|
||||
self.message = "Slicer not configured: {slicer}".format(slicer=slicer)
|
||||
self.message = f"Slicer not configured: {slicer}"
|
||||
|
||||
|
||||
class UnknownSlicer(SlicerException):
|
||||
@@ -77,7 +77,7 @@ class UnknownSlicer(SlicerException):
|
||||
|
||||
def __init__(self, slicer, *args, **kwargs):
|
||||
SlicerException.__init__(self, slicer, *args, **kwargs)
|
||||
self.message = "No such slicer: {slicer}".format(slicer=slicer)
|
||||
self.message = f"No such slicer: {slicer}"
|
||||
|
||||
|
||||
class ProfileException(Exception):
|
||||
|
||||
@@ -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
|
||||
@@ -410,7 +410,8 @@ $(function () {
|
||||
self.addTerminalFilter = function () {
|
||||
self.terminalFilters.push({
|
||||
name: "New",
|
||||
regex: "(Send:\\s+(N\\d+\\s+)?M105)|(Recv:\\s+(ok\\s+)?.*(B|T\\d*):\\d+)"
|
||||
regex:
|
||||
"(Send:\\s+(N\\d+\\s+)?M105)|(Recv:\\s+(ok\\s+([PBN]\\d+\\s+)*)?.*([BCLPR]|T\\d*):-?\\d+)"
|
||||
});
|
||||
};
|
||||
|
||||
@@ -774,7 +775,7 @@ $(function () {
|
||||
$(".reload_nonconflicts", self.settingsUpdatedDialog).click(function (e) {
|
||||
e.preventDefault();
|
||||
self.settingsUpdatedDialog.modal("hide");
|
||||
self.requestData(undefined, true);
|
||||
self.requestData(true);
|
||||
return false;
|
||||
});
|
||||
|
||||
@@ -843,14 +844,14 @@ $(function () {
|
||||
self.requestData = function (local) {
|
||||
// handle old parameter format
|
||||
var callback = undefined;
|
||||
if (arguments.length == 2 || _.isFunction(local)) {
|
||||
if (arguments.length === 2 || _.isFunction(local)) {
|
||||
var exc = new Error();
|
||||
log.warn(
|
||||
"The callback parameter of SettingsViewModel.requestData is deprecated, the method now returns a promise, please use that instead. Stacktrace:",
|
||||
exc.stack || exc.stacktrace || "<n/a>"
|
||||
);
|
||||
|
||||
if (arguments.length == 2) {
|
||||
if (arguments.length === 2) {
|
||||
callback = arguments[0];
|
||||
local = arguments[1];
|
||||
} else {
|
||||
|
||||
+17
-24
@@ -5,7 +5,6 @@ import collections
|
||||
import datetime
|
||||
import fnmatch
|
||||
import glob
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import queue
|
||||
@@ -201,7 +200,7 @@ def delete_unrendered_timelapse(name):
|
||||
except Exception:
|
||||
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
|
||||
logging.getLogger(__name__).exception(
|
||||
"Error while processing file {} during cleanup".format(entry.name)
|
||||
f"Error while processing file {entry.name} during cleanup"
|
||||
)
|
||||
|
||||
|
||||
@@ -259,14 +258,12 @@ def delete_old_unrendered_timelapses():
|
||||
except Exception:
|
||||
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
|
||||
logging.getLogger(__name__).exception(
|
||||
"Error while processing file {} during cleanup".format(entry.name)
|
||||
f"Error while processing file {entry.name} during cleanup"
|
||||
)
|
||||
|
||||
for prefix in prefixes_to_clean:
|
||||
delete_unrendered_timelapse(prefix)
|
||||
logging.getLogger(__name__).info(
|
||||
"Deleted old unrendered timelapse {}".format(prefix)
|
||||
)
|
||||
logging.getLogger(__name__).info(f"Deleted old unrendered timelapse {prefix}")
|
||||
|
||||
|
||||
def _create_render_start_handler(name, gcode=None):
|
||||
@@ -682,7 +679,7 @@ class Timelapse:
|
||||
)
|
||||
self._image_number += 1
|
||||
|
||||
self._logger.debug("Capturing image to {}".format(filename))
|
||||
self._logger.debug(f"Capturing image to {filename}")
|
||||
entry = {
|
||||
"type": self.__class__.QUEUE_ENTRY_TYPE_CAPTURE,
|
||||
"filename": filename,
|
||||
@@ -728,9 +725,7 @@ class Timelapse:
|
||||
|
||||
eventManager().fire(Events.CAPTURE_START, {"file": filename})
|
||||
try:
|
||||
self._logger.debug(
|
||||
"Going to capture {} from {}".format(filename, self._snapshot_url)
|
||||
)
|
||||
self._logger.debug(f"Going to capture {filename} from {self._snapshot_url}")
|
||||
r = requests.get(
|
||||
self._snapshot_url,
|
||||
stream=True,
|
||||
@@ -739,18 +734,16 @@ class Timelapse:
|
||||
)
|
||||
r.raise_for_status()
|
||||
|
||||
with io.open(filename, "wb") as f:
|
||||
with open(filename, "wb") as f:
|
||||
for chunk in r.iter_content(chunk_size=1024):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
f.flush()
|
||||
|
||||
self._logger.debug(
|
||||
"Image {} captured from {}".format(filename, self._snapshot_url)
|
||||
)
|
||||
self._logger.debug(f"Image {filename} captured from {self._snapshot_url}")
|
||||
except Exception as e:
|
||||
self._logger.exception(
|
||||
"Could not capture image {} from {}".format(filename, self._snapshot_url)
|
||||
f"Could not capture image {filename} from {self._snapshot_url}"
|
||||
)
|
||||
self._capture_errors += 1
|
||||
err = e
|
||||
@@ -993,7 +986,7 @@ class TimelapseRenderJob:
|
||||
postfix=self._postfix if self._postfix is not None else "",
|
||||
extension=extension,
|
||||
)
|
||||
temporary = os.path.join(self._output_dir, ".{}".format(output_name))
|
||||
temporary = os.path.join(self._output_dir, f".{output_name}")
|
||||
output = os.path.join(self._output_dir, output_name)
|
||||
|
||||
for i in range(4):
|
||||
@@ -1034,7 +1027,7 @@ class TimelapseRenderJob:
|
||||
rotate=rotate,
|
||||
watermark=watermark,
|
||||
)
|
||||
self._logger.debug("Executing command: {}".format(command_str))
|
||||
self._logger.debug(f"Executing command: {command_str}")
|
||||
|
||||
with self.render_job_lock:
|
||||
try:
|
||||
@@ -1075,7 +1068,7 @@ class TimelapseRenderJob:
|
||||
os.remove(temporary)
|
||||
except Exception:
|
||||
self._logger.warning(
|
||||
"Could not delete temporary timelapse {}".format(temporary)
|
||||
f"Could not delete temporary timelapse {temporary}"
|
||||
)
|
||||
self._notify_callback("always", output)
|
||||
|
||||
@@ -1155,7 +1148,7 @@ class TimelapseRenderJob:
|
||||
"-framerate",
|
||||
str(fps),
|
||||
"-i",
|
||||
'"{}"'.format(input),
|
||||
f'"{input}"',
|
||||
"-vcodec",
|
||||
videocodec,
|
||||
"-threads",
|
||||
@@ -1174,12 +1167,12 @@ class TimelapseRenderJob:
|
||||
)
|
||||
|
||||
if filter_string is not None:
|
||||
logger.debug("Applying videofilter chain: {}".format(filter_string))
|
||||
logger.debug(f"Applying videofilter chain: {filter_string}")
|
||||
command.extend(["-vf", sarge.shell_quote(filter_string)])
|
||||
|
||||
# finalize command with output file
|
||||
logger.debug("Rendering movie to {}".format(output))
|
||||
command.append('"{}"'.format(output))
|
||||
logger.debug(f"Rendering movie to {output}")
|
||||
command.append(f'"{output}"')
|
||||
|
||||
return " ".join(command)
|
||||
|
||||
@@ -1204,7 +1197,7 @@ class TimelapseRenderJob:
|
||||
### See unit tests in test/timelapse/test_timelapse_renderjob.py
|
||||
|
||||
# apply pixel format
|
||||
filters = ["format={}".format(pixfmt)]
|
||||
filters = [f"format={pixfmt}"]
|
||||
|
||||
# flip video if configured
|
||||
if hflip:
|
||||
@@ -1236,7 +1229,7 @@ class TimelapseRenderJob:
|
||||
|
||||
def _notify_callback(self, callback, *args, **kwargs):
|
||||
"""Notifies registered callbacks of type `callback`."""
|
||||
name = "_on_{}".format(callback)
|
||||
name = f"_on_{callback}"
|
||||
method = getattr(self, name, None)
|
||||
if method is not None and callable(method):
|
||||
method(*args, **kwargs)
|
||||
@@ -10,7 +10,6 @@ import collections
|
||||
import contextlib
|
||||
import copy
|
||||
import glob
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import queue
|
||||
@@ -22,10 +21,11 @@ import threading
|
||||
import time
|
||||
import traceback
|
||||
import warnings
|
||||
from collections.abc import Iterable, MutableMapping, Set
|
||||
from functools import wraps
|
||||
from typing import Union
|
||||
|
||||
import frozendict
|
||||
from immutabledict import immutabledict
|
||||
|
||||
from octoprint import UMASK
|
||||
from octoprint.util.connectivity import ConnectivityChecker # noqa: F401
|
||||
@@ -338,9 +338,9 @@ def get_formatted_size(num):
|
||||
|
||||
for x in ["B", "KB", "MB", "GB"]:
|
||||
if num < 1024:
|
||||
return "%3.1f%s" % (num, x)
|
||||
return f"{num:3.1f}{x}"
|
||||
num /= 1024
|
||||
return "%3.1f%s" % (num, "TB")
|
||||
return "{:3.1f}{}".format(num, "TB")
|
||||
|
||||
|
||||
def is_allowed_file(filename, extensions):
|
||||
@@ -975,7 +975,7 @@ def dict_flatten(dictionary, prefix="", separator="."):
|
||||
result = {}
|
||||
for k, v in dictionary.items():
|
||||
key = prefix + separator + k if prefix else k
|
||||
if isinstance(v, collections.MutableMapping):
|
||||
if isinstance(v, MutableMapping):
|
||||
result.update(dict_flatten(v, prefix=key, separator=separator))
|
||||
else:
|
||||
result[key] = v
|
||||
@@ -1119,7 +1119,7 @@ class DefaultOrderedDict(collections.OrderedDict):
|
||||
|
||||
# noinspection PyMethodOverriding
|
||||
def __repr__(self):
|
||||
return "OrderedDefaultDict(%s, %s)" % (
|
||||
return "OrderedDefaultDict({}, {})".format(
|
||||
self.default_factory,
|
||||
collections.OrderedDict.__repr__(self),
|
||||
)
|
||||
@@ -1257,7 +1257,7 @@ else:
|
||||
os.remove(self._path)
|
||||
except Exception as exc:
|
||||
logging.getLogger(__name__).warning(
|
||||
"Could not delete temporary directory {}: {}".format(self.name, exc)
|
||||
f"Could not delete temporary directory {self.name}: {exc}"
|
||||
)
|
||||
|
||||
def __enter__(self):
|
||||
@@ -1283,13 +1283,13 @@ def bom_aware_open(filename, encoding="ascii", mode="r", **kwargs):
|
||||
# these encodings might have a BOM, so let's see if there is one
|
||||
bom = getattr(codecs, potential_bom_attribute)
|
||||
|
||||
with io.open(filename, mode="rb") as f:
|
||||
with open(filename, mode="rb") as f:
|
||||
header = f.read(4)
|
||||
|
||||
if header.startswith(bom):
|
||||
encoding += "-sig"
|
||||
|
||||
return io.open(filename, encoding=encoding, mode=mode, **kwargs)
|
||||
return open(filename, encoding=encoding, mode=mode, **kwargs)
|
||||
|
||||
|
||||
def is_hidden_path(path):
|
||||
@@ -1327,15 +1327,15 @@ glob_escape = deprecated(
|
||||
)(glob.escape)
|
||||
|
||||
|
||||
def thaw_frozendict(obj):
|
||||
if not isinstance(obj, (dict, frozendict.frozendict)):
|
||||
raise ValueError("obj must be a dict or frozendict instance")
|
||||
def thaw_immutabledict(obj):
|
||||
if not isinstance(obj, (dict, immutabledict)):
|
||||
raise ValueError("obj must be a dict or immutabledict instance")
|
||||
|
||||
# only true love can thaw a frozen dict
|
||||
letitgo = {}
|
||||
for key, value in obj.items():
|
||||
if isinstance(value, (dict, frozendict.frozendict)):
|
||||
letitgo[key] = thaw_frozendict(value)
|
||||
if isinstance(value, (dict, immutabledict)):
|
||||
letitgo[key] = thaw_immutabledict(value)
|
||||
else:
|
||||
letitgo[key] = copy.deepcopy(value)
|
||||
return letitgo
|
||||
@@ -1683,7 +1683,6 @@ class CountedEvent:
|
||||
|
||||
class InvariantContainer:
|
||||
def __init__(self, initial_data=None, guarantee_invariant=None):
|
||||
from collections.abc import Iterable
|
||||
from threading import RLock
|
||||
|
||||
if guarantee_invariant is None:
|
||||
@@ -1778,7 +1777,7 @@ class TypedQueue(PrependableQueue):
|
||||
if item_type is not None:
|
||||
if item_type in self._lookup:
|
||||
raise TypeAlreadyInQueue(
|
||||
item_type, "Type {} is already in queue".format(item_type)
|
||||
item_type, f"Type {item_type} is already in queue"
|
||||
)
|
||||
else:
|
||||
self._lookup.add(item_type)
|
||||
@@ -1799,7 +1798,7 @@ class TypedQueue(PrependableQueue):
|
||||
if item_type is not None:
|
||||
if item_type in self._lookup:
|
||||
raise TypeAlreadyInQueue(
|
||||
item_type, "Type {} is already in queue".format(item_type)
|
||||
item_type, f"Type {item_type} is already in queue"
|
||||
)
|
||||
else:
|
||||
self._lookup.add(item_type)
|
||||
@@ -1897,12 +1896,12 @@ class protectedkeydict(collections.MutableMapping):
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
if key in self.protected_keys:
|
||||
raise KeyError("Cannot set protected key {!r}".format(key))
|
||||
raise KeyError(f"Cannot set protected key {key!r}")
|
||||
self.data[key] = value
|
||||
|
||||
def __delitem__(self, key):
|
||||
if key in self.protected_keys:
|
||||
raise KeyError("Cannot delete protected key {!r}".format(key))
|
||||
raise KeyError(f"Cannot delete protected key {key!r}")
|
||||
|
||||
def _get_item(self, key):
|
||||
if key not in self.protected_keys:
|
||||
@@ -1920,7 +1919,7 @@ class protectedkeydict(collections.MutableMapping):
|
||||
return value
|
||||
|
||||
|
||||
class CaseInsensitiveSet(collections.Set):
|
||||
class CaseInsensitiveSet(Set):
|
||||
"""
|
||||
Basic case insensitive set
|
||||
|
||||
@@ -1963,7 +1962,7 @@ def fqfn(f):
|
||||
f.__self__.__class__.__module__, f.__self__.__class__.__name__, f.__name__
|
||||
)
|
||||
else:
|
||||
return "{}.{}".format(f.__module__, f.__name__)
|
||||
return f"{f.__module__}.{f.__name__}"
|
||||
|
||||
|
||||
def time_this(
|
||||
@@ -1971,33 +1970,38 @@ def time_this(
|
||||
expand_logtarget=False,
|
||||
message="{func} took {timing:.2f}ms",
|
||||
incl_func_args=False,
|
||||
log_enter=False,
|
||||
message_enter="Entering {func}...",
|
||||
):
|
||||
def decorator(f):
|
||||
func = fqfn(f)
|
||||
|
||||
lt = logtarget
|
||||
if expand_logtarget:
|
||||
lt += "." + func
|
||||
|
||||
logger = logging.getLogger(lt)
|
||||
|
||||
@wraps(f)
|
||||
def wrapper(*args, **kwargs):
|
||||
data = {"func": func, "func_args": "?", "func_kwargs": "?"}
|
||||
if incl_func_args and logger.isEnabledFor(logging.DEBUG):
|
||||
data.update(
|
||||
func_args=",".join(map(repr, args)),
|
||||
func_kwargs=",".join(
|
||||
map(lambda x: "{}={!r}".format(x[0], x[1]), kwargs.items())
|
||||
),
|
||||
)
|
||||
if log_enter:
|
||||
logger.debug(message_enter.format(**data), extra=data)
|
||||
|
||||
start = time.time()
|
||||
try:
|
||||
return f(*args, **kwargs)
|
||||
finally:
|
||||
timing = (time.time() - start) * 1000
|
||||
func = fqfn(f)
|
||||
|
||||
lt = logtarget
|
||||
if expand_logtarget:
|
||||
lt += "." + func
|
||||
|
||||
logger = logging.getLogger(lt)
|
||||
if logger.isEnabledFor(logging.DEBUG):
|
||||
data = {"func": func, "timing": timing}
|
||||
if incl_func_args:
|
||||
data.update(
|
||||
func_args=",".join(map(repr, args)),
|
||||
func_kwargs=",".join(
|
||||
map(
|
||||
lambda x: "{}={!r}".format(x[0], x[1]), kwargs.items()
|
||||
)
|
||||
),
|
||||
)
|
||||
data.update(timing=timing)
|
||||
logger.debug(message.format(**data), extra=data)
|
||||
|
||||
return wrapper
|
||||
|
||||
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user